!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.torque=e()}}(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o _) { this.time(0); } this.rescale(); return this; }, steps: function(_) { this.options.steps = _; return this.rescale(); }, step: function(s) { if(arguments.length === 0) return this.range(this.domain(this._time)); this._time = this.domainInv(this.rangeInv(s)); }, pause: function() { this.running = false; cancelAnimationFrame(this._tick); this.options.onPause && this.options.onPause(); }, _tick: function() { var t1 = +new Date(); var delta = (t1 - this._t0)*0.001; // if delta is really big means the tab lost the focus // at some point, so limit delta change delta = Math.min(this.options.maxDelta, delta); this._t0 = t1; this._time += delta; if(this.step() >= this.options.steps) { if(!this.options.loop){ // set time to max time this.time(this.options.animationDuration); this.pause(); } else { this._time = 0; } } if(this.running) { this.time(this._time); requestAnimationFrame(this._tick); } } }; module.exports = Animator; }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"./":10}],2:[function(require,module,exports){ var _torque_reference_latest = { "version": "1.0.0", "style": { "comp-op": { "css": "comp-op", "default-value": "src-over", "default-meaning": "add the current layer on top of other layers", "doc": "Composite operation. This defines how this layer should behave relative to layers atop or below it.", "type": [ "src", // "src-over", // "dst-over", // "src-in", // "dst-in", // "src-out", // "dst-out", // "src-atop", // "dst-atop", // "xor", // "darken", // "lighten" // ] } }, "layer" : { "buffer-size": { "default-value": "0", "type":"float", "default-meaning": "No buffer will be used", "doc": "Extra tolerance around the Layer extent (in pixels) used to when querying and (potentially) clipping the layer data during rendering" }, "-torque-clear-color": { "css": "-torque-clear-color", "type": "color", "default-value": "rgba(255, 255, 255, 0)", "default-meaning": "full clear", "doc": "color used to clear canvas on each frame" }, "-torque-frame-count": { "css": "-torque-frame-count", "default-value": "128", "type":"number", "default-meaning": "the data is broken into 128 time frames", "doc": "Number of animation steps/frames used in the animation. If the data contains a fewere number of total frames, the lesser value will be used." }, "-torque-resolution": { "css": "-torque-resolution", "default-value": "2", "type":"number", "default-meaning": "", "doc": "Spatial resolution in pixels. A resolution of 1 means no spatial aggregation of the data. Any other resolution of N results in spatial aggregation into cells of NxN pixels. The value N must be power of 2" }, "-torque-animation-duration": { "css": "-torque-animation-duration", "default-value": "30", "type":"number", "default-meaning": "the animation lasts 30 seconds", "doc": "Animation duration in seconds" }, "-torque-aggregation-function": { "css": "-torque-aggregation-function", "default-value": "count(cartodb_id)", "type": "string", "default-meaning": "the value for each cell is the count of points in that cell", "doc": "A function used to calculate a value from the aggregate data for each cell. See -torque-resolution" }, "-torque-time-attribute": { "css": "-torque-time-attribute", "default-value": "time", "type": "string", "default-meaning": "the data column in your table that is of a time based type", "doc": "The table column that contains the time information used create the animation" }, "-torque-data-aggregation": { "css": "-torque-data-aggregation", "default-value": "linear", "type": [ "cumulative" ], "default-meaning": "previous values are discarded", "doc": "A linear animation will discard previous values while a cumulative animation will accumulate them until it restarts" } }, "symbolizers" : { "*": { "comp-op": { "css": "comp-op", "default-value": "src-over", "default-meaning": "add the current layer on top of other layers", "doc": "Composite operation. This defines how this layer should behave relative to layers atop or below it.", "type": [ "src", // "src-over", // "dst-over", // "src-in", // "dst-in", // "src-out", // "dst-out", // "src-atop", // "dst-atop", // "xor", // "darken", // "lighten" // ] }, "opacity": { "css": "opacity", "type": "float", "doc": "An alpha value for the style (which means an alpha applied to all features in separate buffer and then composited back to main buffer)", "default-value": 1, "default-meaning": "no separate buffer will be used and no alpha will be applied to the style after rendering" } }, "trail": { "steps": { "css": "trail-steps", "type": "float", "default-value": 1, "default-meaning": "no trail steps", "doc": "How many steps of trails are going to be rendered" } }, "polygon": { "fill": { "css": "polygon-fill", "type": "color", "default-value": "rgba(128,128,128,1)", "default-meaning": "gray and fully opaque (alpha = 1), same as rgb(128,128,128)", "doc": "Fill color to assign to a polygon" }, "fill-opacity": { "css": "polygon-opacity", "type": "float", "doc": "The opacity of the polygon", "default-value": 1, "default-meaning": "opaque" } }, "line": { "stroke": { "css": "line-color", "default-value": "rgba(0,0,0,1)", "type": "color", "default-meaning": "black and fully opaque (alpha = 1), same as rgb(0,0,0)", "doc": "The color of a drawn line" }, "stroke-width": { "css": "line-width", "default-value": 1, "type": "float", "doc": "The width of a line in pixels" }, "stroke-opacity": { "css": "line-opacity", "default-value": 1, "type": "float", "default-meaning": "opaque", "doc": "The opacity of a line" }, "stroke-linejoin": { "css": "line-join", "default-value": "miter", "type": [ "miter", "round", "bevel" ], "doc": "The behavior of lines when joining" }, "stroke-linecap": { "css": "line-cap", "default-value": "butt", "type": [ "butt", "round", "square" ], "doc": "The display of line endings" } }, "markers": { "file": { "css": "marker-file", "doc": "An SVG file that this marker shows at each placement. If no file is given, the marker will show an ellipse.", "default-value": "", "default-meaning": "An ellipse or circle, if width equals height", "type": "uri" }, "opacity": { "css": "marker-opacity", "doc": "The overall opacity of the marker, if set, overrides both the opacity of both the fill and stroke", "default-value": 1, "default-meaning": "The stroke-opacity and fill-opacity will be used", "type": "float" }, "fill-opacity": { "css": "marker-fill-opacity", "doc": "The fill opacity of the marker", "default-value": 1, "default-meaning": "opaque", "type": "float" }, "stroke": { "css": "marker-line-color", "doc": "The color of the stroke around a marker shape.", "default-value": "black", "type": "color" }, "stroke-width": { "css": "marker-line-width", "doc": "The width of the stroke around a marker shape, in pixels. This is positioned on the boundary, so high values can cover the area itself.", "type": "float" }, "stroke-opacity": { "css": "marker-line-opacity", "default-value": 1, "default-meaning": "opaque", "doc": "The opacity of a line", "type": "float" }, "fill": { "css": "marker-fill", "default-value": "blue", "doc": "The color of the area of the marker.", "type": "color" }, "marker-type": { "css": "marker-type", "type": [ "rectangle", "ellipse" ], "default-value": "ellipse", "doc": "The default marker-type. If a SVG file is not given as the marker-file parameter, the renderer provides either an rectangle or an ellipse (a circle if height is equal to width)" }, "width": { "css": "marker-width", "default-value": 10, "doc": "The width of the marker, if using one of the default types.", "type": "float" } }, "point": { "file": { "css": "point-file", "type": "uri", "required": false, "default-value": "none", "doc": "Image file to represent a point" }, "opacity": { "css": "point-opacity", "type": "float", "default-value": 1.0, "default-meaning": "Fully opaque", "doc": "A value from 0 to 1 to control the opacity of the point" } } }, "colors": { "aliceblue": [240, 248, 255], "antiquewhite": [250, 235, 215], "aqua": [0, 255, 255], "aquamarine": [127, 255, 212], "azure": [240, 255, 255], "beige": [245, 245, 220], "bisque": [255, 228, 196], "black": [0, 0, 0], "blanchedalmond": [255,235,205], "blue": [0, 0, 255], "blueviolet": [138, 43, 226], "brown": [165, 42, 42], "burlywood": [222, 184, 135], "cadetblue": [95, 158, 160], "chartreuse": [127, 255, 0], "chocolate": [210, 105, 30], "coral": [255, 127, 80], "cornflowerblue": [100, 149, 237], "cornsilk": [255, 248, 220], "crimson": [220, 20, 60], "cyan": [0, 255, 255], "darkblue": [0, 0, 139], "darkcyan": [0, 139, 139], "darkgoldenrod": [184, 134, 11], "darkgray": [169, 169, 169], "darkgreen": [0, 100, 0], "darkgrey": [169, 169, 169], "darkkhaki": [189, 183, 107], "darkmagenta": [139, 0, 139], "darkolivegreen": [85, 107, 47], "darkorange": [255, 140, 0], "darkorchid": [153, 50, 204], "darkred": [139, 0, 0], "darksalmon": [233, 150, 122], "darkseagreen": [143, 188, 143], "darkslateblue": [72, 61, 139], "darkslategrey": [47, 79, 79], "darkturquoise": [0, 206, 209], "darkviolet": [148, 0, 211], "deeppink": [255, 20, 147], "deepskyblue": [0, 191, 255], "dimgray": [105, 105, 105], "dimgrey": [105, 105, 105], "dodgerblue": [30, 144, 255], "firebrick": [178, 34, 34], "floralwhite": [255, 250, 240], "forestgreen": [34, 139, 34], "fuchsia": [255, 0, 255], "gainsboro": [220, 220, 220], "ghostwhite": [248, 248, 255], "gold": [255, 215, 0], "goldenrod": [218, 165, 32], "gray": [128, 128, 128], "grey": [128, 128, 128], "green": [0, 128, 0], "greenyellow": [173, 255, 47], "honeydew": [240, 255, 240], "hotpink": [255, 105, 180], "indianred": [205, 92, 92], "indigo": [75, 0, 130], "ivory": [255, 255, 240], "khaki": [240, 230, 140], "lavender": [230, 230, 250], "lavenderblush": [255, 240, 245], "lawngreen": [124, 252, 0], "lemonchiffon": [255, 250, 205], "lightblue": [173, 216, 230], "lightcoral": [240, 128, 128], "lightcyan": [224, 255, 255], "lightgoldenrodyellow": [250, 250, 210], "lightgray": [211, 211, 211], "lightgreen": [144, 238, 144], "lightgrey": [211, 211, 211], "lightpink": [255, 182, 193], "lightsalmon": [255, 160, 122], "lightseagreen": [32, 178, 170], "lightskyblue": [135, 206, 250], "lightslategray": [119, 136, 153], "lightslategrey": [119, 136, 153], "lightsteelblue": [176, 196, 222], "lightyellow": [255, 255, 224], "lime": [0, 255, 0], "limegreen": [50, 205, 50], "linen": [250, 240, 230], "magenta": [255, 0, 255], "maroon": [128, 0, 0], "mediumaquamarine": [102, 205, 170], "mediumblue": [0, 0, 205], "mediumorchid": [186, 85, 211], "mediumpurple": [147, 112, 219], "mediumseagreen": [60, 179, 113], "mediumslateblue": [123, 104, 238], "mediumspringgreen": [0, 250, 154], "mediumturquoise": [72, 209, 204], "mediumvioletred": [199, 21, 133], "midnightblue": [25, 25, 112], "mintcream": [245, 255, 250], "mistyrose": [255, 228, 225], "moccasin": [255, 228, 181], "navajowhite": [255, 222, 173], "navy": [0, 0, 128], "oldlace": [253, 245, 230], "olive": [128, 128, 0], "olivedrab": [107, 142, 35], "orange": [255, 165, 0], "orangered": [255, 69, 0], "orchid": [218, 112, 214], "palegoldenrod": [238, 232, 170], "palegreen": [152, 251, 152], "paleturquoise": [175, 238, 238], "palevioletred": [219, 112, 147], "papayawhip": [255, 239, 213], "peachpuff": [255, 218, 185], "peru": [205, 133, 63], "pink": [255, 192, 203], "plum": [221, 160, 221], "powderblue": [176, 224, 230], "purple": [128, 0, 128], "red": [255, 0, 0], "rosybrown": [188, 143, 143], "royalblue": [65, 105, 225], "saddlebrown": [139, 69, 19], "salmon": [250, 128, 114], "sandybrown": [244, 164, 96], "seagreen": [46, 139, 87], "seashell": [255, 245, 238], "sienna": [160, 82, 45], "silver": [192, 192, 192], "skyblue": [135, 206, 235], "slateblue": [106, 90, 205], "slategray": [112, 128, 144], "slategrey": [112, 128, 144], "snow": [255, 250, 250], "springgreen": [0, 255, 127], "steelblue": [70, 130, 180], "tan": [210, 180, 140], "teal": [0, 128, 128], "thistle": [216, 191, 216], "tomato": [255, 99, 71], "turquoise": [64, 224, 208], "violet": [238, 130, 238], "wheat": [245, 222, 179], "white": [255, 255, 255], "whitesmoke": [245, 245, 245], "yellow": [255, 255, 0], "yellowgreen": [154, 205, 50], "transparent": [0, 0, 0, 0] } }; module.exports = { version: { latest: _torque_reference_latest, '1.0.0': _torque_reference_latest } }; },{}],3:[function(require,module,exports){ (function (global){ // // common functionallity for torque layers // var carto = global.carto || require('carto'); function TorqueLayer() {} TorqueLayer.prototype = { }; TorqueLayer.optionsFromLayer = function(mapConfig) { var opts = {}; if (!mapConfig) return opts; var attrs = { 'buffer-size': 'buffer-size', '-torque-frame-count': 'steps', '-torque-resolution': 'resolution', '-torque-animation-duration': 'animationDuration', '-torque-aggregation-function': 'countby', '-torque-time-attribute': 'column', '-torque-data-aggregation': 'data_aggregation' }; for (var i in attrs) { var v = mapConfig.eval(i); if (v !== undefined) { var a = attrs[i]; opts[a] = v; } } return opts; }; TorqueLayer.optionsFromCartoCSS = function(cartocss) { var shader = new carto.RendererJS().render(cartocss); var mapConfig = shader.findLayer({ name: 'Map' }); return TorqueLayer.optionsFromLayer(mapConfig); }; module.exports.TorqueLayer = TorqueLayer; }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"carto":36}],4:[function(require,module,exports){ (function (global){ var Event = {}; Event.on = function(evt, callback) { var cb = this._evt_callbacks = this._evt_callbacks || {}; var l = cb[evt] || (cb[evt] = []); l.push(callback); return this; }; Event.trigger = function(evt) { var c = this._evt_callbacks && this._evt_callbacks[evt]; for(var i = 0; c && i < c.length; ++i) { c[i].apply(this, Array.prototype.slice.call(arguments, 1)); } return this; }; Event.fire = Event.trigger; Event.off = function (evt, callback) { var c = this._evt_callbacks && this._evt_callbacks[evt]; if (c && !callback) { delete this._evt_callbacks[evt]; return this; } var remove = []; for(var i = 0; c && i < c.length; ++i) { if(c[i] === callback) remove.push(i); } while((i = remove.pop()) !== undefined) c.splice(i, 1); return this; }; Event.callbacks = function(evt) { return (this._evt_callbacks && this._evt_callbacks[evt]) || []; }; function extend() { var objs = arguments; var a = objs[0]; for (var i = 1; i < objs.length; ++i) { var b = objs[i]; for (var k in b) { a[k] = b[k]; } } return a; } function clone(a) { return extend({}, a); } function isFunction(f) { return typeof f == 'function' || false; } function isArray(value) { return value && typeof value == 'object' && Object.prototype.toString.call(value) == '[object Array]'; } // types var types = { Uint8Array: typeof(global['Uint8Array']) !== 'undefined' ? global.Uint8Array : Array, Uint32Array: typeof(global['Uint32Array']) !== 'undefined' ? global.Uint32Array : Array, Int32Array: typeof(global['Int32Array']) !== 'undefined' ? global.Int32Array: Array }; function isBrowserSupported() { return !!document.createElement('canvas'); } function userAgent() { return typeof navigator !== 'undefined' ? navigator.userAgent : ''; } var flags = { sprites_to_images: userAgent().indexOf('Safari') === -1 }; module.exports = { Event: Event, extend: extend, clone: clone, isFunction: isFunction, isArray: isArray, types: types, isBrowserSupported: isBrowserSupported, flags: flags }; }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{}],5:[function(require,module,exports){ /** * @license * Copyright 2013 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. */ /** * @fileoverview Extends OverlayView to provide a canvas "Layer". * @author Brendan Kenny */ /** * A map layer that provides a canvas over the slippy map and a callback * system for efficient animation. Requires canvas and CSS 2D transform * support. * @constructor * @extends google.maps.OverlayView * @param {CanvasLayerOptions=} opt_options Options to set in this CanvasLayer. */ function CanvasLayer(opt_options) { /** * If true, canvas is in a map pane and the OverlayView is fully functional. * See google.maps.OverlayView.onAdd for more information. * @type {boolean} * @private */ this.isAdded_ = false; /** * If true, each update will immediately schedule the next. * @type {boolean} * @private */ this.isAnimated_ = false; /** * The name of the MapPane in which this layer will be displayed. * @type {string} * @private */ this.paneName_ = CanvasLayer.DEFAULT_PANE_NAME_; /** * A user-supplied function called whenever an update is required. Null or * undefined if a callback is not provided. * @type {?function=} * @private */ this.updateHandler_ = null; /** * A user-supplied function called whenever an update is required and the * map has been resized since the last update. Null or undefined if a * callback is not provided. * @type {?function} * @private */ this.resizeHandler_ = null; /** * The LatLng coordinate of the top left of the current view of the map. Will * be null when this.isAdded_ is false. * @type {google.maps.LatLng} * @private */ this.topLeft_ = null; /** * The map-pan event listener. Will be null when this.isAdded_ is false. Will * be null when this.isAdded_ is false. * @type {?function} * @private */ this.centerListener_ = null; /** * The map-resize event listener. Will be null when this.isAdded_ is false. * @type {?function} * @private */ this.resizeListener_ = null; /** * If true, the map size has changed and this.resizeHandler_ must be called * on the next update. * @type {boolean} * @private */ this.needsResize_ = true; /** * A browser-defined id for the currently requested callback. Null when no * callback is queued. * @type {?number} * @private */ this.requestAnimationFrameId_ = null; var canvas = document.createElement('canvas'); canvas.style.position = 'absolute'; canvas.style.top = 0; canvas.style.left = 0; canvas.style.pointerEvents = 'none'; /** * The canvas element. * @type {!HTMLCanvasElement} */ this.canvas = canvas; /** * Simple bind for functions with no args for bind-less browsers (Safari). * @param {Object} thisArg The this value used for the target function. * @param {function} func The function to be bound. */ function simpleBindShim(thisArg, func) { return function() { func.apply(thisArg); }; } /** * A reference to this.repositionCanvas_ with this bound as its this value. * @type {function} * @private */ this.repositionFunction_ = simpleBindShim(this, this.repositionCanvas_); /** * A reference to this.resize_ with this bound as its this value. * @type {function} * @private */ this.resizeFunction_ = simpleBindShim(this, this.resize_); /** * A reference to this.update_ with this bound as its this value. * @type {function} * @private */ this.requestUpdateFunction_ = simpleBindShim(this, this.update_); // set provided options, if any if (opt_options) { this.setOptions(opt_options); } } CanvasLayer.prototype = new google.maps.OverlayView(); /** * The default MapPane to contain the canvas. * @type {string} * @const * @private */ CanvasLayer.DEFAULT_PANE_NAME_ = 'overlayLayer'; /** * Transform CSS property name, with vendor prefix if required. If browser * does not support transforms, property will be ignored. * @type {string} * @const * @private */ CanvasLayer.CSS_TRANSFORM_ = (function() { var div = document.createElement('div'); var transformProps = [ 'transform', 'WebkitTransform', 'MozTransform', 'OTransform', 'msTransform' ]; for (var i = 0; i < transformProps.length; i++) { var prop = transformProps[i]; if (div.style[prop] !== undefined) { return prop; } } // return unprefixed version by default return transformProps[0]; })(); /** * The requestAnimationFrame function, with vendor-prefixed or setTimeout-based * fallbacks. MUST be called with window as thisArg. * @type {function} * @param {function} callback The function to add to the frame request queue. * @return {number} The browser-defined id for the requested callback. * @private */ CanvasLayer.prototype.requestAnimFrame_ = window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || function(callback) { return window.setTimeout(callback, 1000 / 60); }; /** * The cancelAnimationFrame function, with vendor-prefixed fallback. Does not * fall back to clearTimeout as some platforms implement requestAnimationFrame * but not cancelAnimationFrame, and the cost is an extra frame on onRemove. * MUST be called with window as thisArg. * @type {function} * @param {number=} requestId The id of the frame request to cancel. * @private */ CanvasLayer.prototype.cancelAnimFrame_ = window.cancelAnimationFrame || window.webkitCancelAnimationFrame || window.mozCancelAnimationFrame || window.oCancelAnimationFrame || window.msCancelAnimationFrame || function(requestId) {}; /** * Sets any options provided. See CanvasLayerOptions for more information. * @param {CanvasLayerOptions} options The options to set. */ CanvasLayer.prototype.setOptions = function(options) { if (options.animate !== undefined) { this.setAnimate(options.animate); } if (options.paneName !== undefined) { this.setPane(options.paneName); } if (options.updateHandler !== undefined) { this.setUpdateHandler(options.updateHandler); } if (options.resizeHandler !== undefined) { this.setResizeHandler(options.resizeHandler); } if(options.readyHandler) { this.readyHandler = options.readyHandler; } }; /** * Set the animated state of the layer. If true, updateHandler will be called * repeatedly, once per frame. If false, updateHandler will only be called when * a map property changes that could require the canvas content to be redrawn. * @param {boolean} animate Whether the canvas is animated. */ CanvasLayer.prototype.setAnimate = function(animate) { this.isAnimated_ = !!animate; if (this.isAnimated_) { this.scheduleUpdate(); } }; /** * @return {boolean} Whether the canvas is animated. */ CanvasLayer.prototype.isAnimated = function() { return this.isAnimated_; }; /** * Set the MapPane in which this layer will be displayed, by name. See * {@code google.maps.MapPanes} for the panes available. * @param {string} paneName The name of the desired MapPane. */ CanvasLayer.prototype.setPaneName = function(paneName) { this.paneName_ = paneName; this.setPane_(); }; /** * @return {string} The name of the current container pane. */ CanvasLayer.prototype.getPaneName = function() { return this.paneName_; }; /** * Adds the canvas to the specified container pane. Since this is guaranteed to * execute only after onAdd is called, this is when paneName's existence is * checked (and an error is thrown if it doesn't exist). * @private */ CanvasLayer.prototype.setPane_ = function() { if (!this.isAdded_) { return; } // onAdd has been called, so panes can be used var panes = this.getPanes(); if (!panes[this.paneName_]) { throw new Error('"' + this.paneName_ + '" is not a valid MapPane name.'); } panes[this.paneName_].appendChild(this.canvas); }; /** * Set a function that will be called whenever the parent map and the overlay's * canvas have been resized. If opt_resizeHandler is null or unspecified, any * existing callback is removed. * @param {?function=} opt_resizeHandler The resize callback function. */ CanvasLayer.prototype.setResizeHandler = function(opt_resizeHandler) { this.resizeHandler_ = opt_resizeHandler; }; /** * Set a function that will be called when a repaint of the canvas is required. * If opt_updateHandler is null or unspecified, any existing callback is * removed. * @param {?function=} opt_updateHandler The update callback function. */ CanvasLayer.prototype.setUpdateHandler = function(opt_updateHandler) { this.updateHandler_ = opt_updateHandler; }; /** * @inheritDoc */ CanvasLayer.prototype.onAdd = function() { if (this.isAdded_) { return; } this.isAdded_ = true; this.setPane_(); this.resizeListener_ = google.maps.event.addListener(this.getMap(), 'resize', this.resizeFunction_); this.centerListener_ = google.maps.event.addListener(this.getMap(), 'center_changed', this.repositionFunction_); this.resize_(); this.repositionCanvas_(); this.readyHandler && this.readyHandler(); }; /** * @inheritDoc */ CanvasLayer.prototype.onRemove = function() { if (!this.isAdded_) { return; } this.isAdded_ = false; this.topLeft_ = null; // remove canvas and listeners for pan and resize from map this.canvas.parentElement.removeChild(this.canvas); if (this.centerListener_) { google.maps.event.removeListener(this.centerListener_); this.centerListener_ = null; } if (this.resizeListener_) { google.maps.event.removeListener(this.resizeListener_); this.resizeListener_ = null; } // cease canvas update callbacks if (this.requestAnimationFrameId_) { this.cancelAnimFrame_.call(window, this.requestAnimationFrameId_); this.requestAnimationFrameId_ = null; } }; /** * The internal callback for resize events that resizes the canvas to keep the * map properly covered. * @private */ CanvasLayer.prototype.resize_ = function() { // TODO(bckenny): it's common to use a smaller canvas but use CSS to scale // what is drawn by the browser to save on fill rate. Add an option to do // this. if (!this.isAdded_) { return; } var map = this.getMap(); var width = map.getDiv().offsetWidth; var height = map.getDiv().offsetHeight; var oldWidth = this.canvas.width; var oldHeight = this.canvas.height; // resizing may allocate a new back buffer, so do so conservatively if (oldWidth !== width || oldHeight !== height) { this.canvas.width = width; this.canvas.height = height; this.canvas.style.width = width + 'px'; this.canvas.style.height = height + 'px'; this.needsResize_ = true; this.scheduleUpdate(); } }; /** * @inheritDoc */ CanvasLayer.prototype.draw = function() { this.repositionCanvas_(); }; /** * Internal callback for map view changes. Since the Maps API moves the overlay * along with the map, this function calculates the opposite translation to * keep the canvas in place. * @private */ CanvasLayer.prototype.repositionCanvas_ = function() { // TODO(bckenny): *should* only be executed on RAF, but in current browsers // this causes noticeable hitches in map and overlay relative // positioning. var bounds = this.getMap().getBounds(); this.topLeft_ = new google.maps.LatLng(bounds.getNorthEast().lat(), bounds.getSouthWest().lng()); // canvas position relative to draggable map's conatainer depends on // overlayView's projection, not the map's var projection = this.getProjection(); var divTopLeft = projection.fromLatLngToDivPixel(this.topLeft_); // when the zoom level is low, more than one map can be shown in the screen // so the canvas should be attach to the map with more are in the screen var mapSize = (1 << this.getMap().getZoom())*256; if (Math.abs(divTopLeft.x) > mapSize) { divTopLeft.x -= mapSize; } this.canvas.style[CanvasLayer.CSS_TRANSFORM_] = 'translate(' + Math.round(divTopLeft.x) + 'px,' + Math.round(divTopLeft.y) + 'px)'; this.scheduleUpdate(); }; /** * Internal callback that serves as main animation scheduler via * requestAnimationFrame. Calls resize and update callbacks if set, and * schedules the next frame if overlay is animated. * @private */ CanvasLayer.prototype.update_ = function() { this.requestAnimationFrameId_ = null; if (!this.isAdded_) { return; } if (this.isAnimated_) { this.scheduleUpdate(); } if (this.needsResize_ && this.resizeHandler_) { this.needsResize_ = false; this.resizeHandler_(); } if (this.updateHandler_) { this.updateHandler_(); } }; /** * A convenience method to get the current LatLng coordinate of the top left of * the current view of the map. * @return {google.maps.LatLng} The top left coordinate. */ CanvasLayer.prototype.getTopLeft = function() { return this.topLeft_; }; /** * Schedule a requestAnimationFrame callback to updateHandler. If one is * already scheduled, there is no effect. */ CanvasLayer.prototype.scheduleUpdate = function() { if (this.isAdded_ && !this.requestAnimationFrameId_) { this.requestAnimationFrameId_ = this.requestAnimFrame_.call(window, this.requestUpdateFunction_); } }; module.exports = CanvasLayer; },{}],6:[function(require,module,exports){ /* ==================== canvas setup for drawing tiles ==================== */ function CanvasTileLayer(canvas_setup, render) { this.tileSize = new google.maps.Size(256, 256); this.maxZoom = 19; this.name = "Tile #s"; this.alt = "Canvas tile layer"; this.tiles = {}; this.canvas_setup = canvas_setup; this.render = render; if (!render) { this.render = canvas_setup; } } // create a tile with a canvas element CanvasTileLayer.prototype.create_tile_canvas = function (coord, zoom, ownerDocument) { // create canvas and reset style var canvas = ownerDocument.createElement('canvas'); var hit_canvas = ownerDocument.createElement('canvas'); canvas.style.border = hit_canvas.style.border = "none"; canvas.style.margin = hit_canvas.style.margin = "0"; canvas.style.padding = hit_canvas.style.padding = "0"; // prepare canvas and context sizes var ctx = canvas.getContext('2d'); ctx.width = canvas.width = this.tileSize.width; ctx.height = canvas.height = this.tileSize.height; var hit_ctx = hit_canvas.getContext('2d'); hit_canvas.width = hit_ctx.width = this.tileSize.width; hit_canvas.height = hit_ctx.height = this.tileSize.height; //set unique id var tile_id = coord.x + '_' + coord.y + '_' + zoom; canvas.setAttribute('id', tile_id); hit_canvas.setAttribute('id', tile_id); if (tile_id in this.tiles) delete this.tiles[tile_id]; this.tiles[tile_id] = {canvas:canvas, ctx:ctx, hit_canvas:hit_canvas, hit_ctx:hit_ctx, coord:coord, zoom:zoom, primitives:null}; // custom setup //if (tile_id == '19295_24654_16'){ if (this.canvas_setup) this.canvas_setup(this.tiles[tile_id], coord, zoom); //} return canvas; } CanvasTileLayer.prototype.each = function (callback) { for (var t in this.tiles) { var tile = this.tiles[t]; callback(tile); } } CanvasTileLayer.prototype.recreate = function () { for (var t in this.tiles) { var tile = this.tiles[t]; this.canvas_setup(tile, tile.coord, tile.zoom); } }; CanvasTileLayer.prototype.redraw_tile = function (tile) { this.render(tile, tile.coord, tile.zoom); }; CanvasTileLayer.prototype.redraw = function () { for (var t in this.tiles) { var tile = this.tiles[t]; this.render(tile, tile.coord, tile.zoom); } }; // could be called directly... CanvasTileLayer.prototype.getTile = function (coord, zoom, ownerDocument) { return this.create_tile_canvas(coord, zoom, ownerDocument); }; CanvasTileLayer.prototype.releaseTile = function (tile) { var id = tile.getAttribute('id'); delete this.tiles[id]; }; module.exports = CanvasTileLayer; },{}],7:[function(require,module,exports){ function GMapsTileLoader() { } GMapsTileLoader.prototype = { _initTileLoader: function(map, projection) { this._map = map; this._projection = projection; this._tiles = {}; this._tilesLoading = {}; this._tilesToLoad = 0; this._updateTiles = this._updateTiles.bind(this); this._listeners = []; this._listeners.push( google.maps.event.addListener(this._map, 'dragend', this._updateTiles), google.maps.event.addListener(this._map, 'zoom_changed', this._updateTiles) ); this.tileSize = 256; this._updateTiles(); }, _removeTileLoader: function() { for(var i in this._listeners) { google.maps.event.removeListener(this._listeners[i]); } this._removeTiles(); }, _removeTiles: function () { for (var key in this._tiles) { this._removeTile(key); } }, _reloadTiles: function() { this._removeTiles(); this._updateTiles(); }, _updateTiles: function () { if (!this._map) { return; } var bounds = this._map.getBounds(); var zoom = this._map.getZoom(); var tileSize = this.tileSize; var mzoom = (1 << zoom); var topLeft = new google.maps.LatLng( bounds.getNorthEast().lat(), bounds.getSouthWest().lng() ); var bottomRigth = new google.maps.LatLng( bounds.getSouthWest().lat(), bounds.getNorthEast().lng() ); this._projection = this._map.getProjection(); var divTopLeft = this._projection.fromLatLngToPoint(topLeft); var divBottomRight = this._projection.fromLatLngToPoint(bottomRigth); var nwTilePoint = new google.maps.Point( Math.floor(divTopLeft.x*mzoom / tileSize), Math.floor(divTopLeft.y*mzoom / tileSize)), seTilePoint = new google.maps.Point( Math.floor(divBottomRight.x*mzoom / tileSize), Math.floor(divBottomRight.y*mzoom / tileSize)); this._addTilesFromCenterOut(nwTilePoint, seTilePoint); this._removeOtherTiles(nwTilePoint, seTilePoint); }, _removeOtherTiles: function (nwTilePoint, seTilePoint) { var kArr, x, y, key; var zoom = this._map.getZoom(); for (key in this._tiles) { if (this._tiles.hasOwnProperty(key)) { kArr = key.split(':'); x = parseInt(kArr[0], 10); y = parseInt(kArr[1], 10); z = parseInt(kArr[2], 10); // remove tile if it's out of bounds if (z !== zoom || x < nwTilePoint.x || x > seTilePoint.x || y < nwTilePoint.y || y > seTilePoint.y) { this._removeTile(key); } } } }, _removeTile: function (key) { this.onTileRemoved && this.onTileRemoved(this._tiles[key]); delete this._tiles[key]; delete this._tilesLoading[key]; }, _tileKey: function(tilePoint) { return tilePoint.x + ':' + tilePoint.y + ':' + tilePoint.zoom; }, _tileShouldBeLoaded: function (tilePoint) { var k = this._tileKey(tilePoint); return !(k in this._tiles) && !(k in this._tilesLoading); }, _tileLoaded: function(tilePoint, tileData) { this._tilesToLoad--; var k = tilePoint.x + ':' + tilePoint.y + ':' + tilePoint.zoom this._tiles[k] = tileData; delete this._tilesLoading[k]; if(this._tilesToLoad === 0) { this.onTilesLoaded && this.onTilesLoaded(); } }, getTilePos: function (tilePoint) { var limit = (1 << this._map.getZoom()); // wrap tile tilePoint = { x: ((tilePoint.x % limit) + limit) % limit, y: tilePoint.y }; tilePoint = new google.maps.Point( tilePoint.x * this.tileSize, tilePoint.y * this.tileSize ); var bounds = this._map.getBounds(); var topLeft = new google.maps.LatLng( bounds.getNorthEast().lat(), bounds.getSouthWest().lng() ); var divTopLeft = this._map.getProjection().fromLatLngToPoint(topLeft); zoom = (1 << this._map.getZoom()); divTopLeft.x = divTopLeft.x * zoom; divTopLeft.y = divTopLeft.y * zoom; return new google.maps.Point( tilePoint.x - divTopLeft.x, tilePoint.y - divTopLeft.y ); }, _addTilesFromCenterOut: function (nwTilePoint, seTilePoint) { var queue = [], center = new google.maps.Point( (nwTilePoint.x + seTilePoint.x) * 0.5, (nwTilePoint.y + seTilePoint.y) * 0.5 ), zoom = this._map.getZoom(); var j, i, point; for (j = nwTilePoint.y; j <= seTilePoint.y; j++) { for (i = nwTilePoint.x; i <= seTilePoint.x; i++) { point = new google.maps.Point (i, j); point.zoom = zoom; if (this._tileShouldBeLoaded(point)) { queue.push(point); } } } var tilesToLoad = queue.length; if (tilesToLoad === 0) { return; } function distanceToCenterSq(point) { var dx = point.x - center.x; var dy = point.y - center.y; return dx * dx + dy * dy; } // load tiles in order of their distance to center queue.sort(function (a, b) { return distanceToCenterSq(a) - distanceToCenterSq(b); }); this._tilesToLoad += tilesToLoad; for (i = 0; i < tilesToLoad; i++) { var t = queue[i]; var k = this._tileKey(t); this._tilesLoading[k] = t; // events if (this.onTileAdded) { this.onTileAdded(t); } } this.onTilesLoading && this.onTilesLoading(); } } module.exports = GMapsTileLoader; },{}],8:[function(require,module,exports){ var gmaps = {}; if (typeof google !== 'undefined' && typeof google.maps !== 'undefined') { gmaps = require('./torque'); gmaps.GMapsTileLoader = require('./gmaps_tileloader_mixin'); } module.exports = gmaps; },{"./gmaps_tileloader_mixin":7,"./torque":9}],9:[function(require,module,exports){ (function (global){ var carto = global.carto || require('carto'); var torque = require('../'); var CanvasLayer = require('./CanvasLayer'); var CanvasTileLayer = require('./canvas_tile_layer'); var GMapsTileLoader = require('./gmaps_tileloader_mixin'); function GMapsTorqueLayer(options) { var self = this; if (!torque.isBrowserSupported()) { throw new Error("browser is not supported by torque"); } this.key = 0; this.shader = null; this.ready = false; this.options = torque.extend({}, options); this.options = torque.extend({ provider: 'windshaft', renderer: 'point', resolution: 2, steps: 100, visible: true }, this.options); if (options.cartocss) { torque.extend(this.options, torque.common.TorqueLayer.optionsFromCartoCSS(options.cartocss)); } this.hidden = !this.options.visible; this.animator = new torque.Animator(function(time) { var k = time | 0; if(self.key !== k) { self.setKey(k); } }, torque.clone(this.options)); this.play = this.animator.start.bind(this.animator); this.stop = this.animator.stop.bind(this.animator); this.pause = this.animator.pause.bind(this.animator); this.toggle = this.animator.toggle.bind(this.animator); this.setDuration = this.animator.duration.bind(this.animator); this.isRunning = this.animator.isRunning.bind(this.animator); CanvasLayer.call(this, { map: this.options.map, //resizeHandler: this.redraw, animate: false, updateHandler: this.render, readyHandler: this.initialize }); } /** * torque layer */ GMapsTorqueLayer.prototype = torque.extend({}, CanvasLayer.prototype, GMapsTileLoader.prototype, torque.Event, { providers: { 'sql_api': torque.providers.json, 'url_template': torque.providers.jsonarray, 'windshaft': torque.providers.windshaft }, renderers: { 'point': torque.renderer.Point, 'pixel': torque.renderer.Rectangle }, initialize: function() { var self = this; this.onTileAdded = this.onTileAdded.bind(this); this.options.ready = function() { self.fire("change:bounds", { bounds: self.provider.getBounds() }); self.animator.steps(self.provider.getSteps()); self.animator.rescale(); self.fire('change:steps', { steps: self.provider.getSteps() }); self.setKey(self.key); }; this.provider = new this.providers[this.options.provider](this.options); this.renderer = new this.renderers[this.options.renderer](this.getCanvas(), this.options); // this listener should be before tile loader this._cacheListener = google.maps.event.addListener(this.options.map, 'zoom_changed', function() { self.renderer && self.renderer.clearSpriteCache(); }); this._initTileLoader(this.options.map, this.getProjection()); if (this.shader) { this.renderer.setShader(this.shader); } }, hide: function() { if(this.hidden) return this; this.pause(); this.clear(); this.hidden = true; return this; }, show: function() { if(!this.hidden) return this; this.hidden = false; this.play(); return this; }, setSQL: function(sql) { if (!this.provider || !this.provider.setSQL) { throw new Error("this provider does not support SQL"); } this.provider.setSQL(sql); this._reloadTiles(); return this; }, setBlendMode: function(_) { this.renderer && this.renderer.setBlendMode(_); this.redraw(); }, setSteps: function(steps) { this.provider && this.provider.setSteps(steps); this.animator && this.animator.steps(steps); this._reloadTiles(); }, setColumn: function(column, isTime) { this.provider && this.provider.setColumn(column, isTime); this._reloadTiles(); }, getTimeBounds: function() { return this.provider && this.provider.getKeySpan(); }, getCanvas: function() { return this.canvas; }, // for each tile shown on the map request the data onTileAdded: function(t) { var self = this; this.provider.getTileData(t, t.zoom, function(tileData) { // don't load tiles that are not being shown if (t.zoom !== self.options.map.getZoom()) return; self._tileLoaded(t, tileData); if (tileData) { self.redraw(); } }); }, clear: function() { var canvas = this.canvas; canvas.width = canvas.width; }, /** * render the selectef key * don't call this function directly, it's called by * requestAnimationFrame. Use redraw to refresh it */ render: function() { if(this.hidden) return; var t, tile, pos; var canvas = this.canvas; this.renderer.clearCanvas(); var ctx = canvas.getContext('2d'); // renders only a "frame" for(t in this._tiles) { tile = this._tiles[t]; if (tile) { pos = this.getTilePos(tile.coord); ctx.setTransform(1, 0, 0, 1, pos.x, pos.y); this.renderer.renderTile(tile, this.key, pos.x, pos.y); } } }, getActivePointsBBox: function(step) { var positions = []; var tileMax = this.options.resolution * (256/this.options.resolution - 1); for(var t in this._tiles) { var tile = this._tiles[t]; positions = positions.concat(this.renderer.getActivePointsBBox(tile, step)); } return positions; }, /** * set key to be shown. If it's a single value * it renders directly, if it's an array it renders * accumulated */ setKey: function(key) { this.key = key; this.animator.step(key); this.redraw(); this.fire('change:time', { time: this.getTime(), step: this.key }); }, /** * helper function, does the same than ``setKey`` but only * accepts scalars. */ setStep: function(time) { if(time === undefined || time.length !== undefined) { throw new Error("setTime only accept scalars"); } this.setKey(time); }, /** * transform from animation step to Date object * that contains the animation time * * ``step`` should be between 0 and ``steps - 1`` */ stepToTime: function(step) { if (!this.provider) return 0; var times = this.provider.getKeySpan(); var time = times.start + (times.end - times.start)*(step/this.provider.getSteps()); return new Date(time); }, timeToStep: function(timestamp) { if (typeof timestamp === "Date") timestamp = timestamp.getTime(); if (!this.provider) return 0; var times = this.provider.getKeySpan(); var step = (this.provider.getSteps() * (timestamp - times.start)) / (times.end - times.start); return step; }, getStep: function() { return this.key; }, /** * returns the animation time defined by the data * in the defined column. Date object */ getTime: function() { return this.stepToTime(this.key); }, /** * set the cartocss for the current renderer */ setCartoCSS: function(cartocss) { var shader = new carto.RendererJS().render(cartocss); this.shader = shader; if (this.renderer) { this.renderer.setShader(shader); } // provider options var options = torque.common.TorqueLayer.optionsFromLayer(shader.findLayer({ name: 'Map' })); this.provider && this.provider.setCartoCSS && this.provider.setCartoCSS(cartocss); if(this.provider && this.provider.setOptions(options)) { this._reloadTiles(); } torque.extend(this.options, options); // animator options if (options.animationDuration) { this.animator.duration(options.animationDuration); } this.redraw(); return this; }, redraw: function() { this.scheduleUpdate(); }, onRemove: function() { CanvasLayer.prototype.onRemove.call(this); this.animator.stop(); this._removeTileLoader(); google.maps.event.removeListener(this._cacheListener); } }); function GMapsTiledTorqueLayer(options) { this.options = torque.extend({}, options); CanvasTileLayer.call(this, this._loadTile.bind(this), this.drawTile.bind(this)); this.initialize(options); } GMapsTiledTorqueLayer.prototype = torque.extend({}, CanvasTileLayer.prototype, { providers: { 'sql_api': torque.providers.json, 'url_template': torque.providers.JsonArray }, renderers: { 'point': torque.renderer.Point, 'pixel': torque.renderer.Rectangle }, initialize: function(options) { var self = this; this.key = 0; this.options.renderer = this.options.renderer || 'pixel'; this.options.provider = this.options.provider || 'sql_api'; this.provider = new this.providers[this.options.provider](options); this.renderer = new this.renderers[this.options.renderer](null, options); }, _tileLoaded: function(tile, tileData) { tile.data = tileData; this.drawTile(tile); }, _loadTile: function(tile, coord, zoom) { var self = this; var limit = 1 << zoom; // wrap tile var wrappedCoord = { x: ((coord.x % limit) + limit) % limit, y: coord.y }; this.provider.getTileData(wrappedCoord, zoom, function(tileData) { self._tileLoaded(tile, tileData); }); }, drawTile: function (tile) { var canvas = tile.canvas; if(!tile.data) return; canvas.width = canvas.width; this.renderer.setCanvas(canvas); var accum = this.renderer.accumulate(tile.data, this.key); this.renderer.renderTileAccum(accum, 0, 0); }, setKey: function(key) { this.key = key; this.redraw(); }, /** * set the cartocss for the current renderer */ setCartoCSS: function(cartocss) { if (!this.renderer) throw new Error('renderer is not valid'); return this.renderer.setCartoCSS(cartocss); } }); module.exports = { GMapsTiledTorqueLayer: GMapsTiledTorqueLayer, GMapsTorqueLayer: GMapsTorqueLayer }; }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"../":10,"./CanvasLayer":5,"./canvas_tile_layer":6,"./gmaps_tileloader_mixin":7,"carto":36}],10:[function(require,module,exports){ module.exports = require('./core'); module.exports.Animator = require('./animator'); module.exports.cartocss_reference = require('./cartocss_reference'); module.exports.common = require('./common'); module.exports.math = require('./math'); module.exports.Mercator = require('./mercator'); module.exports.net = require('./request'); module.exports.renderer = require('./renderer'); module.exports.providers = require('./provider'); require('./leaflet'); var gmaps = require('./gmaps'); module.exports.GMapsTileLoader = gmaps.GMapsTileLoader; module.exports.GMapsTorqueLayer = gmaps.GMapsTorqueLayer; module.exports.GMapsTiledTorqueLayer = gmaps.GMapsTiledTorqueLayer; },{"./animator":1,"./cartocss_reference":2,"./common":3,"./core":4,"./gmaps":8,"./leaflet":12,"./math":15,"./mercator":16,"./provider":18,"./renderer":23,"./request":27}],11:[function(require,module,exports){ require('./leaflet_tileloader_mixin'); /** * full canvas layer implementation for Leaflet */ L.CanvasLayer = L.Class.extend({ includes: [L.Mixin.Events, L.Mixin.TileLoader], options: { minZoom: 0, maxZoom: 28, tileSize: 256, subdomains: 'abc', errorTileUrl: '', attribution: '', zoomOffset: 0, opacity: 1, unloadInvisibleTiles: L.Browser.mobile, updateWhenIdle: L.Browser.mobile, tileLoader: false, // installs tile loading events zoomAnimation: true }, initialize: function (options) { var self = this; options = options || {}; //this.project = this._project.bind(this); this.render = this.render.bind(this); L.Util.setOptions(this, options); this._canvas = this._createCanvas(); // backCanvas for zoom animation if (this.options.zoomAnimation) { this._backCanvas = this._createCanvas(); } this._ctx = this._canvas.getContext('2d'); this.currentAnimationFrame = -1; this.requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame || function(callback) { return window.setTimeout(callback, 1000 / 60); }; this.cancelAnimationFrame = window.cancelAnimationFrame || window.mozCancelAnimationFrame || window.webkitCancelAnimationFrame || window.msCancelAnimationFrame || function(id) { clearTimeout(id); }; }, _createCanvas: function() { var canvas; canvas = document.createElement('canvas'); canvas.style.position = 'absolute'; canvas.style.top = 0; canvas.style.left = 0; canvas.style.pointerEvents = "none"; canvas.style.zIndex = this.options.zIndex || 0; var className = 'leaflet-tile-container'; if (this.options.zoomAnimation) { className += ' leaflet-zoom-animated'; } canvas.setAttribute('class', className); return canvas; }, onAdd: function (map) { this._map = map; // add container with the canvas to the tile pane // the container is moved in the oposite direction of the // map pane to keep the canvas always in (0, 0) var tilePane = this._map._panes.tilePane; var _container = L.DomUtil.create('div', 'leaflet-layer'); _container.appendChild(this._canvas); if (this.options.zoomAnimation) { _container.appendChild(this._backCanvas); this._backCanvas.style.display = 'none'; } tilePane.appendChild(_container); this._container = _container; // hack: listen to predrag event launched by dragging to // set container in position (0, 0) in screen coordinates map.dragging._draggable.on('predrag', function() { var d = map.dragging._draggable; L.DomUtil.setPosition(this._canvas, { x: -d._newPos.x, y: -d._newPos.y }); }, this); map.on({ 'viewreset': this._reset }, this); map.on('move', this.render, this); map.on('resize', this._reset, this); if (this.options.zoomAnimation) { map.on({ 'zoomanim': this._animateZoom, 'zoomend': this._endZoomAnim, 'moveend': this._reset }, this); } if(this.options.tileLoader) { this._initTileLoader(); } this._reset(); }, _animateZoom: function (e) { if (!this._animating) { this._animating = true; } var back = this._backCanvas; back.width = this._canvas.width; back.height = this._canvas.height; // paint current canvas in back canvas with trasnformation var pos = this._canvas._leaflet_pos || { x: 0, y: 0 }; back.getContext('2d').drawImage(this._canvas, 0, 0); L.DomUtil.setPosition(back, L.DomUtil.getPosition(this._canvas)); // hide original this._canvas.style.display = 'none'; back.style.display = 'block'; var map = this._map; var scale = map.getZoomScale(e.zoom); var newCenter = map._latLngToNewLayerPoint(map.getCenter(), e.zoom, e.center); var oldCenter = map._latLngToNewLayerPoint(e.center, e.zoom, e.center); var origin = { x: newCenter.x - oldCenter.x + pos.x, y: newCenter.y - oldCenter.y + pos.y, }; var bg = back; var transform = L.DomUtil.TRANSFORM; setTimeout(function() { bg.style[transform] = L.DomUtil.getTranslateString(origin) + ' scale(' + e.scale + ') '; }, 0) }, _endZoomAnim: function () { this._animating = false; this._canvas.style.display = 'block'; this._backCanvas.style.display = 'none'; this._backCanvas.style[L.DomUtil.TRANSFORM] = ''; }, getCanvas: function() { return this._canvas; }, getAttribution: function() { return this.options.attribution; }, draw: function() { return this._reset(); }, onRemove: function (map) { this._container.parentNode.removeChild(this._container); map.off({ 'viewreset': this._reset, 'move': this._render, 'moveend': this._reset, 'resize': this._reset, 'zoomanim': this._animateZoom, 'zoomend': this._endZoomAnim }, this); }, addTo: function (map) { map.addLayer(this); return this; }, setOpacity: function (opacity) { this.options.opacity = opacity; this._updateOpacity(); return this; }, setZIndex: function(zIndex) { this._canvas.style.zIndex = zIndex; if (this.options.zoomAnimation) { this._backCanvas.style.zIndex = zIndex; } }, bringToFront: function () { return this; }, bringToBack: function () { return this; }, _reset: function () { var size = this._map.getSize(); this._canvas.width = size.x; this._canvas.height = size.y; // fix position var pos = L.DomUtil.getPosition(this._map.getPanes().mapPane); if (pos) { L.DomUtil.setPosition(this._canvas, { x: -pos.x, y: -pos.y }); } this.onResize(); this._render(); }, /* _project: function(x) { var point = this._map.latLngToLayerPoint(new L.LatLng(x[1], x[0])); return [point.x, point.y]; }, */ _updateOpacity: function () { }, _render: function() { if (this.currentAnimationFrame >= 0) { this.cancelAnimationFrame.call(window, this.currentAnimationFrame); } this.currentAnimationFrame = this.requestAnimationFrame.call(window, this.render); }, // use direct: true if you are inside an animation frame call redraw: function(direct) { if (direct) { this.render(); } else { this._render(); } }, onResize: function() { }, render: function() { throw new Error('render function should be implemented'); } }); },{"./leaflet_tileloader_mixin":13}],12:[function(require,module,exports){ if (typeof L !== 'undefined') { require('./torque'); } },{"./torque":14}],13:[function(require,module,exports){ L.Mixin.TileLoader = { _initTileLoader: function() { this._tiles = {} this._tilesLoading = {}; this._tilesToLoad = 0; this._map.on({ 'moveend': this._updateTiles }, this); this._updateTiles(); }, _removeTileLoader: function() { this._map.off({ 'moveend': this._updateTiles }, this); this._removeTiles(); }, _updateTiles: function () { if (!this._map) { return; } var bounds = this._map.getPixelBounds(), zoom = this._map.getZoom(), tileSize = this.options.tileSize; if (zoom > this.options.maxZoom || zoom < this.options.minZoom) { return; } var nwTilePoint = new L.Point( Math.floor(bounds.min.x / tileSize), Math.floor(bounds.min.y / tileSize)), seTilePoint = new L.Point( Math.floor(bounds.max.x / tileSize), Math.floor(bounds.max.y / tileSize)), tileBounds = new L.Bounds(nwTilePoint, seTilePoint); this._addTilesFromCenterOut(tileBounds); this._removeOtherTiles(tileBounds); }, _removeTiles: function (bounds) { for (var key in this._tiles) { this._removeTile(key); } }, _reloadTiles: function() { this._removeTiles(); this._updateTiles(); }, _removeOtherTiles: function (bounds) { var kArr, x, y, z, key; var zoom = this._map.getZoom(); for (key in this._tiles) { if (this._tiles.hasOwnProperty(key)) { kArr = key.split(':'); x = parseInt(kArr[0], 10); y = parseInt(kArr[1], 10); z = parseInt(kArr[2], 10); // remove tile if it's out of bounds if (zoom !== z || x < bounds.min.x || x > bounds.max.x || y < bounds.min.y || y > bounds.max.y) { this._removeTile(key); } } } }, _removeTile: function (key) { this.fire('tileRemoved', this._tiles[key]); delete this._tiles[key]; delete this._tilesLoading[key]; }, _tileKey: function(tilePoint) { return tilePoint.x + ':' + tilePoint.y + ':' + tilePoint.zoom; }, _tileShouldBeLoaded: function (tilePoint) { var k = this._tileKey(tilePoint); return !(k in this._tiles) && !(k in this._tilesLoading); }, _tileLoaded: function(tilePoint, tileData) { this._tilesToLoad--; var k = tilePoint.x + ':' + tilePoint.y + ':' + tilePoint.zoom this._tiles[k] = tileData; delete this._tilesLoading[k]; if(this._tilesToLoad === 0) { this.fire("tilesLoaded"); } }, getTilePos: function (tilePoint) { tilePoint = new L.Point(tilePoint.x, tilePoint.y); var origin = this._map._getNewTopLeftPoint(this._map.getCenter()), tileSize = this.options.tileSize; return tilePoint.multiplyBy(tileSize).subtract(origin); }, _addTilesFromCenterOut: function (bounds) { var queue = [], center = bounds.getCenter(), zoom = this._map.getZoom(); var j, i, point; for (j = bounds.min.y; j <= bounds.max.y; j++) { for (i = bounds.min.x; i <= bounds.max.x; i++) { point = new L.Point(i, j); point.zoom = zoom; if (this._tileShouldBeLoaded(point)) { queue.push(point); } } } var tilesToLoad = queue.length; if (tilesToLoad === 0) { return; } // load tiles in order of their distance to center queue.sort(function (a, b) { return a.distanceTo(center) - b.distanceTo(center); }); this._tilesToLoad += tilesToLoad; for (i = 0; i < tilesToLoad; i++) { var t = queue[i]; var k = this._tileKey(t); this._tilesLoading[k] = t; this.fire('tileAdded', t); } this.fire("tilesLoading"); } } },{}],14:[function(require,module,exports){ (function (global){ var carto = global.carto || require('carto'); var torque = require('../'); require('./canvas_layer'); /** * torque layer */ L.TorqueLayer = L.CanvasLayer.extend({ providers: { 'sql_api': torque.providers.json, 'url_template': torque.providers.jsonarray, 'windshaft': torque.providers.windshaft }, renderers: { 'point': torque.renderer.Point, 'pixel': torque.renderer.Rectangle }, initialize: function(options) { var self = this; if (!torque.isBrowserSupported()) { throw new Error("browser is not supported by torque"); } options.tileLoader = true; this.key = 0; this.prevRenderedKey = 0; if (options.cartocss) { torque.extend(options, torque.common.TorqueLayer.optionsFromCartoCSS(options.cartocss)); } options.resolution = options.resolution || 2; options.steps = options.steps || 100; options.visible = options.visible === undefined ? true: options.visible; this.hidden = !options.visible; this.animator = new torque.Animator(function(time) { var k = time | 0; if(self.key !== k) { self.setKey(k, { direct: true }); } }, torque.extend(torque.clone(options), { onPause: function() { self.fire('pause'); }, onStop: function() { self.fire('stop'); }, onStart: function() { self.fire('play'); } })); this.play = this.animator.start.bind(this.animator); this.stop = this.animator.stop.bind(this.animator); this.pause = this.animator.pause.bind(this.animator); this.toggle = this.animator.toggle.bind(this.animator); this.setDuration = this.animator.duration.bind(this.animator); this.isRunning = this.animator.isRunning.bind(this.animator); L.CanvasLayer.prototype.initialize.call(this, options); this.options.renderer = this.options.renderer || 'point'; this.options.provider = this.options.provider || 'windshaft'; options.ready = function() { self.fire("change:bounds", { bounds: self.provider.getBounds() }); self.animator.steps(self.provider.getSteps()); self.animator.rescale(); self.fire('change:steps', { steps: self.provider.getSteps() }); self.setKey(self.key); }; this.provider = new this.providers[this.options.provider](options); this.renderer = new this.renderers[this.options.renderer](this.getCanvas(), options); this.renderer.on("allIconsLoaded", this.render.bind(this)); // for each tile shown on the map request the data this.on('tileAdded', function(t) { var tileData = this.provider.getTileData(t, t.zoom, function(tileData) { // don't load tiles that are not being shown if (t.zoom !== self._map.getZoom()) return; self._tileLoaded(t, tileData); self._clearTileCaches(); if (tileData) { self.redraw(); } }); }, this); }, _clearTileCaches: function() { var t, tile; for(t in this._tiles) { tile = this._tiles[t]; if (tile && tile._tileCache) { tile._tileCache = null; } } }, _clearCaches: function() { this.renderer && this.renderer.clearSpriteCache(); this._clearTileCaches(); }, onAdd: function (map) { map.on({ 'zoomend': this._clearCaches, 'zoomstart': this._pauseOnZoom, }, this); map.on({ 'zoomend': this._resumeOnZoom }, this); L.CanvasLayer.prototype.onAdd.call(this, map); }, onRemove: function(map) { this._removeTileLoader(); map.off({ 'zoomend': this._clearCaches, 'zoomstart': this._pauseOnZoom, }, this); map.off({ 'zoomend': this._resumeOnZoom }, this); L.CanvasLayer.prototype.onRemove.call(this, map); }, _pauseOnZoom: function() { this.wasRunning = this.isRunning(); if (this.wasRunning) { this.pause(); } }, _resumeOnZoom: function() { if (this.wasRunning) { this.play(); } }, hide: function() { if(this.hidden) return this; this.pause(); this.clear(); this.hidden = true; return this; }, show: function() { if(!this.hidden) return this; this.hidden = false; this.play(); return this; }, setSQL: function(sql) { if (!this.provider || !this.provider.setSQL) { throw new Error("this provider does not support SQL"); } this.provider.setSQL(sql); this._reloadTiles(); return this; }, setBlendMode: function(_) { this.renderer.setBlendMode(_); this.redraw(); }, setSteps: function(steps) { this.provider.setSteps(steps); this._reloadTiles(); }, setColumn: function(column, isTime) { this.provider.setColumn(column, isTime); this._reloadTiles(); }, getTimeBounds: function() { return this.provider && this.provider.getKeySpan(); }, clear: function() { var canvas = this.getCanvas(); canvas.width = canvas.width; }, /** * render the selectef key * don't call this function directly, it's called by * requestAnimationFrame. Use redraw to refresh it */ render: function() { if(this.hidden) return; var t, tile, pos; var canvas = this.getCanvas(); this.renderer.clearCanvas(); var ctx = canvas.getContext('2d'); for(t in this._tiles) { tile = this._tiles[t]; if (tile) { // clear cache if (this.animator.isRunning()) { tile._tileCache = null; } pos = this.getTilePos(tile.coord); ctx.setTransform(1, 0, 0, 1, pos.x, pos.y); if (tile._tileCache) { // when the tile has a cached image just render it and avoid to render // all the points this.renderer._ctx.drawImage(tile._tileCache, 0, 0); } else { this.renderer.renderTile(tile, this.key); } } } this.renderer.applyFilters(); // prepare caches if the animation is not running // don't cache if the key has just changed, this avoids to cache // when the user is dragging, it only cache when the map is still if (!this.animator.isRunning() && this.key === this.prevRenderedKey) { var tile_size = this.renderer.TILE_SIZE; for(t in this._tiles) { tile = this._tiles[t]; if (tile && !tile._tileCache) { var c = tile._tileCache = document.createElement('canvas'); c.width = c.height = tile_size; pos = this.getTilePos(tile.coord); // clip bounds, firefox raise an exception when try to get data from outside canvas var x = Math.max(0, pos.x) var y = Math.max(0, pos.y) var w = Math.min(tile_size, this.getCanvas().width - x); var h = Math.min(tile_size, this.getCanvas().height - y); if (w > 0 && h > 0) { c.getContext('2d').drawImage(this.getCanvas(), x, y, w, h, x - pos.x, y - pos.y, w, h); } } } } this.prevRenderedKey = this.key; }, /** * set key to be shown. If it's a single value * it renders directly, if it's an array it renders * accumulated */ setKey: function(key, options) { this.key = key; this.animator.step(key); this._clearTileCaches(); this.redraw(options && options.direct); this.fire('change:time', { time: this.getTime(), step: this.key }); }, /** * helper function, does the same than ``setKey`` but only * accepts scalars. */ setStep: function(time) { if(time === undefined || time.length !== undefined) { throw new Error("setTime only accept scalars"); } this.setKey(time); }, /** * transform from animation step to Date object * that contains the animation time * * ``step`` should be between 0 and ``steps - 1`` */ stepToTime: function(step) { var times = this.provider.getKeySpan(); var time = times.start + (times.end - times.start)*(step/this.provider.getSteps()); return new Date(time); }, timeToStep: function(timestamp) { if (typeof timestamp === "Date") timestamp = timestamp.getTime(); if (!this.provider) return 0; var times = this.provider.getKeySpan(); var step = (this.provider.getSteps() * (timestamp - times.start)) / (times.end - times.start); return step; }, getStep: function() { return this.key; }, /** * returns the animation time defined by the data * in the defined column. Date object */ getTime: function() { return this.stepToTime(this.key); }, /** * returns an object with the start and end times */ getTimeSpan: function() { return this.provider.getKeySpan(); }, /** * set the cartocss for the current renderer */ setCartoCSS: function(cartocss) { if (!this.renderer) throw new Error('renderer is not valid'); var shader = new carto.RendererJS().render(cartocss); this.renderer.setShader(shader); // provider options var options = torque.common.TorqueLayer.optionsFromLayer(shader.findLayer({ name: 'Map' })); this.provider.setCartoCSS && this.provider.setCartoCSS(cartocss); if(this.provider.setOptions(options)) { this._reloadTiles(); } torque.extend(this.options, options); // animator options if (options.animationDuration) { this.animator.duration(options.animationDuration); } this._clearCaches(); this.redraw(); return this; }, /** * get active points for a step in active zoom * returns a list of bounding boxes [[] , [], []] * empty list if there is no active pixels */ getActivePointsBBox: function(step) { var positions = []; for(var t in this._tiles) { var tile = this._tiles[t]; positions = positions.concat(this.renderer.getActivePointsBBox(tile, step)); } return positions; }, /** * return the value for position relative to map coordinates. null for no value */ getValueForPos: function(x, y, step) { step = step === undefined ? this.key: step; var t, tile, pos, value = null, xx, yy; for(t in this._tiles) { tile = this._tiles[t]; pos = this.getTilePos(tile.coord); xx = x - pos.x; yy = y - pos.y; if (xx >= 0 && yy >= 0 && xx < this.renderer.TILE_SIZE && yy <= this.renderer.TILE_SIZE) { value = this.renderer.getValueFor(tile, step, xx, yy); } if (value !== null) { return value; } } return null; }, invalidate: function() { this.provider.reload(); } }); }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"../":10,"./canvas_layer":11,"carto":36}],15:[function(require,module,exports){ function clamp(a, b) { return function(t) { return Math.max(Math.min(t, b), a); }; } function invLinear(a, b) { var c = clamp(0, 1.0); return function(t) { return c((t - a)/(b - a)); }; } function linear(a, b) { var c = clamp(a, b); function _linear(t) { return c(a*(1.0 - t) + t*b); } _linear.invert = function() { return invLinear(a, b); }; return _linear; } module.exports = { clamp: clamp, linear: linear, invLinear: invLinear }; },{}],16:[function(require,module,exports){ var Point = function(x, y) { this.x = x || 0; this.y = y || 0; }; function clamp(value, optMin, optMax) { if (optMin !== null) value = Math.max(value, optMin); if (optMax !== null) value = Math.min(value, optMax); return value; } function degreesToRadians(deg) { return deg * (Math.PI / 180); } function radiansToDegrees(rad) { return rad / (Math.PI / 180); } var MercatorProjection = function() { // this._tileSize = L.Browser.retina ? 512 : 256; this._tileSize = 256; this._pixelOrigin = new Point(this._tileSize / 2, this._tileSize / 2); this._pixelsPerLonDegree = this._tileSize / 360; this._pixelsPerLonRadian = this._tileSize / (2 * Math.PI); }; MercatorProjection.prototype._fromLatLonToPoint = function(lat, lon) { var point = new Point(0, 0); var origin = this._pixelOrigin; point.x = origin.x + lon * this._pixelsPerLonDegree; // NOTE(appleton): Truncating to 0.9999 effectively limits latitude to // 89.189. This is about a third of a tile past the edge of the world // tile. var siny = clamp(Math.sin(degreesToRadians(lat)), -0.9999, 0.9999); point.y = origin.y + 0.5 * Math.log((1 + siny) / (1 - siny)) * -this._pixelsPerLonRadian; return point; }; MercatorProjection.prototype._fromPointToLatLon = function(point) { var me = this; var origin = me._pixelOrigin; var lon = (point.x - origin.x) / me._pixelsPerLonDegree; var latRadians = (point.y - origin.y) / -me._pixelsPerLonRadian; var lat = radiansToDegrees(2 * Math.atan(Math.exp(latRadians)) - Math.PI / 2); return { lat:lat, lon:lon }; }; MercatorProjection.prototype._tilePixelPos = function(tileX, tileY) { return { x: tileX*this._tileSize, y: tileY*this._tileSize }; }; MercatorProjection.prototype.tilePixelBBox = function(x, y, zoom, px, py, res) { res = res || 1.0; var numTiles = 1 < 1) { Profiler.new_value(this.name, this.count); this.count = 0; this.start(); } } }; Profiler.metric = function(name) { return new Metric(name); }; module.exports = Profiler; },{}],18:[function(require,module,exports){ module.exports = { json: require('./json'), JsonArray: require('./jsonarray'), windshaft: require('./windshaft') }; },{"./json":19,"./jsonarray":20,"./windshaft":21}],19:[function(require,module,exports){ var torque = require('../'); var Profiler = require('../profiler'); var Uint8Array = torque.types.Uint8Array; var Int32Array = torque.types.Int32Array; var Uint32Array = torque.types.Uint32Array; // format('hello, {0}', 'rambo') -> "hello, rambo" function format(str) { for(var i = 1; i < arguments.length; ++i) { var attrs = arguments[i]; for(var attr in attrs) { str = str.replace(RegExp('\\{' + attr + '\\}', 'g'), attrs[attr]); } } return str; } var json = function (options) { this._ready = false; this._tileQueue = []; this.options = options; this.options.is_time = this.options.is_time === undefined ? true: this.options.is_time; this.options.tiler_protocol = options.tiler_protocol || 'http'; this.options.tiler_domain = options.tiler_domain || 'cartodb.com'; this.options.tiler_port = options.tiler_port || 80; if (this.options.data_aggregation) { this.options.cumulative = this.options.data_aggregation === 'cumulative'; } // check options if (options.resolution === undefined ) throw new Error("resolution should be provided"); if (options.steps === undefined ) throw new Error("steps should be provided"); if(options.start === undefined) { this._fetchKeySpan(); } else { this._setReady(true); } }; json.prototype = { /** * return the torque tile encoded in an efficient javascript * structure: * { * x:Uint8Array x coordinates in tile reference system, normally from 0-255 * y:Uint8Array y coordinates in tile reference system * Index: Array index to the properties * } */ proccessTile: function(rows, coord, zoom) { var r; var x = new Uint8Array(rows.length); var y = new Uint8Array(rows.length); var prof_mem = Profiler.metric('ProviderJSON:mem'); var prof_point_count = Profiler.metric('ProviderJSON:point_count'); var prof_process_time = Profiler.metric('ProviderJSON:process_time').start() // count number of dates var dates = 0; var maxDateSlots = -1; for (r = 0; r < rows.length; ++r) { var row = rows[r]; dates += row.dates__uint16.length; for(var d = 0; d < row.dates__uint16.length; ++d) { maxDateSlots = Math.max(maxDateSlots, row.dates__uint16[d]); } } if(this.options.cumulative) { dates = (1 + maxDateSlots) * rows.length; } var type = this.options.cumulative ? Uint32Array: Uint8Array; // reserve memory for all the dates var timeIndex = new Int32Array(maxDateSlots + 1); //index-size var timeCount = new Int32Array(maxDateSlots + 1); var renderData = new (this.options.valueDataType || type)(dates); var renderDataPos = new Uint32Array(dates); prof_mem.inc( 4 * maxDateSlots + // timeIndex 4 * maxDateSlots + // timeCount dates + //renderData dates * 4 ); //renderDataPos prof_point_count.inc(rows.length); var rowsPerSlot = {}; // precache pixel positions for (var r = 0; r < rows.length; ++r) { var row = rows[r]; x[r] = row.x__uint8 * this.options.resolution; // fix value when it's in the tile EDGE // TODO: this should be fixed in SQL query if (row.y__uint8 === -1) { y[r] = 0; } else { y[r] = row.y__uint8 * this.options.resolution; } var dates = row.dates__uint16; var vals = row.vals__uint8; if (!this.options.cumulative) { for (var j = 0, len = dates.length; j < len; ++j) { var rr = rowsPerSlot[dates[j]] || (rowsPerSlot[dates[j]] = []); if(this.options.cumulative) { vals[j] += prev_val; } prev_val = vals[j]; rr.push([r, vals[j]]); } } else { var valByDate = {} for (var j = 0, len = dates.length; j < len; ++j) { valByDate[dates[j]] = vals[j]; } var accum = 0; // extend the latest to the end for (var j = dates[0]; j <= maxDateSlots; ++j) { var rr = rowsPerSlot[j] || (rowsPerSlot[j] = []); var v = valByDate[j]; if (v) { accum += v; } rr.push([r, accum]); } /*var lastDateSlot = dates[dates.length - 1]; for (var j = lastDateSlot + 1; j <= maxDateSlots; ++j) { var rr = rowsPerSlot[j] || (rowsPerSlot[j] = []); rr.push([r, prev_val]); } */ } } // for each timeslot search active buckets var renderDataIndex = 0; var timeSlotIndex = 0; var i = 0; for(var i = 0; i <= maxDateSlots; ++i) { var c = 0; var slotRows = rowsPerSlot[i] if(slotRows) { for (var r = 0; r < slotRows.length; ++r) { var rr = slotRows[r]; ++c; renderDataPos[renderDataIndex] = rr[0] renderData[renderDataIndex] = rr[1]; ++renderDataIndex; } } timeIndex[i] = timeSlotIndex; timeCount[i] = c; timeSlotIndex += c; } prof_process_time.end(); return { x: x, y: y, z: zoom, coord: { x: coord.x, y: coord.y, z: zoom }, timeCount: timeCount, timeIndex: timeIndex, renderDataPos: renderDataPos, renderData: renderData, maxDate: maxDateSlots }; }, _host: function() { var opts = this.options; var port = opts.sql_api_port; var domain = ((opts.user_name || opts.user) + '.' + (opts.sql_api_domain || 'cartodb.com')) + (port ? ':' + port: ''); var protocol = opts.sql_api_protocol || 'http'; return this.options.url || protocol + '://' + domain + '/api/v2/sql'; }, url: function(subhost) { var opts = this.options; var protocol = opts.sql_api_protocol || 'http'; if (!this.options.cdn_url) { return this._host(); } var h = protocol+ "://"; if (subhost) { h += subhost + "."; } var cdn_host = opts.cdn_url; if(!cdn_host.http && !cdn_host.https) { throw new Error("cdn_host should contain http and/or https entries"); } h += cdn_host[protocol] + "/" + (opts.user_name || opts.user) + '/api/v2/sql'; return h; }, _hash: function(str) { var hash = 0; if (!str || str.length == 0) return hash; for (var i = 0, l = str.length; i < l; ++i) { hash = (( (hash << 5 ) - hash ) + str.charCodeAt(i)) | 0; } return hash; }, _extraParams: function() { if (this.options.extra_params) { var p = []; for(var k in this.options.extra_params) { var v = this.options.extra_params[k]; if (v) { p.push(k + "=" + encodeURIComponent(v)); } } return p.join('&'); } return null; }, isHttps: function() { return this.options.sql_api_protocol && this.options.sql_api_protocol === 'https'; }, // execute actual query sql: function(sql, callback, options) { options = options || {}; var subdomains = this.options.subdomains || '0123'; if(this.isHttps()) { subdomains = [null]; // no subdomain } var url; if (options.no_cdn) { url = this._host(); } else { url = this.url(subdomains[Math.abs(this._hash(sql))%subdomains.length]); } var extra = this._extraParams(); torque.net.get( url + "?q=" + encodeURIComponent(sql) + (extra ? "&" + extra: ''), function (data) { if(options.parseJSON) { data = JSON.parse(data && data.responseText); } callback && callback(data); }); }, getTileData: function(coord, zoom, callback) { if(!this._ready) { this._tileQueue.push([coord, zoom, callback]); } else { this._getTileData(coord, zoom, callback); } }, _setReady: function(ready) { this._ready = true; this._processQueue(); this.options.ready && this.options.ready(); }, _processQueue: function() { var item; while (item = this._tileQueue.pop()) { this._getTileData.apply(this, item); } }, /** * `coord` object like {x : tilex, y: tiley } * `zoom` quadtree zoom level */ _getTileData: function(coord, zoom, callback) { var prof_fetch_time = Profiler.metric('ProviderJSON:tile_fetch_time').start() this.table = this.options.table; var numTiles = 1 << zoom; var column_conv = this.options.column; if(this.options.is_time) { column_conv = format("date_part('epoch', {column})", this.options); } var sql = "" + "WITH " + "par AS (" + " SELECT CDB_XYZ_Resolution({zoom})*{resolution} as res" + ", 256/{resolution} as tile_size" + ", CDB_XYZ_Extent({x}, {y}, {zoom}) as ext " + ")," + "cte AS ( "+ " SELECT ST_SnapToGrid(i.the_geom_webmercator, p.res) g" + ", {countby} c" + ", floor(({column_conv} - {start})/{step}) d" + " FROM ({_sql}) i, par p " + " WHERE i.the_geom_webmercator && p.ext " + " GROUP BY g, d" + ") " + "" + "SELECT (st_x(g)-st_xmin(p.ext))/p.res x__uint8, " + " (st_y(g)-st_ymin(p.ext))/p.res y__uint8," + " array_agg(c) vals__uint8," + " array_agg(d) dates__uint16" + // the tile_size where are needed because the overlaps query in cte subquery includes the points // in the left and bottom borders of the tile " FROM cte, par p where (st_y(g)-st_ymin(p.ext))/p.res < tile_size and (st_x(g)-st_xmin(p.ext))/p.res < tile_size GROUP BY x__uint8, y__uint8"; var query = format(sql, this.options, { zoom: zoom, x: coord.x, y: coord.y, column_conv: column_conv, _sql: this.getSQL() }); var self = this; this.sql(query, function (data) { if (data) { var rows = JSON.parse(data.responseText).rows; callback(self.proccessTile(rows, coord, zoom)); } else { callback(null); } prof_fetch_time.end(); }); }, getKeySpan: function() { return { start: this.options.start * 1000, end: this.options.end * 1000, step: this.options.step, steps: this.options.steps, columnType: this.options.is_time ? 'date': 'number' }; }, setColumn: function(column, isTime) { this.options.column = column; this.options.is_time = isTime === undefined ? true: false; this.reload(); }, setResolution: function(res) { this.options.resolution = res; }, // return true if tiles has been changed setOptions: function(opt) { var refresh = false; if(opt.resolution !== undefined && opt.resolution !== this.options.resolution) { this.options.resolution = opt.resolution; refresh = true; } if(opt.steps !== undefined && opt.steps !== this.options.steps) { this.setSteps(opt.steps, { silent: true }); refresh = true; } if(opt.column !== undefined && opt.column !== this.options.column) { this.options.column = opt.column; refresh = true; } if(opt.countby !== undefined && opt.countby !== this.options.countby) { this.options.countby = opt.countby; refresh = true; } if(opt.data_aggregation !== undefined) { var c = opt.data_aggregation === 'cumulative'; if (this.options.cumulative !== c) { this.options.cumulative = c; refresh = true; } } if (refresh) this.reload(); return refresh; }, reload: function() { this._ready = false; this._fetchKeySpan(); }, setSQL: function(sql) { if (this.options.sql != sql) { this.options.sql = sql; this.reload(); } }, getSteps: function() { return Math.min(this.options.steps, this.options.data_steps); }, setSteps: function(steps, opt) { opt = opt || {}; if (this.options.steps !== steps) { this.options.steps = steps; this.options.step = (this.options.end - this.options.start)/this.getSteps(); this.options.step = this.options.step || 1; if (!opt.silent) this.reload(); } }, getBounds: function() { return this.options.bounds; }, getSQL: function() { return this.options.sql || "select * from " + this.options.table; }, _tilerHost: function() { var opts = this.options; var user = (opts.user_name || opts.user); return opts.tiler_protocol + "://" + (user ? user + "." : "") + opts.tiler_domain + ((opts.tiler_port != "") ? (":" + opts.tiler_port) : ""); }, _fetchUpdateAt: function(callback) { var self = this; var layergroup = { "version": "1.0.1", "stat_tag": this.options.stat_tag || 'torque', "layers": [{ "type": "cartodb", "options": { "cartocss_version": "2.1.1", "cartocss": "#layer {}", "sql": this.getSQL() } }] }; var url = this._tilerHost() + "/tiles/layergroup"; var extra = this._extraParams(); // tiler needs map_key instead of api_key // so replace it if (extra) { extra = extra.replace('api_key=', 'map_key='); } url = url + "?config=" + encodeURIComponent(JSON.stringify(layergroup)) + "&callback=?" + (extra ? "&" + extra: ''); torque.net.jsonp(url, function (data) { var query = format("select * from ({sql}) __torque_wrap_sql limit 0", { sql: self.getSQL() }); self.sql(query, function (queryData) { if (data) { callback({ updated_at: data.last_updated, fields: queryData.fields }); } }, { parseJSON: true }); }); }, // // the data range could be set by the user though ``start`` // option. It can be fecthed from the table when the start // is not specified. // _fetchKeySpan: function() { var self = this; var max_col, min_col, max_tmpl, min_tmpl; this._fetchUpdateAt(function(data) { if (!data) return; self.options.extra_params = self.options.extra_params || {}; self.options.extra_params.last_updated = data.updated_at || 0; self.options.extra_params.cache_policy = 'persist'; self.options.is_time = data.fields[self.options.column].type === 'date'; var column_conv = self.options.column; if (self.options.is_time){ max_tmpl = "date_part('epoch', max({column}))"; min_tmpl = "date_part('epoch', min({column}))"; column_conv = format("date_part('epoch', {column})", self.options); } else { max_tmpl = "max({column})"; min_tmpl = "min({column})"; } max_col = format(max_tmpl, { column: self.options.column }); min_col = format(min_tmpl, { column: self.options.column }); /*var sql_stats = "" + "WITH summary_groups as ( " + "WITH summary as ( " + "select (row_number() over (order by __time_col asc nulls last)+1)/2 as rownum, __time_col " + "from (select *, {column} as __time_col from ({sql}) __s) __torque_wrap_sql " + "order by __time_col asc " + ") " + "SELECT " + "max(__time_col) OVER(PARTITION BY rownum) - " + "min(__time_col) OVER(PARTITION BY rownum) diff " + "FROM summary " + "), subq as ( " + " SELECT " + "st_xmax(st_envelope(st_collect(the_geom))) xmax, " + "st_ymax(st_envelope(st_collect(the_geom))) ymax, " + "st_xmin(st_envelope(st_collect(the_geom))) xmin, " + "st_ymin(st_envelope(st_collect(the_geom))) ymin, " + "{max_col} max, " + "{min_col} min FROM ({sql}) __torque_wrap_sql " + ")" + "SELECT " + "xmax, xmin, ymax, ymin, a.max as max_date, a.min as min_date, " + "avg(diff) as diffavg," + "(a.max - a.min)/avg(diff) as num_steps " + "FROM summary_groups, subq a " + "WHERE diff > 0 group by xmax, xmin, ymax, ymin, max_date, min_date"; */ var sql_stats = " SELECT " + "st_xmax(st_envelope(st_collect(the_geom))) xmax, " + "st_ymax(st_envelope(st_collect(the_geom))) ymax, " + "st_xmin(st_envelope(st_collect(the_geom))) xmin, " + "st_ymin(st_envelope(st_collect(the_geom))) ymin, " + "count(*) as num_steps, " + "{max_col} max_date, " + "{min_col} min_date FROM ({sql}) __torque_wrap_sql "; var sql = format(sql_stats, { max_col: max_col, min_col: min_col, column: column_conv, sql: self.getSQL() }); self.sql(sql, function(data) { //TODO: manage bounds data = data.rows[0]; self.options.start = data.min_date; self.options.end = data.max_date; self.options.step = (data.max_date - data.min_date)/Math.min(self.options.steps, data.num_steps>>0); self.options.data_steps = data.num_steps >> 0; // step can't be 0 self.options.step = self.options.step || 1; self.options.bounds = [ [data.ymin, data.xmin], [data.ymax, data.xmax] ]; self._setReady(true); }, { parseJSON: true, no_cdn: true }); }, { parseJSON: true, no_cdn: true}) } }; module.exports = json; },{"../":10,"../profiler":17}],20:[function(require,module,exports){ var torque = require('../'); var Profiler = require('../profiler'); var Uint8Array = torque.types.Uint8Array; var Int32Array = torque.types.Int32Array; var Uint32Array = torque.types.Uint32Array; // format('hello, {0}', 'rambo') -> "hello, rambo" function format(str, attrs) { for(var i = 1; i < arguments.length; ++i) { var attrs = arguments[i]; for(var attr in attrs) { str = str.replace(RegExp('\\{' + attr + '\\}', 'g'), attrs[attr]); } } return str; } var json = function (options) { // check options this.options = options; }; json.prototype = { // // return the data aggregated by key: // { // key0: 12, // key1: 32 // key2: 25 // } // aggregateByKey: function(rows) { function getKeys(row) { var HEADER_SIZE = 3; var valuesCount = row.data[2]; var keys = {}; for (var s = 0; s < valuesCount; ++s) { keys[row.data[HEADER_SIZE + s]] = row.data[HEADER_SIZE + valuesCount + s]; } return keys; } var keys = {}; for (r = 0; r < rows.length; ++r) { var rowKeys = getKeys(rows[r]); for(var k in rowKeys) { keys[k] = keys[k] || 0; keys[k] += rowKeys[k]; } } return keys; }, /** * */ proccessTile: function(rows, coord, zoom) { var r; var x = new Uint8Array(rows.length); var y = new Uint8Array(rows.length); var self = this; // decode into a javascript strcuture the array function decode_row(row) { var HEADER_SIZE = 3; var o = { x: row.data[0] * self.options.resolution, y: row.data[1] * self.options.resolution, valuesCount: row.data[2], times: [], values: [] }; for (var s = 0; s < o.valuesCount; ++s) { o.times.push(row.data[HEADER_SIZE + s]); o.values.push(row.data[HEADER_SIZE + o.valuesCount + s]); } if(self.options.cumulative) { for (var s = 1; s < o.valuesCount; ++s) { o.values[s] += o.values[s - 1]; } } return o } // decode all the rows for (r = 0; r < rows.length; ++r) { rows[r] = decode_row(rows[r]); } // count number of dates var dates = 0; var maxDateSlots = 0; for (r = 0; r < rows.length; ++r) { var row = rows[r]; dates += row.times.length; for(var d = 0; d < row.times.length; ++d) { maxDateSlots = Math.max(maxDateSlots, row.times[d]); } } // reserve memory for all the dates var timeIndex = new Int32Array(maxDateSlots + 1); //index-size var timeCount = new Int32Array(maxDateSlots + 1); var renderData = new (this.options.valueDataType || Uint8Array)(dates); var renderDataPos = new Uint32Array(dates); var rowsPerSlot = {}; // precache pixel positions for (var r = 0; r < rows.length; ++r) { var row = rows[r]; x[r] = row.x; y[r] = row.y; var dates = row.times; var vals = row.values; for (var j = 0, len = dates.length; j < len; ++j) { var rr = rowsPerSlot[dates[j]] || (rowsPerSlot[dates[j]] = []); rr.push([r, vals[j]]); } } // for each timeslot search active buckets var renderDataIndex = 0; var timeSlotIndex = 0; var i = 0; for(var i = 0; i <= maxDateSlots; ++i) { var c = 0; var slotRows = rowsPerSlot[i] if(slotRows) { for (var r = 0; r < slotRows.length; ++r) { var rr = slotRows[r]; ++c; renderDataPos[renderDataIndex] = rr[0] renderData[renderDataIndex] = rr[1]; ++renderDataIndex; } } timeIndex[i] = timeSlotIndex; timeCount[i] = c; timeSlotIndex += c; } return { x: x, y: y, coord: { x: coord.x, y: coord.y, z: zoom }, timeCount: timeCount, timeIndex: timeIndex, renderDataPos: renderDataPos, renderData: renderData }; }, url: function() { return this.options.url; }, tileUrl: function(coord, zoom) { var template = this.url(); var s = (this.options.subdomains || 'abcd')[(coord.x + coord.y + zoom) % 4]; return template .replace('{x}', coord.x) .replace('{y}', coord.y) .replace('{z}', zoom) .replace('{s}', s); }, getTile: function(coord, zoom, callback) { var template = this.tileUrl(coord, zoom); var self = this; var fetchTime = Profiler.metric('jsonarray:fetch time'); fetchTime.start(); torque.net.get(template, function (data) { fetchTime.end(); if(data) { data = JSON.parse(data.responseText); } callback(data); }); }, /** * `coord` object like {x : tilex, y: tiley } * `zoom` quadtree zoom level */ getTileData: function(coord, zoom, callback) { var template = this.tileUrl(coord, zoom); var self = this; var fetchTime = Profiler.metric('jsonarray:fetch time'); fetchTime.start(); torque.net.get(template, function (data) { fetchTime.end(); var processed = null; var processingTime = Profiler.metric('jsonarray:processing time'); var parsingTime = Profiler.metric('jsonarray:parsing time'); try { processingTime.start(); parsingTime.start(); var rows = JSON.parse(data.responseText || data.response).rows; parsingTime.end(); processed = self.proccessTile(rows, coord, zoom); processingTime.end(); } catch(e) { console.error("problem parsing JSON on ", coord, zoom); } callback(processed); }); } }; module.exports = json; },{"../":10,"../profiler":17}],21:[function(require,module,exports){ var torque = require('../'); var Profiler = require('../profiler'); var Uint8Array = torque.types.Uint8Array; var Int32Array = torque.types.Int32Array; var Uint32Array = torque.types.Uint32Array; // format('hello, {0}', 'rambo') -> "hello, rambo" function format(str) { for(var i = 1; i < arguments.length; ++i) { var attrs = arguments[i]; for(var attr in attrs) { str = str.replace(RegExp('\\{' + attr + '\\}', 'g'), attrs[attr]); } } return str; } var json = function (options) { this._ready = false; this._tileQueue = []; this.options = options; this.options.is_time = this.options.is_time === undefined ? true: this.options.is_time; this.options.tiler_protocol = options.tiler_protocol || 'http'; this.options.tiler_domain = options.tiler_domain || 'cartodb.com'; this.options.tiler_port = options.tiler_port || 80; if (this.options.data_aggregation) { this.options.cumulative = this.options.data_aggregation === 'cumulative'; } if (this.options.auth_token) { var e = this.options.extra_params || (this.options.extra_params = {}); e.auth_token = this.options.auth_token; } if (!this.options.no_fetch_map) { this._fetchMap(); } }; json.prototype = { /** * return the torque tile encoded in an efficient javascript * structure: * { * x:Uint8Array x coordinates in tile reference system, normally from 0-255 * y:Uint8Array y coordinates in tile reference system * Index: Array index to the properties * } */ proccessTile: function(rows, coord, zoom) { var r; var x = new Uint8Array(rows.length); var y = new Uint8Array(rows.length); var prof_mem = Profiler.metric('torque.provider.windshaft.mem'); var prof_point_count = Profiler.metric('torque.provider.windshaft.points'); var prof_process_time = Profiler.metric('torque.provider.windshaft.process_time').start(); // count number of dates var dates = 0; var maxDateSlots = -1; for (r = 0; r < rows.length; ++r) { var row = rows[r]; dates += row.dates__uint16.length; for(var d = 0; d < row.dates__uint16.length; ++d) { maxDateSlots = Math.max(maxDateSlots, row.dates__uint16[d]); } } if(this.options.cumulative) { dates = (1 + maxDateSlots) * rows.length; } var type = this.options.cumulative ? Uint32Array: Uint8Array; // reserve memory for all the dates var timeIndex = new Int32Array(maxDateSlots + 1); //index-size var timeCount = new Int32Array(maxDateSlots + 1); var renderData = new (this.options.valueDataType || type)(dates); var renderDataPos = new Uint32Array(dates); prof_mem.inc( 4 * maxDateSlots + // timeIndex 4 * maxDateSlots + // timeCount dates + //renderData dates * 4 ); //renderDataPos prof_point_count.inc(rows.length); var rowsPerSlot = {}; // precache pixel positions for (var r = 0; r < rows.length; ++r) { var row = rows[r]; x[r] = row.x__uint8 * this.options.resolution; // fix value when it's in the tile EDGE // TODO: this should be fixed in SQL query if (row.y__uint8 === -1) { y[r] = 0; } else { y[r] = row.y__uint8 * this.options.resolution; } var dates = row.dates__uint16; var vals = row.vals__uint8; if (!this.options.cumulative) { for (var j = 0, len = dates.length; j < len; ++j) { var rr = rowsPerSlot[dates[j]] || (rowsPerSlot[dates[j]] = []); if(this.options.cumulative) { vals[j] += prev_val; } prev_val = vals[j]; rr.push([r, vals[j]]); } } else { var valByDate = {} for (var j = 0, len = dates.length; j < len; ++j) { valByDate[dates[j]] = vals[j]; } var accum = 0; // extend the latest to the end for (var j = dates[0]; j <= maxDateSlots; ++j) { var rr = rowsPerSlot[j] || (rowsPerSlot[j] = []); var v = valByDate[j]; if (v) { accum += v; } rr.push([r, accum]); } /*var lastDateSlot = dates[dates.length - 1]; for (var j = lastDateSlot + 1; j <= maxDateSlots; ++j) { var rr = rowsPerSlot[j] || (rowsPerSlot[j] = []); rr.push([r, prev_val]); } */ } } // for each timeslot search active buckets var renderDataIndex = 0; var timeSlotIndex = 0; var i = 0; for(var i = 0; i <= maxDateSlots; ++i) { var c = 0; var slotRows = rowsPerSlot[i] if(slotRows) { for (var r = 0; r < slotRows.length; ++r) { var rr = slotRows[r]; ++c; renderDataPos[renderDataIndex] = rr[0] renderData[renderDataIndex] = rr[1]; ++renderDataIndex; } } timeIndex[i] = timeSlotIndex; timeCount[i] = c; timeSlotIndex += c; } prof_process_time.end(); return { x: x, y: y, z: zoom, coord: { x: coord.x, y: coord.y, z: zoom }, timeCount: timeCount, timeIndex: timeIndex, renderDataPos: renderDataPos, renderData: renderData, maxDate: maxDateSlots }; }, /*setCartoCSS: function(c) { this.options.cartocss = c; },*/ setSteps: function(steps, opt) { opt = opt || {}; if (this.options.steps !== steps) { this.options.steps = steps; this.options.step = (this.options.end - this.options.start)/this.getSteps(); this.options.step = this.options.step || 1; if (!opt.silent) this.reload(); } }, setOptions: function(opt) { var refresh = false; if(opt.resolution !== undefined && opt.resolution !== this.options.resolution) { this.options.resolution = opt.resolution; refresh = true; } if(opt.steps !== undefined && opt.steps !== this.options.steps) { this.setSteps(opt.steps, { silent: true }); refresh = true; } if(opt.column !== undefined && opt.column !== this.options.column) { this.options.column = opt.column; refresh = true; } if(opt.countby !== undefined && opt.countby !== this.options.countby) { this.options.countby = opt.countby; refresh = true; } if(opt.data_aggregation !== undefined) { var c = opt.data_aggregation === 'cumulative'; if (this.options.cumulative !== c) { this.options.cumulative = c; refresh = true; } } if (refresh) this.reload(); return refresh; }, _extraParams: function(e) { e = torque.extend(torque.extend({}, e), this.options.extra_params); if (e) { var p = []; for(var k in e) { var v = e[k]; if (v) { if (torque.isArray(v)) { for (var i = 0, len = v.length; i < len; i++) { p.push(k + "[]=" + encodeURIComponent(v[i])); } } else { p.push(k + "=" + encodeURIComponent(v)); } } } return p.join('&'); } return null; }, getTileData: function(coord, zoom, callback) { if(!this._ready) { this._tileQueue.push([coord, zoom, callback]); } else { this._getTileData(coord, zoom, callback); } }, _setReady: function(ready) { this._ready = true; this._processQueue(); this.options.ready && this.options.ready(); }, _processQueue: function() { var item; while (item = this._tileQueue.pop()) { this._getTileData.apply(this, item); } }, /** * `coord` object like {x : tilex, y: tiley } * `zoom` quadtree zoom level */ _getTileData: function(coord, zoom, callback) { var self = this; var prof_fetch_time = Profiler.metric('torque.provider.windshaft.tile.fetch').start(); var subdomains = this.options.subdomains || '0123'; var limit_x = Math.pow(2, zoom); var corrected_x = ((coord.x % limit_x) + limit_x) % limit_x; var index = Math.abs(corrected_x + coord.y) % subdomains.length; var url = this.templateUrl .replace('{x}', corrected_x) .replace('{y}', coord.y) .replace('{z}', zoom) .replace('{s}', subdomains[index]) var extra = this._extraParams(); torque.net.get( url + (extra ? "?" + extra: ''), function (data) { prof_fetch_time.end(); if (data && data.responseText) { var rows = JSON.parse(data.responseText); callback(self.proccessTile(rows, coord, zoom)); } else { Profiler.metric('torque.provider.windshaft.tile.error').inc(); callback(null); } }); }, getKeySpan: function() { return { start: this.options.start, end: this.options.end, step: this.options.step, steps: this.options.steps, columnType: this.options.column_type }; }, setColumn: function(column, isTime) { this.options.column = column; this.options.is_time = isTime === undefined ? true: false; this.reload(); }, reload: function() { this._ready = false; this._fetchMap(); }, getSteps: function() { return Math.min(this.options.steps, this.options.data_steps); }, getBounds: function() { return this.options.bounds; }, getSQL: function() { return this.options.sql || "select * from " + this.options.table; }, setSQL: function(sql) { if (this.options.sql != sql) { this.options.sql = sql; this.reload(); } }, _tilerHost: function() { var opts = this.options; var user = (opts.user_name || opts.user); return opts.tiler_protocol + "://" + (user ? user + "." : "") + opts.tiler_domain + ((opts.tiler_port != "") ? (":" + opts.tiler_port) : ""); }, url: function() { var opts = this.options; var protocol = opts.tiler_protocol || 'http'; if (!this.options.cdn_url || this.options.no_cdn) { return this._tilerHost(); } var h = protocol + "://" if (protocol === 'http') { h += "{s}."; } var cdn_host = opts.cdn_url; if(!cdn_host.http && !cdn_host.https) { throw new Error("cdn_host should contain http and/or https entries"); } h += cdn_host[protocol] + "/" + (opts.user_name || opts.user); return h; }, _generateCartoCSS: function() { var attr = { '-torque-frame-count': this.options.steps, '-torque-resolution': this.options.resolution, '-torque-aggregation-function': "'" + this.options.countby + "'", '-torque-time-attribute': "'" + this.options.column + "'", '-torque-data-aggregation': this.options.cumulative ? 'cumulative': 'linear', }; var st = 'Map{'; for (var k in attr) { st += k + ":" + attr[k] + ";"; } return st + "}"; }, _fetchMap: function(callback) { var self = this; var layergroup = {}; var host = this.options.dynamic_cdn ? this.url().replace('{s}', '0'): this._tilerHost(); var url = host + "/api/v1/map"; var named = this.options.named_map; var allParams = {}; if(named) { //tiles/template url = host + "/api/v1/map/named/" + named.name + "/jsonp"; if(typeof named.params !== "undefined"){ layergroup = named.params; } } else { layergroup = { "version": "1.0.1", "stat_tag": this.options.stat_tag || 'torque', "layers": [{ "type": "torque", "options": { "cartocss_version": "1.0.0", "cartocss": this._generateCartoCSS(), "sql": this.getSQL() } }] }; } if(this.options.stat_tag){ allParams["stat_tag"] = this.options.stat_tag; } extra = this._extraParams(allParams); // tiler needs map_key instead of api_key // so replace it if (extra) { extra = extra.replace('api_key=', 'map_key='); } url = url + "?config=" + encodeURIComponent(JSON.stringify(layergroup)) + "&callback=?" + (extra ? "&" + extra: ''); var map_instance_time = Profiler.metric('torque.provider.windshaft.layergroup.time').start(); torque.net.jsonp(url, function (data) { map_instance_time.end(); if (data) { var torque_key = Object.keys(data.metadata.torque)[0] var opt = data.metadata.torque[torque_key]; for(var k in opt) { self.options[k] = opt[k]; } // use cdn_url if present if (data.cdn_url) { var c = self.options.cdn_url = self.options.cdn_url || {}; c.http = data.cdn_url.http || c.http; c.https = data.cdn_url.https || c.https; } self.templateUrl = self.url() + "/api/v1/map/" + data.layergroupid + "/" + torque_key + "/{z}/{x}/{y}.json.torque"; self._setReady(true); } else { Profiler.metric('torque.provider.windshaft.layergroup.error').inc(); } }, { callbackName: self.options.instanciateCallback }); } }; module.exports = json; },{"../":10,"../profiler":17}],22:[function(require,module,exports){ var TAU = Math.PI*2; // min value to render a line. // it does not make sense to render a line of a width is not even visible var LINEWIDTH_MIN_VALUE = 0.05; function renderPoint(ctx, st) { ctx.fillStyle = st['marker-fill']; var pixel_size = st['marker-width']; // render a circle // TODO: fill and stroke order should depend on the order of the properties // in the cartocss. // fill ctx.beginPath(); ctx.arc(0, 0, pixel_size, 0, TAU, true, true); ctx.closePath(); if (st['marker-fill']) { if (st['marker-fill-opacity'] !== undefined || st['marker-opacity'] !== undefined) { ctx.globalAlpha = st['marker-fill-opacity'] || st['marker-opacity']; } ctx.fill(); } // stroke ctx.globalAlpha = 1.0; if (st['marker-line-color'] && st['marker-line-width'] && st['marker-line-width'] > LINEWIDTH_MIN_VALUE) { if (st['marker-line-opacity'] !== undefined) { ctx.globalAlpha = st['marker-line-opacity']; } if (st['marker-line-width'] !== undefined) { ctx.lineWidth = st['marker-line-width']; } ctx.strokeStyle = st['marker-line-color']; // do not render for alpha = 0 if (ctx.globalAlpha > 0) { ctx.stroke(); } } } function renderRectangle(ctx, st) { ctx.fillStyle = st['marker-fill']; var pixel_size = st['marker-width']; var w = pixel_size * 2; // fill if (st['marker-fill']) { if (st['marker-fill-opacity'] !== undefined || st['marker-opacity'] !== undefined) { ctx.globalAlpha = st['marker-fill-opacity'] || st['marker-opacity']; } ctx.fillRect(-pixel_size, -pixel_size, w, w) } // stroke ctx.globalAlpha = 1.0; if (st['marker-line-color'] && st['marker-line-width']) { if (st['marker-line-opacity']) { ctx.globalAlpha = st['marker-line-opacity']; } if (st['marker-line-width']) { ctx.lineWidth = st['marker-line-width']; } ctx.strokeStyle = st['marker-line-color']; // do not render for alpha = 0 if (ctx.globalAlpha > 0) { ctx.strokeRect(-pixel_size, -pixel_size, w, w) } } } function renderSprite(ctx, img, st) { if(img.complete){ if (st['marker-fill-opacity'] !== undefined || st['marker-opacity'] !== undefined) { ctx.globalAlpha = st['marker-fill-opacity'] || st['marker-opacity']; } ctx.drawImage(img, -img.w, -img.h, img.w*2, img.h*2); } } module.exports = { renderPoint: renderPoint, renderSprite: renderSprite, renderRectangle: renderRectangle }; },{}],23:[function(require,module,exports){ module.exports = { cartocss: require('./cartocss_render'), Point: require('./point'), Rectangle: require('./rectangle') }; },{"./cartocss_render":22,"./point":24,"./rectangle":25}],24:[function(require,module,exports){ (function (global){ var torque = require('../'); var cartocss = require('./cartocss_render'); var Profiler = require('../profiler'); var carto = global.carto || require('carto'); var filters = require('./torque_filters'); var TAU = Math.PI * 2; var DEFAULT_CARTOCSS = [ '#layer {', ' marker-fill: #662506;', ' marker-width: 4;', ' [value > 1] { marker-fill: #FEE391; }', ' [value > 2] { marker-fill: #FEC44F; }', ' [value > 3] { marker-fill: #FE9929; }', ' [value > 4] { marker-fill: #EC7014; }', ' [value > 5] { marker-fill: #CC4C02; }', ' [value > 6] { marker-fill: #993404; }', ' [value > 7] { marker-fill: #662506; }', '}' ].join('\n'); var COMP_OP_TO_CANVAS = { "src": 'source-over', "src-over": 'source-over', "dst-over": 'destination-over', "src-in": 'source-in', "dst-in": 'destination-in', "src-out": 'source-out', "dst-out": 'destination-out', "src-atop": 'source-atop', "dst-atop": 'destination-atop', "xor": 'xor', "darken": 'darken', "lighten": 'lighten' } function compop2canvas(compop) { return COMP_OP_TO_CANVAS[compop] || compop; } // // this renderer just render points depending of the value // function PointRenderer(canvas, options) { if (!canvas) { throw new Error("canvas can't be undefined"); } this.options = options; this._canvas = canvas; this._ctx = canvas.getContext('2d'); this._sprites = []; // sprites per layer this._shader = null; this._icons = {}; this._filters = filters(this._canvas); this.setCartoCSS(this.options.cartocss || DEFAULT_CARTOCSS); this.TILE_SIZE = 256; this._style = null; this._gradients = {}; this._forcePoints = false; } torque.extend(PointRenderer.prototype, torque.Event, { clearCanvas: function() { var canvas = this._canvas; var color = this._Map['-torque-clear-color'] // shortcut for the default value if (color === "rgba(255, 255, 255, 0)" || !color) { this._canvas.width = this._canvas.width; } else { var ctx = this._ctx; ctx.setTransform(1, 0, 0, 1, 0, 0); var compop = this._Map['comp-op'] ctx.globalCompositeOperation = compop2canvas(compop); ctx.fillStyle = color; ctx.fillRect(0, 0, canvas.width, canvas.height); } }, setCanvas: function(canvas) { this._canvas = canvas; this._ctx = canvas.getContext('2d'); }, // // sets the cartocss style to render stuff // setCartoCSS: function(cartocss) { // clean sprites this.setShader(new carto.RendererJS().render(cartocss)); }, setShader: function(shader) { // clean sprites this._sprites = []; this._shader = shader; this._Map = this._shader.getDefault().getStyle({}, { zoom: 0 }); var img_names = this._shader.getImageURLs(); this._preloadIcons(img_names); }, clearSpriteCache: function() { this._sprites = []; }, // // generate sprite based on cartocss style // generateSprite: function(shader, value, shaderVars) { var self = this; var prof = Profiler.metric('torque.renderer.point.generateSprite').start(); var st = shader.getStyle({ value: value }, shaderVars); if(this._style === null || this._style !== st){ this._style = st; } var pointSize = st['marker-width']; if (!pointSize) { return null; } if (st['marker-opacity'] === 0 && !st['marker-line-opacity']) { return null; } var canvas = this._createCanvas(); // take into account the exterior ring to calculate the size var canvasSize = (st['marker-line-width'] || 0) + pointSize*2; var ctx = canvas.getContext('2d'); var w = ctx.width = canvas.width = ctx.height = canvas.height = Math.ceil(canvasSize); ctx.translate(w/2, w/2); var img_name = this._qualifyURL(st["marker-file"] || st["point-file"]); if (img_name && this._icons.itemsToLoad <= 0) { var img = this._icons[img_name]; img.w = st['marker-width'] || img.width; img.h = st['marker-width'] || st['marker-height']; cartocss.renderSprite(ctx, img, st); } else { var mt = st['marker-type']; if (mt && mt === 'rectangle') { cartocss.renderRectangle(ctx, st); } else { cartocss.renderPoint(ctx, st); } } prof.end(true); if (torque.flags.sprites_to_images) { var i = this._createImage(); i.src = canvas.toDataURL(); return i; } return canvas; }, // // renders all the layers (and frames for each layer) from cartocss // renderTile: function(tile, key) { var prof = Profiler.metric('torque.renderer.point.renderLayers').start(); var layers = this._shader.getLayers(); for(var i = 0, n = layers.length; i < n; ++i ) { var layer = layers[i]; if (layer.name() !== "Map") { var sprites = this._sprites[i] || (this._sprites[i] = {}); // frames for each layer for(var fr = 0; fr < layer.frames().length; ++fr) { var frame = layer.frames()[fr]; var fr_sprites = sprites[frame] || (sprites[frame] = []); this._renderTile(tile, key - frame, frame, fr_sprites, layer); } } } prof.end(true); }, _createCanvas: function() { return this.options.canvasClass ? new this.options.canvasClass() : document.createElement('canvas'); }, _createImage: function() { return this.options.imageClass ? new this.options.imageClass() : new Image(); }, _qualifyURL: function(url) { if (typeof this.options.qualifyURL !== "undefined"){ return this.options.qualifyURL(url); } else{ var a = document.createElement('a'); a.href = url; return a.href; } }, // // renders a tile in the canvas for key defined in // the torque tile // _renderTile: function(tile, key, frame_offset, sprites, shader, shaderVars) { if (!this._canvas) return; var prof = Profiler.metric('torque.renderer.point.renderTile').start(); var ctx = this._ctx; var blendMode = compop2canvas(shader.eval('comp-op')) || this.options.blendmode; if (blendMode) { ctx.globalCompositeOperation = blendMode; } if (this.options.cumulative && key > tile.maxDate) { //TODO: precache because this tile is not going to change key = tile.maxDate; } var tileMax = this.options.resolution * (this.TILE_SIZE/this.options.resolution - 1) var activePixels = tile.timeCount[key]; if (activePixels) { var pixelIndex = tile.timeIndex[key]; for(var p = 0; p < activePixels; ++p) { var posIdx = tile.renderDataPos[pixelIndex + p]; var c = tile.renderData[pixelIndex + p]; if (c) { var sp = sprites[c]; if (sp === undefined) { sp = sprites[c] = this.generateSprite(shader, c, torque.extend({ zoom: tile.z, 'frame-offset': frame_offset }, shaderVars)); } if (sp) { var x = tile.x[posIdx]- (sp.width >> 1); var y = tileMax - tile.y[posIdx]; // flip mercator ctx.drawImage(sp, x, y - (sp.height >> 1)); } } } } prof.end(true); }, setBlendMode: function(b) { this.options.blendmode = b; }, /** * get active points for a step in active zoom * returns a list of bounding boxes [[sw, ne] , [], []] where ne is a {lat: .., lon: ...} obj * empty list if there is no active pixels */ getActivePointsBBox: function(tile, step) { var positions = []; var mercator = new torque.Mercator(); var tileMax = this.options.resolution * (this.TILE_SIZE/this.options.resolution - 1); //this.renderer.renderTile(tile, this.key, pos.x, pos.y); var activePixels = tile.timeCount[step]; var pixelIndex = tile.timeIndex[step]; for(var p = 0; p < activePixels; ++p) { var posIdx = tile.renderDataPos[pixelIndex + p]; var c = tile.renderData[pixelIndex + p]; if (c) { var x = tile.x[posIdx]; var y = tileMax - tile.y[posIdx]; // flip mercator positions.push(mercator.tilePixelBBox( tile.coord.x, tile.coord.y, tile.coord.z, x, y )); } } return positions; }, // return the value for x, y (tile coordinates) // null for no value getValueFor: function(tile, step, px, py) { var mercator = new torque.Mercator(); var res = this.options.resolution; var res2 = res >> 1; var tileMax = this.options.resolution * (this.TILE_SIZE/this.options.resolution - 1); //this.renderer.renderTile(tile, this.key, pos.x, pos.y); var activePixels = tile.timeCount[step]; var pixelIndex = tile.timeIndex[step]; for(var p = 0; p < activePixels; ++p) { var posIdx = tile.renderDataPos[pixelIndex + p]; var c = tile.renderData[pixelIndex + p]; if (c) { var x = tile.x[posIdx]; var y = tileMax - tile.y[posIdx]; var dx = px + res2 - x; var dy = py + res2 - y; if (dx >= 0 && dx < res && dy >= 0 && dy < res) { return { value: c, bbox: mercator.tilePixelBBox( tile.coord.x, tile.coord.y, tile.coord.z, x - res2, y - res2, res ) } } } } return null; }, _preloadIcons: function(img_names){ var self = this; this._icons = {}; if (img_names.length > 0 && !this._forcePoints){ for (var i = 0; i 10] { polygon-fill: #FFFF00; }', ' [value > 100] { polygon-fill: #FFCC00; }', ' [value > 1000] { polygon-fill: #FE9929; }', ' [value > 10000] { polygon-fill: #FF6600; }', ' [value > 100000] { polygon-fill: #FF3300; }', '}' ].join('\n'); var TAU = Math.PI * 2; // // this renderer just render points depending of the value // function RectanbleRenderer(canvas, options) { this.options = options; carto.tree.Reference.set(torque['torque-reference']); this.setCanvas(canvas); this.setCartoCSS(this.options.cartocss || DEFAULT_CARTOCSS); } RectanbleRenderer.prototype = { // // sets the cartocss style to render stuff // setCartoCSS: function(cartocss) { this._cartoCssStyle = new carto.RendererJS().render(cartocss); if(this._cartoCssStyle.getLayers().length > 1) { throw new Error("only one CartoCSS layer is supported"); } this._shader = this._cartoCssStyle.getLayers()[0].shader; }, setCanvas: function(canvas) { if(!canvas) return; this._canvas = canvas; this._ctx = canvas.getContext('2d'); }, accumulate: function(tile, keys) { var prof = Profiler.metric('RectangleRender:accumulate').start(); var x, y, posIdx, p, k, key, activePixels, pixelIndex; var res = this.options.resolution; var s = 256/res; var accum = new Float32Array(s*s); if(typeof(keys) !== 'object') { keys = [keys]; } for(k = 0; k < keys.length; ++k) { key = keys[k]; activePixels = tile.timeCount[key]; if(activePixels) { pixelIndex = tile.timeIndex[key]; for(p = 0; p < activePixels; ++p) { posIdx = tile.renderDataPos[pixelIndex + p]; x = tile.x[posIdx]/res; y = tile.y[posIdx]/res; accum[x*s + y] += tile.renderData[pixelIndex + p]; } } } prof.end(); return accum; }, renderTileAccum: function(accum, px, py) { var prof = Profiler.metric('RectangleRender:renderTileAccum').start(); var color, x, y, alpha; var res = this.options.resolution; var ctx = this._ctx; var s = (256/res) | 0; var s2 = s*s; var colors = this._colors; if(this.options.blendmode) { ctx.globalCompositeOperation = this.options.blendmode; } var polygon_alpha = this._shader['polygon-opacity'] || function() { return 1.0; }; for(var i = 0; i < s2; ++i) { var xy = i; var value = accum[i]; if(value) { x = (xy/s) | 0; y = xy % s; // by-pass the style generation for improving performance color = this._shader['polygon-fill']({ value: value }, { zoom: 0 }); ctx.fillStyle = color; //TODO: each function should have a default value for each //property defined in the cartocss alpha = polygon_alpha({ value: value }, { zoom: 0 }); if(alpha === null) { alpha = 1.0; } ctx.globalAlpha = alpha; ctx.fillRect(x * res, 256 - res - y * res, res, res); } } prof.end(); }, // // renders a tile in the canvas for key defined in // the torque tile // renderTile: function(tile, key, px, py) { if(!this._canvas) return; var res = this.options.resolution; //var prof = Profiler.get('render').start(); var ctx = this._ctx; var colors = this._colors; var activepixels = tile.timeCount[key]; if(activepixels) { var w = this._canvas.width; var h = this._canvas.height; //var imageData = ctx.getImageData(0, 0, w, h); //var pixels = imageData.data; var pixelIndex = tile.timeIndex[key]; for(var p = 0; p < activePixels; ++p) { var posIdx = tile.renderDataPos[pixelIndex + p]; var c = tile.renderData[pixelIndex + p]; if(c) { var color = colors[Math.min(c, colors.length - 1)]; var x = tile.x[posIdx];// + px; var y = tile.y[posIdx]; //+ py; ctx.fillStyle = color; ctx.fillRect(x, y, res, res); /* for(var xx = 0; xx < res; ++xx) { for(var yy = 0; yy < res; ++yy) { var idx = 4*((x+xx) + w*(y + yy)); pixels[idx + 0] = color[0]; pixels[idx + 1] = color[1]; pixels[idx + 2] = color[2]; pixels[idx + 3] = color[3]; } } */ } } //ctx.putImageData(imageData, 0, 0); } //prof.end(); } }; // exports public api module.exports = RectanbleRenderer; }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"carto":36}],26:[function(require,module,exports){ /* Based on simpleheat, a tiny JavaScript library for drawing heatmaps with Canvas, by Vladimir Agafonkin https://github.com/mourner/simpleheat */ 'use strict'; function torque_filters(canvas) { // jshint newcap: false, validthis: true if (!(this instanceof torque_filters)) { return new torque_filters(canvas); } this._canvas = canvas = typeof canvas === 'string' ? document.getElementById(canvas) : canvas; this._ctx = canvas.getContext('2d'); this._width = canvas.width; this._height = canvas.height; this._max = 1; this._data = []; } torque_filters.prototype = { defaultGradient: { 0.4: 'blue', 0.6: 'cyan', 0.7: 'lime', 0.8: 'yellow', 1.0: 'red' }, gradient: function (grad) { // create a 256x1 gradient that we'll use to turn a grayscale heatmap into a colored one var canvas = document.createElement('canvas'), ctx = canvas.getContext('2d'), gradient = ctx.createLinearGradient(0, 0, 0, 256); canvas.width = 1; canvas.height = 256; for (var i in grad) { gradient.addColorStop(i, grad[i]); } ctx.fillStyle = gradient; ctx.fillRect(0, 0, 1, 256); this._grad = ctx.getImageData(0, 0, 1, 256).data; return this; }, draw: function () { if (!this._grad) { this.gradient(this.defaultGradient); } var ctx = this._ctx; var colored = ctx.getImageData(0, 0, this._canvas.width, this._canvas.height); this._colorize(colored.data, this._grad); ctx.putImageData(colored, 0, 0); return this; }, _colorize: function (pixels, gradient) { for (var i = 3, len = pixels.length, j; i < len; i += 4) { j = pixels[i] * 4; // get gradient color from opacity value if (j) { pixels[i - 3] = gradient[j]; pixels[i - 2] = gradient[j + 1]; pixels[i - 1] = gradient[j + 2]; } } } }; module.exports = torque_filters; },{}],27:[function(require,module,exports){ (function (global){ var torque = require('./core'); var lastCall = null; function jsonp(url, callback, options) { options = options || {}; options.timeout = options.timeout === undefined ? 10000: options.timeout; var head = document.getElementsByTagName('head')[0]; var script = document.createElement('script'); // function name var fnName = options.callbackName || 'torque_' + Date.now(); if (torque.isFunction(fnName)) { fnName = fnName(); } function clean() { head.removeChild(script); clearTimeout(timeoutTimer); delete window[fnName]; } window[fnName] = function() { clean(); callback.apply(window, arguments); }; // timeout for errors var timeoutTimer = setTimeout(function() { clean(); callback.call(window, null); }, options.timeout); // setup url url = url.replace('callback=\?', 'callback=' + fnName); script.type = 'text/javascript'; script.src = url; script.async = true; // defer the loading because IE9 loads in the same frame the script // so Loader._script is null setTimeout(function() { head.appendChild(script); }, 0); } function get(url, callback, options) { options = options || { method: 'GET', data: null, responseType: 'text' }; lastCall = { url: url, callback: callback }; var request = XMLHttpRequest; // from d3.js if (global.XDomainRequest && !("withCredentials" in request) && /^(http(s)?:)?\/\//.test(url)) request = XDomainRequest; var req = new request(); req.open(options.method, url, true); function respond() { var status = req.status, result; var r = options.responseType === 'arraybuffer' ? req.response: req.responseText; if (!status && r || status >= 200 && status < 300 || status === 304) { callback(req); } else { callback(null); } } "onload" in req ? req.onload = req.onerror = respond : req.onreadystatechange = function() { req.readyState > 3 && respond(); }; req.onprogress = function() {}; req.responseType = options.responseType; //'arraybuffer'; if (options.data) { req.setRequestHeader("Content-type", "application/json"); //req.setRequestHeader("Content-type", "application/x-www-form-urlencoded") req.setRequestHeader("Accept", "*"); } req.send(options.data); return req; } function post(url, data, callback) { return get(url, callback, { data: data, method: "POST" }); } module.exports = { get: get, post: post, jsonp: jsonp, lastCall: function() { return lastCall; } }; }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"./core":4}],28:[function(require,module,exports){ },{}],29:[function(require,module,exports){ // http://wiki.commonjs.org/wiki/Unit_Testing/1.0 // // THIS IS NOT TESTED NOR LIKELY TO WORK OUTSIDE V8! // // Originally from narwhal.js (http://narwhaljs.org) // Copyright (c) 2009 Thomas Robinson <280north.com> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the 'Software'), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN // ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // when used in node, this will actually load the util module we depend on // versus loading the builtin util module as happens otherwise // this is a bug in node module loading as far as I am concerned var util = require('util/'); var pSlice = Array.prototype.slice; var hasOwn = Object.prototype.hasOwnProperty; // 1. The assert module provides functions that throw // AssertionError's when particular conditions are not met. The // assert module must conform to the following interface. var assert = module.exports = ok; // 2. The AssertionError is defined in assert. // new assert.AssertionError({ message: message, // actual: actual, // expected: expected }) assert.AssertionError = function AssertionError(options) { this.name = 'AssertionError'; this.actual = options.actual; this.expected = options.expected; this.operator = options.operator; if (options.message) { this.message = options.message; this.generatedMessage = false; } else { this.message = getMessage(this); this.generatedMessage = true; } var stackStartFunction = options.stackStartFunction || fail; if (Error.captureStackTrace) { Error.captureStackTrace(this, stackStartFunction); } else { // non v8 browsers so we can have a stacktrace var err = new Error(); if (err.stack) { var out = err.stack; // try to strip useless frames var fn_name = stackStartFunction.name; var idx = out.indexOf('\n' + fn_name); if (idx >= 0) { // once we have located the function frame // we need to strip out everything before it (and its line) var next_line = out.indexOf('\n', idx + 1); out = out.substring(next_line + 1); } this.stack = out; } } }; // assert.AssertionError instanceof Error util.inherits(assert.AssertionError, Error); function replacer(key, value) { if (util.isUndefined(value)) { return '' + value; } if (util.isNumber(value) && (isNaN(value) || !isFinite(value))) { return value.toString(); } if (util.isFunction(value) || util.isRegExp(value)) { return value.toString(); } return value; } function truncate(s, n) { if (util.isString(s)) { return s.length < n ? s : s.slice(0, n); } else { return s; } } function getMessage(self) { return truncate(JSON.stringify(self.actual, replacer), 128) + ' ' + self.operator + ' ' + truncate(JSON.stringify(self.expected, replacer), 128); } // At present only the three keys mentioned above are used and // understood by the spec. Implementations or sub modules can pass // other keys to the AssertionError's constructor - they will be // ignored. // 3. All of the following functions must throw an AssertionError // when a corresponding condition is not met, with a message that // may be undefined if not provided. All assertion methods provide // both the actual and expected values to the assertion error for // display purposes. function fail(actual, expected, message, operator, stackStartFunction) { throw new assert.AssertionError({ message: message, actual: actual, expected: expected, operator: operator, stackStartFunction: stackStartFunction }); } // EXTENSION! allows for well behaved errors defined elsewhere. assert.fail = fail; // 4. Pure assertion tests whether a value is truthy, as determined // by !!guard. // assert.ok(guard, message_opt); // This statement is equivalent to assert.equal(true, !!guard, // message_opt);. To test strictly for the value true, use // assert.strictEqual(true, guard, message_opt);. function ok(value, message) { if (!value) fail(value, true, message, '==', assert.ok); } assert.ok = ok; // 5. The equality assertion tests shallow, coercive equality with // ==. // assert.equal(actual, expected, message_opt); assert.equal = function equal(actual, expected, message) { if (actual != expected) fail(actual, expected, message, '==', assert.equal); }; // 6. The non-equality assertion tests for whether two objects are not equal // with != assert.notEqual(actual, expected, message_opt); assert.notEqual = function notEqual(actual, expected, message) { if (actual == expected) { fail(actual, expected, message, '!=', assert.notEqual); } }; // 7. The equivalence assertion tests a deep equality relation. // assert.deepEqual(actual, expected, message_opt); assert.deepEqual = function deepEqual(actual, expected, message) { if (!_deepEqual(actual, expected)) { fail(actual, expected, message, 'deepEqual', assert.deepEqual); } }; function _deepEqual(actual, expected) { // 7.1. All identical values are equivalent, as determined by ===. if (actual === expected) { return true; } else if (util.isBuffer(actual) && util.isBuffer(expected)) { if (actual.length != expected.length) return false; for (var i = 0; i < actual.length; i++) { if (actual[i] !== expected[i]) return false; } return true; // 7.2. If the expected value is a Date object, the actual value is // equivalent if it is also a Date object that refers to the same time. } else if (util.isDate(actual) && util.isDate(expected)) { return actual.getTime() === expected.getTime(); // 7.3 If the expected value is a RegExp object, the actual value is // equivalent if it is also a RegExp object with the same source and // properties (`global`, `multiline`, `lastIndex`, `ignoreCase`). } else if (util.isRegExp(actual) && util.isRegExp(expected)) { return actual.source === expected.source && actual.global === expected.global && actual.multiline === expected.multiline && actual.lastIndex === expected.lastIndex && actual.ignoreCase === expected.ignoreCase; // 7.4. Other pairs that do not both pass typeof value == 'object', // equivalence is determined by ==. } else if (!util.isObject(actual) && !util.isObject(expected)) { return actual == expected; // 7.5 For all other Object pairs, including Array objects, equivalence is // determined by having the same number of owned properties (as verified // with Object.prototype.hasOwnProperty.call), the same set of keys // (although not necessarily the same order), equivalent values for every // corresponding key, and an identical 'prototype' property. Note: this // accounts for both named and indexed properties on Arrays. } else { return objEquiv(actual, expected); } } function isArguments(object) { return Object.prototype.toString.call(object) == '[object Arguments]'; } function objEquiv(a, b) { if (util.isNullOrUndefined(a) || util.isNullOrUndefined(b)) return false; // an identical 'prototype' property. if (a.prototype !== b.prototype) return false; //~~~I've managed to break Object.keys through screwy arguments passing. // Converting to array solves the problem. if (isArguments(a)) { if (!isArguments(b)) { return false; } a = pSlice.call(a); b = pSlice.call(b); return _deepEqual(a, b); } try { var ka = objectKeys(a), kb = objectKeys(b), key, i; } catch (e) {//happens when one is a string literal and the other isn't return false; } // having the same number of owned properties (keys incorporates // hasOwnProperty) if (ka.length != kb.length) return false; //the same set of keys (although not necessarily the same order), ka.sort(); kb.sort(); //~~~cheap key test for (i = ka.length - 1; i >= 0; i--) { if (ka[i] != kb[i]) return false; } //equivalent values for every corresponding key, and //~~~possibly expensive deep test for (i = ka.length - 1; i >= 0; i--) { key = ka[i]; if (!_deepEqual(a[key], b[key])) return false; } return true; } // 8. The non-equivalence assertion tests for any deep inequality. // assert.notDeepEqual(actual, expected, message_opt); assert.notDeepEqual = function notDeepEqual(actual, expected, message) { if (_deepEqual(actual, expected)) { fail(actual, expected, message, 'notDeepEqual', assert.notDeepEqual); } }; // 9. The strict equality assertion tests strict equality, as determined by ===. // assert.strictEqual(actual, expected, message_opt); assert.strictEqual = function strictEqual(actual, expected, message) { if (actual !== expected) { fail(actual, expected, message, '===', assert.strictEqual); } }; // 10. The strict non-equality assertion tests for strict inequality, as // determined by !==. assert.notStrictEqual(actual, expected, message_opt); assert.notStrictEqual = function notStrictEqual(actual, expected, message) { if (actual === expected) { fail(actual, expected, message, '!==', assert.notStrictEqual); } }; function expectedException(actual, expected) { if (!actual || !expected) { return false; } if (Object.prototype.toString.call(expected) == '[object RegExp]') { return expected.test(actual); } else if (actual instanceof expected) { return true; } else if (expected.call({}, actual) === true) { return true; } return false; } function _throws(shouldThrow, block, expected, message) { var actual; if (util.isString(expected)) { message = expected; expected = null; } try { block(); } catch (e) { actual = e; } message = (expected && expected.name ? ' (' + expected.name + ').' : '.') + (message ? ' ' + message : '.'); if (shouldThrow && !actual) { fail(actual, expected, 'Missing expected exception' + message); } if (!shouldThrow && expectedException(actual, expected)) { fail(actual, expected, 'Got unwanted exception' + message); } if ((shouldThrow && actual && expected && !expectedException(actual, expected)) || (!shouldThrow && actual)) { throw actual; } } // 11. Expected to throw an error: // assert.throws(block, Error_opt, message_opt); assert.throws = function(block, /*optional*/error, /*optional*/message) { _throws.apply(this, [true].concat(pSlice.call(arguments))); }; // EXTENSION! This is annoying to write outside this module. assert.doesNotThrow = function(block, /*optional*/message) { _throws.apply(this, [false].concat(pSlice.call(arguments))); }; assert.ifError = function(err) { if (err) {throw err;}}; var objectKeys = Object.keys || function (obj) { var keys = []; for (var key in obj) { if (hasOwn.call(obj, key)) keys.push(key); } return keys; }; },{"util/":34}],30:[function(require,module,exports){ if (typeof Object.create === 'function') { // implementation from standard node.js 'util' module module.exports = function inherits(ctor, superCtor) { ctor.super_ = superCtor ctor.prototype = Object.create(superCtor.prototype, { constructor: { value: ctor, enumerable: false, writable: true, configurable: true } }); }; } else { // old school shim for old browsers module.exports = function inherits(ctor, superCtor) { ctor.super_ = superCtor var TempCtor = function () {} TempCtor.prototype = superCtor.prototype ctor.prototype = new TempCtor() ctor.prototype.constructor = ctor } } },{}],31:[function(require,module,exports){ (function (process){ // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // resolves . and .. elements in a path array with directory names there // must be no slashes, empty elements, or device names (c:\) in the array // (so also no leading and trailing slashes - it does not distinguish // relative and absolute paths) function normalizeArray(parts, allowAboveRoot) { // if the path tries to go above the root, `up` ends up > 0 var up = 0; for (var i = parts.length - 1; i >= 0; i--) { var last = parts[i]; if (last === '.') { parts.splice(i, 1); } else if (last === '..') { parts.splice(i, 1); up++; } else if (up) { parts.splice(i, 1); up--; } } // if the path is allowed to go above the root, restore leading ..s if (allowAboveRoot) { for (; up--; up) { parts.unshift('..'); } } return parts; } // Split a filename into [root, dir, basename, ext], unix version // 'root' is just a slash, or nothing. var splitPathRe = /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/; var splitPath = function(filename) { return splitPathRe.exec(filename).slice(1); }; // path.resolve([from ...], to) // posix version exports.resolve = function() { var resolvedPath = '', resolvedAbsolute = false; for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) { var path = (i >= 0) ? arguments[i] : process.cwd(); // Skip empty and invalid entries if (typeof path !== 'string') { throw new TypeError('Arguments to path.resolve must be strings'); } else if (!path) { continue; } resolvedPath = path + '/' + resolvedPath; resolvedAbsolute = path.charAt(0) === '/'; } // At this point the path should be resolved to a full absolute path, but // handle relative paths to be safe (might happen when process.cwd() fails) // Normalize the path resolvedPath = normalizeArray(filter(resolvedPath.split('/'), function(p) { return !!p; }), !resolvedAbsolute).join('/'); return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.'; }; // path.normalize(path) // posix version exports.normalize = function(path) { var isAbsolute = exports.isAbsolute(path), trailingSlash = substr(path, -1) === '/'; // Normalize the path path = normalizeArray(filter(path.split('/'), function(p) { return !!p; }), !isAbsolute).join('/'); if (!path && !isAbsolute) { path = '.'; } if (path && trailingSlash) { path += '/'; } return (isAbsolute ? '/' : '') + path; }; // posix version exports.isAbsolute = function(path) { return path.charAt(0) === '/'; }; // posix version exports.join = function() { var paths = Array.prototype.slice.call(arguments, 0); return exports.normalize(filter(paths, function(p, index) { if (typeof p !== 'string') { throw new TypeError('Arguments to path.join must be strings'); } return p; }).join('/')); }; // path.relative(from, to) // posix version exports.relative = function(from, to) { from = exports.resolve(from).substr(1); to = exports.resolve(to).substr(1); function trim(arr) { var start = 0; for (; start < arr.length; start++) { if (arr[start] !== '') break; } var end = arr.length - 1; for (; end >= 0; end--) { if (arr[end] !== '') break; } if (start > end) return []; return arr.slice(start, end - start + 1); } var fromParts = trim(from.split('/')); var toParts = trim(to.split('/')); var length = Math.min(fromParts.length, toParts.length); var samePartsLength = length; for (var i = 0; i < length; i++) { if (fromParts[i] !== toParts[i]) { samePartsLength = i; break; } } var outputParts = []; for (var i = samePartsLength; i < fromParts.length; i++) { outputParts.push('..'); } outputParts = outputParts.concat(toParts.slice(samePartsLength)); return outputParts.join('/'); }; exports.sep = '/'; exports.delimiter = ':'; exports.dirname = function(path) { var result = splitPath(path), root = result[0], dir = result[1]; if (!root && !dir) { // No dirname whatsoever return '.'; } if (dir) { // It has a dirname, strip trailing slash dir = dir.substr(0, dir.length - 1); } return root + dir; }; exports.basename = function(path, ext) { var f = splitPath(path)[2]; // TODO: make this comparison case-insensitive on windows? if (ext && f.substr(-1 * ext.length) === ext) { f = f.substr(0, f.length - ext.length); } return f; }; exports.extname = function(path) { return splitPath(path)[3]; }; function filter (xs, f) { if (xs.filter) return xs.filter(f); var res = []; for (var i = 0; i < xs.length; i++) { if (f(xs[i], i, xs)) res.push(xs[i]); } return res; } // String.prototype.substr - negative index don't work in IE8 var substr = 'ab'.substr(-1) === 'b' ? function (str, start, len) { return str.substr(start, len) } : function (str, start, len) { if (start < 0) start = str.length + start; return str.substr(start, len); } ; }).call(this,require('_process')) },{"_process":32}],32:[function(require,module,exports){ // shim for using process in browser var process = module.exports = {}; process.nextTick = (function () { var canSetImmediate = typeof window !== 'undefined' && window.setImmediate; var canMutationObserver = typeof window !== 'undefined' && window.MutationObserver; var canPost = typeof window !== 'undefined' && window.postMessage && window.addEventListener ; if (canSetImmediate) { return function (f) { return window.setImmediate(f) }; } var queue = []; if (canMutationObserver) { var hiddenDiv = document.createElement("div"); var observer = new MutationObserver(function () { var queueList = queue.slice(); queue.length = 0; queueList.forEach(function (fn) { fn(); }); }); observer.observe(hiddenDiv, { attributes: true }); return function nextTick(fn) { if (!queue.length) { hiddenDiv.setAttribute('yes', 'no'); } queue.push(fn); }; } if (canPost) { window.addEventListener('message', function (ev) { var source = ev.source; if ((source === window || source === null) && ev.data === 'process-tick') { ev.stopPropagation(); if (queue.length > 0) { var fn = queue.shift(); fn(); } } }, true); return function nextTick(fn) { queue.push(fn); window.postMessage('process-tick', '*'); }; } return function nextTick(fn) { setTimeout(fn, 0); }; })(); process.title = 'browser'; process.browser = true; process.env = {}; process.argv = []; function noop() {} process.on = noop; process.addListener = noop; process.once = noop; process.off = noop; process.removeListener = noop; process.removeAllListeners = noop; process.emit = noop; process.binding = function (name) { throw new Error('process.binding is not supported'); }; // TODO(shtylman) process.cwd = function () { return '/' }; process.chdir = function (dir) { throw new Error('process.chdir is not supported'); }; },{}],33:[function(require,module,exports){ module.exports = function isBuffer(arg) { return arg && typeof arg === 'object' && typeof arg.copy === 'function' && typeof arg.fill === 'function' && typeof arg.readUInt8 === 'function'; } },{}],34:[function(require,module,exports){ (function (process,global){ // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var formatRegExp = /%[sdj%]/g; exports.format = function(f) { if (!isString(f)) { var objects = []; for (var i = 0; i < arguments.length; i++) { objects.push(inspect(arguments[i])); } return objects.join(' '); } var i = 1; var args = arguments; var len = args.length; var str = String(f).replace(formatRegExp, function(x) { if (x === '%%') return '%'; if (i >= len) return x; switch (x) { case '%s': return String(args[i++]); case '%d': return Number(args[i++]); case '%j': try { return JSON.stringify(args[i++]); } catch (_) { return '[Circular]'; } default: return x; } }); for (var x = args[i]; i < len; x = args[++i]) { if (isNull(x) || !isObject(x)) { str += ' ' + x; } else { str += ' ' + inspect(x); } } return str; }; // Mark that a method should not be used. // Returns a modified function which warns once by default. // If --no-deprecation is set, then it is a no-op. exports.deprecate = function(fn, msg) { // Allow for deprecating things in the process of starting up. if (isUndefined(global.process)) { return function() { return exports.deprecate(fn, msg).apply(this, arguments); }; } if (process.noDeprecation === true) { return fn; } var warned = false; function deprecated() { if (!warned) { if (process.throwDeprecation) { throw new Error(msg); } else if (process.traceDeprecation) { console.trace(msg); } else { console.error(msg); } warned = true; } return fn.apply(this, arguments); } return deprecated; }; var debugs = {}; var debugEnviron; exports.debuglog = function(set) { if (isUndefined(debugEnviron)) debugEnviron = process.env.NODE_DEBUG || ''; set = set.toUpperCase(); if (!debugs[set]) { if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) { var pid = process.pid; debugs[set] = function() { var msg = exports.format.apply(exports, arguments); console.error('%s %d: %s', set, pid, msg); }; } else { debugs[set] = function() {}; } } return debugs[set]; }; /** * Echos the value of a value. Trys to print the value out * in the best way possible given the different types. * * @param {Object} obj The object to print out. * @param {Object} opts Optional options object that alters the output. */ /* legacy: obj, showHidden, depth, colors*/ function inspect(obj, opts) { // default options var ctx = { seen: [], stylize: stylizeNoColor }; // legacy... if (arguments.length >= 3) ctx.depth = arguments[2]; if (arguments.length >= 4) ctx.colors = arguments[3]; if (isBoolean(opts)) { // legacy... ctx.showHidden = opts; } else if (opts) { // got an "options" object exports._extend(ctx, opts); } // set default options if (isUndefined(ctx.showHidden)) ctx.showHidden = false; if (isUndefined(ctx.depth)) ctx.depth = 2; if (isUndefined(ctx.colors)) ctx.colors = false; if (isUndefined(ctx.customInspect)) ctx.customInspect = true; if (ctx.colors) ctx.stylize = stylizeWithColor; return formatValue(ctx, obj, ctx.depth); } exports.inspect = inspect; // http://en.wikipedia.org/wiki/ANSI_escape_code#graphics inspect.colors = { 'bold' : [1, 22], 'italic' : [3, 23], 'underline' : [4, 24], 'inverse' : [7, 27], 'white' : [37, 39], 'grey' : [90, 39], 'black' : [30, 39], 'blue' : [34, 39], 'cyan' : [36, 39], 'green' : [32, 39], 'magenta' : [35, 39], 'red' : [31, 39], 'yellow' : [33, 39] }; // Don't use 'blue' not visible on cmd.exe inspect.styles = { 'special': 'cyan', 'number': 'yellow', 'boolean': 'yellow', 'undefined': 'grey', 'null': 'bold', 'string': 'green', 'date': 'magenta', // "name": intentionally not styling 'regexp': 'red' }; function stylizeWithColor(str, styleType) { var style = inspect.styles[styleType]; if (style) { return '\u001b[' + inspect.colors[style][0] + 'm' + str + '\u001b[' + inspect.colors[style][1] + 'm'; } else { return str; } } function stylizeNoColor(str, styleType) { return str; } function arrayToHash(array) { var hash = {}; array.forEach(function(val, idx) { hash[val] = true; }); return hash; } function formatValue(ctx, value, recurseTimes) { // Provide a hook for user-specified inspect functions. // Check that value is an object with an inspect function on it if (ctx.customInspect && value && isFunction(value.inspect) && // Filter out the util module, it's inspect function is special value.inspect !== exports.inspect && // Also filter out any prototype objects using the circular check. !(value.constructor && value.constructor.prototype === value)) { var ret = value.inspect(recurseTimes, ctx); if (!isString(ret)) { ret = formatValue(ctx, ret, recurseTimes); } return ret; } // Primitive types cannot have properties var primitive = formatPrimitive(ctx, value); if (primitive) { return primitive; } // Look up the keys of the object. var keys = Object.keys(value); var visibleKeys = arrayToHash(keys); if (ctx.showHidden) { keys = Object.getOwnPropertyNames(value); } // IE doesn't make error fields non-enumerable // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx if (isError(value) && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) { return formatError(value); } // Some type of object without properties can be shortcutted. if (keys.length === 0) { if (isFunction(value)) { var name = value.name ? ': ' + value.name : ''; return ctx.stylize('[Function' + name + ']', 'special'); } if (isRegExp(value)) { return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); } if (isDate(value)) { return ctx.stylize(Date.prototype.toString.call(value), 'date'); } if (isError(value)) { return formatError(value); } } var base = '', array = false, braces = ['{', '}']; // Make Array say that they are Array if (isArray(value)) { array = true; braces = ['[', ']']; } // Make functions say that they are functions if (isFunction(value)) { var n = value.name ? ': ' + value.name : ''; base = ' [Function' + n + ']'; } // Make RegExps say that they are RegExps if (isRegExp(value)) { base = ' ' + RegExp.prototype.toString.call(value); } // Make dates with properties first say the date if (isDate(value)) { base = ' ' + Date.prototype.toUTCString.call(value); } // Make error with message first say the error if (isError(value)) { base = ' ' + formatError(value); } if (keys.length === 0 && (!array || value.length == 0)) { return braces[0] + base + braces[1]; } if (recurseTimes < 0) { if (isRegExp(value)) { return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); } else { return ctx.stylize('[Object]', 'special'); } } ctx.seen.push(value); var output; if (array) { output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); } else { output = keys.map(function(key) { return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); }); } ctx.seen.pop(); return reduceToSingleString(output, base, braces); } function formatPrimitive(ctx, value) { if (isUndefined(value)) return ctx.stylize('undefined', 'undefined'); if (isString(value)) { var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') .replace(/'/g, "\\'") .replace(/\\"/g, '"') + '\''; return ctx.stylize(simple, 'string'); } if (isNumber(value)) return ctx.stylize('' + value, 'number'); if (isBoolean(value)) return ctx.stylize('' + value, 'boolean'); // For some reason typeof null is "object", so special case here. if (isNull(value)) return ctx.stylize('null', 'null'); } function formatError(value) { return '[' + Error.prototype.toString.call(value) + ']'; } function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { var output = []; for (var i = 0, l = value.length; i < l; ++i) { if (hasOwnProperty(value, String(i))) { output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, String(i), true)); } else { output.push(''); } } keys.forEach(function(key) { if (!key.match(/^\d+$/)) { output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, key, true)); } }); return output; } function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { var name, str, desc; desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] }; if (desc.get) { if (desc.set) { str = ctx.stylize('[Getter/Setter]', 'special'); } else { str = ctx.stylize('[Getter]', 'special'); } } else { if (desc.set) { str = ctx.stylize('[Setter]', 'special'); } } if (!hasOwnProperty(visibleKeys, key)) { name = '[' + key + ']'; } if (!str) { if (ctx.seen.indexOf(desc.value) < 0) { if (isNull(recurseTimes)) { str = formatValue(ctx, desc.value, null); } else { str = formatValue(ctx, desc.value, recurseTimes - 1); } if (str.indexOf('\n') > -1) { if (array) { str = str.split('\n').map(function(line) { return ' ' + line; }).join('\n').substr(2); } else { str = '\n' + str.split('\n').map(function(line) { return ' ' + line; }).join('\n'); } } } else { str = ctx.stylize('[Circular]', 'special'); } } if (isUndefined(name)) { if (array && key.match(/^\d+$/)) { return str; } name = JSON.stringify('' + key); if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { name = name.substr(1, name.length - 2); name = ctx.stylize(name, 'name'); } else { name = name.replace(/'/g, "\\'") .replace(/\\"/g, '"') .replace(/(^"|"$)/g, "'"); name = ctx.stylize(name, 'string'); } } return name + ': ' + str; } function reduceToSingleString(output, base, braces) { var numLinesEst = 0; var length = output.reduce(function(prev, cur) { numLinesEst++; if (cur.indexOf('\n') >= 0) numLinesEst++; return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; }, 0); if (length > 60) { return braces[0] + (base === '' ? '' : base + '\n ') + ' ' + output.join(',\n ') + ' ' + braces[1]; } return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; } // NOTE: These type checking functions intentionally don't use `instanceof` // because it is fragile and can be easily faked with `Object.create()`. function isArray(ar) { return Array.isArray(ar); } exports.isArray = isArray; function isBoolean(arg) { return typeof arg === 'boolean'; } exports.isBoolean = isBoolean; function isNull(arg) { return arg === null; } exports.isNull = isNull; function isNullOrUndefined(arg) { return arg == null; } exports.isNullOrUndefined = isNullOrUndefined; function isNumber(arg) { return typeof arg === 'number'; } exports.isNumber = isNumber; function isString(arg) { return typeof arg === 'string'; } exports.isString = isString; function isSymbol(arg) { return typeof arg === 'symbol'; } exports.isSymbol = isSymbol; function isUndefined(arg) { return arg === void 0; } exports.isUndefined = isUndefined; function isRegExp(re) { return isObject(re) && objectToString(re) === '[object RegExp]'; } exports.isRegExp = isRegExp; function isObject(arg) { return typeof arg === 'object' && arg !== null; } exports.isObject = isObject; function isDate(d) { return isObject(d) && objectToString(d) === '[object Date]'; } exports.isDate = isDate; function isError(e) { return isObject(e) && (objectToString(e) === '[object Error]' || e instanceof Error); } exports.isError = isError; function isFunction(arg) { return typeof arg === 'function'; } exports.isFunction = isFunction; function isPrimitive(arg) { return arg === null || typeof arg === 'boolean' || typeof arg === 'number' || typeof arg === 'string' || typeof arg === 'symbol' || // ES6 symbol typeof arg === 'undefined'; } exports.isPrimitive = isPrimitive; exports.isBuffer = require('./support/isBuffer'); function objectToString(o) { return Object.prototype.toString.call(o); } function pad(n) { return n < 10 ? '0' + n.toString(10) : n.toString(10); } var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; // 26 Feb 16:19:34 function timestamp() { var d = new Date(); var time = [pad(d.getHours()), pad(d.getMinutes()), pad(d.getSeconds())].join(':'); return [d.getDate(), months[d.getMonth()], time].join(' '); } // log is just a thin wrapper to console.log that prepends a timestamp exports.log = function() { console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments)); }; /** * Inherit the prototype methods from one constructor into another. * * The Function.prototype.inherits from lang.js rewritten as a standalone * function (not on Function.prototype). NOTE: If this file is to be loaded * during bootstrapping this function needs to be rewritten using some native * functions as prototype setup using normal JavaScript does not work as * expected during bootstrapping (see mirror.js in r114903). * * @param {function} ctor Constructor function which needs to inherit the * prototype. * @param {function} superCtor Constructor function to inherit prototype from. */ exports.inherits = require('inherits'); exports._extend = function(origin, add) { // Don't do anything if add isn't an object if (!add || !isObject(add)) return origin; var keys = Object.keys(add); var i = keys.length; while (i--) { origin[keys[i]] = add[keys[i]]; } return origin; }; function hasOwnProperty(obj, prop) { return Object.prototype.hasOwnProperty.call(obj, prop); } }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"./support/isBuffer":33,"_process":32,"inherits":30}],35:[function(require,module,exports){ (function (tree) { tree.functions = { rgb: function (r, g, b) { return this.rgba(r, g, b, 1.0); }, rgba: function (r, g, b, a) { var rgb = [r, g, b].map(function (c) { return number(c); }); a = number(a); if (rgb.some(isNaN) || isNaN(a)) return null; return new tree.Color(rgb, a); }, // Only require val stop: function (val) { var color, mode; if (arguments.length > 1) color = arguments[1]; if (arguments.length > 2) mode = arguments[2]; return { is: 'tag', val: val, color: color, mode: mode, toString: function(env) { return '\n\t'; } }; }, hsl: function (h, s, l) { return this.hsla(h, s, l, 1.0); }, hsla: function (h, s, l, a) { h = (number(h) % 360) / 360; s = number(s); l = number(l); a = number(a); if ([h, s, l, a].some(isNaN)) return null; var m2 = l <= 0.5 ? l * (s + 1) : l + s - l * s, m1 = l * 2 - m2; return this.rgba(hue(h + 1/3) * 255, hue(h) * 255, hue(h - 1/3) * 255, a); function hue(h) { h = h < 0 ? h + 1 : (h > 1 ? h - 1 : h); if (h * 6 < 1) return m1 + (m2 - m1) * h * 6; else if (h * 2 < 1) return m2; else if (h * 3 < 2) return m1 + (m2 - m1) * (2/3 - h) * 6; else return m1; } }, hue: function (color) { if (!('toHSL' in color)) return null; return new tree.Dimension(Math.round(color.toHSL().h)); }, saturation: function (color) { if (!('toHSL' in color)) return null; return new tree.Dimension(Math.round(color.toHSL().s * 100), '%'); }, lightness: function (color) { if (!('toHSL' in color)) return null; return new tree.Dimension(Math.round(color.toHSL().l * 100), '%'); }, alpha: function (color) { if (!('toHSL' in color)) return null; return new tree.Dimension(color.toHSL().a); }, saturate: function (color, amount) { if (!('toHSL' in color)) return null; var hsl = color.toHSL(); hsl.s += amount.value / 100; hsl.s = clamp(hsl.s); return hsla(hsl); }, desaturate: function (color, amount) { if (!('toHSL' in color)) return null; var hsl = color.toHSL(); hsl.s -= amount.value / 100; hsl.s = clamp(hsl.s); return hsla(hsl); }, lighten: function (color, amount) { if (!('toHSL' in color)) return null; var hsl = color.toHSL(); hsl.l += amount.value / 100; hsl.l = clamp(hsl.l); return hsla(hsl); }, darken: function (color, amount) { if (!('toHSL' in color)) return null; var hsl = color.toHSL(); hsl.l -= amount.value / 100; hsl.l = clamp(hsl.l); return hsla(hsl); }, fadein: function (color, amount) { if (!('toHSL' in color)) return null; var hsl = color.toHSL(); hsl.a += amount.value / 100; hsl.a = clamp(hsl.a); return hsla(hsl); }, fadeout: function (color, amount) { if (!('toHSL' in color)) return null; var hsl = color.toHSL(); hsl.a -= amount.value / 100; hsl.a = clamp(hsl.a); return hsla(hsl); }, spin: function (color, amount) { if (!('toHSL' in color)) return null; var hsl = color.toHSL(); var hue = (hsl.h + amount.value) % 360; hsl.h = hue < 0 ? 360 + hue : hue; return hsla(hsl); }, replace: function (entity, a, b) { if (entity.is === 'field') { return entity.toString + '.replace(' + a.toString() + ', ' + b.toString() + ')'; } else { return entity.replace(a, b); } }, // // Copyright (c) 2006-2009 Hampton Catlin, Nathan Weizenbaum, and Chris Eppstein // http://sass-lang.com // mix: function (color1, color2, weight) { var p = weight.value / 100.0; var w = p * 2 - 1; var a = color1.toHSL().a - color2.toHSL().a; var w1 = (((w * a == -1) ? w : (w + a) / (1 + w * a)) + 1) / 2.0; var w2 = 1 - w1; var rgb = [color1.rgb[0] * w1 + color2.rgb[0] * w2, color1.rgb[1] * w1 + color2.rgb[1] * w2, color1.rgb[2] * w1 + color2.rgb[2] * w2]; var alpha = color1.alpha * p + color2.alpha * (1 - p); return new tree.Color(rgb, alpha); }, greyscale: function (color) { return this.desaturate(color, new tree.Dimension(100)); }, '%': function (quoted /* arg, arg, ...*/) { var args = Array.prototype.slice.call(arguments, 1), str = quoted.value; for (var i = 0; i < args.length; i++) { str = str.replace(/%s/, args[i].value) .replace(/%[da]/, args[i].toString()); } str = str.replace(/%%/g, '%'); return new tree.Quoted(str); } }; var image_filter_functors = [ 'emboss', 'blur', 'gray', 'sobel', 'edge-detect', 'x-gradient', 'y-gradient', 'sharpen']; for (var i = 0; i < image_filter_functors.length; i++) { var f = image_filter_functors[i]; tree.functions[f] = (function(f) { return function() { return new tree.ImageFilter(f); }; })(f); } tree.functions['agg-stack-blur'] = function(x, y) { return new tree.ImageFilter('agg-stack-blur', [x, y]); }; tree.functions['scale-hsla'] = function(h0,h1,s0,s1,l0,l1,a0,a1) { return new tree.ImageFilter('scale-hsla', [h0,h1,s0,s1,l0,l1,a0,a1]); }; function hsla(h) { return tree.functions.hsla(h.h, h.s, h.l, h.a); } function number(n) { if (n instanceof tree.Dimension) { return parseFloat(n.unit == '%' ? n.value / 100 : n.value); } else if (typeof(n) === 'number') { return n; } else { return NaN; } } function clamp(val) { return Math.min(1, Math.max(0, val)); } })(require('./tree')); },{"./tree":41}],36:[function(require,module,exports){ (function (process,__dirname){ var util = require('util'), fs = require('fs'), path = require('path'); function getVersion() { if (process.browser) { return require('../../package.json').version.split('.'); } else if (parseInt(process.version.split('.')[1], 10) > 4) { return require('../../package.json').version.split('.'); } else { // older node var package_json = JSON.parse(fs.readFileSync(path.join(__dirname,'../../package.json'))); return package_json.version.split('.'); } } var carto = { version: getVersion(), Parser: require('./parser').Parser, Renderer: require('./renderer').Renderer, tree: require('./tree'), RendererJS: require('./renderer_js'), default_reference: require('./torque-reference'), // @TODO writeError: function(ctx, options) { var message = ''; var extract = ctx.extract; var error = []; options = options || {}; if (options.silent) { return; } options.indent = options.indent || ''; if (!('index' in ctx) || !extract) { return util.error(options.indent + (ctx.stack || ctx.message)); } if (typeof(extract[0]) === 'string') { error.push(stylize((ctx.line - 1) + ' ' + extract[0], 'grey')); } if (extract[1] === '' && typeof extract[2] === 'undefined') { extract[1] = '¶'; } error.push(ctx.line + ' ' + extract[1].slice(0, ctx.column) + stylize(stylize(extract[1][ctx.column], 'bold') + extract[1].slice(ctx.column + 1), 'yellow')); if (typeof(extract[2]) === 'string') { error.push(stylize((ctx.line + 1) + ' ' + extract[2], 'grey')); } error = options.indent + error.join('\n' + options.indent) + '\033[0m\n'; message = options.indent + message + stylize(ctx.message, 'red'); if (ctx.filename) (message += stylize(' in ', 'red') + ctx.filename); util.error(message, error); if (ctx.callLine) { util.error(stylize('from ', 'red') + (ctx.filename || '')); util.error(stylize(ctx.callLine, 'grey') + ' ' + ctx.callExtract); } if (ctx.stack) { util.error(stylize(ctx.stack, 'red')); } } }; require('./tree/call'); require('./tree/color'); require('./tree/comment'); require('./tree/definition'); require('./tree/dimension'); require('./tree/element'); require('./tree/expression'); require('./tree/filterset'); require('./tree/filter'); require('./tree/field'); require('./tree/keyword'); require('./tree/layer'); require('./tree/literal'); require('./tree/operation'); require('./tree/quoted'); require('./tree/imagefilter'); require('./tree/reference'); require('./tree/rule'); require('./tree/ruleset'); require('./tree/selector'); require('./tree/style'); require('./tree/url'); require('./tree/value'); require('./tree/variable'); require('./tree/zoom'); require('./tree/invalid'); require('./tree/fontset'); require('./tree/frame_offset'); require('./functions'); for (var k in carto) { exports[k] = carto[k]; } // Stylize a string function stylize(str, style) { var styles = { 'bold' : [1, 22], 'inverse' : [7, 27], 'underline' : [4, 24], 'yellow' : [33, 39], 'green' : [32, 39], 'red' : [31, 39], 'grey' : [90, 39] }; return '\033[' + styles[style][0] + 'm' + str + '\033[' + styles[style][1] + 'm'; } }).call(this,require('_process'),"/node_modules/carto/lib/carto") },{"../../package.json":72,"./functions":35,"./parser":37,"./renderer":38,"./renderer_js":39,"./torque-reference":40,"./tree":41,"./tree/call":42,"./tree/color":43,"./tree/comment":44,"./tree/definition":45,"./tree/dimension":46,"./tree/element":47,"./tree/expression":48,"./tree/field":49,"./tree/filter":50,"./tree/filterset":51,"./tree/fontset":52,"./tree/frame_offset":53,"./tree/imagefilter":54,"./tree/invalid":55,"./tree/keyword":56,"./tree/layer":57,"./tree/literal":58,"./tree/operation":59,"./tree/quoted":60,"./tree/reference":61,"./tree/rule":62,"./tree/ruleset":63,"./tree/selector":64,"./tree/style":65,"./tree/url":66,"./tree/value":67,"./tree/variable":68,"./tree/zoom":69,"_process":32,"fs":28,"path":31,"util":34}],37:[function(require,module,exports){ (function (global){ var carto = exports, tree = require('./tree'), _ = global._ || require('underscore'); // Token matching is done with the `$` function, which either takes // a terminal string or regexp, or a non-terminal function to call. // It also takes care of moving all the indices forwards. carto.Parser = function Parser(env) { var input, // LeSS input string i, // current index in `input` j, // current chunk temp, // temporarily holds a chunk's state, for backtracking memo, // temporarily holds `i`, when backtracking furthest, // furthest index the parser has gone to chunks, // chunkified input current, // index of current chunk, in `input` parser; var that = this; // This function is called after all files // have been imported through `@import`. var finish = function() {}; function save() { temp = chunks[j]; memo = i; current = i; } function restore() { chunks[j] = temp; i = memo; current = i; } function sync() { if (i > current) { chunks[j] = chunks[j].slice(i - current); current = i; } } // // Parse from a token, regexp or string, and move forward if match // function $(tok) { var match, args, length, c, index, endIndex, k; // Non-terminal if (tok instanceof Function) { return tok.call(parser.parsers); // Terminal // Either match a single character in the input, // or match a regexp in the current chunk (chunk[j]). } else if (typeof(tok) === 'string') { match = input.charAt(i) === tok ? tok : null; length = 1; sync(); } else { sync(); match = tok.exec(chunks[j]); if (match) { length = match[0].length; } else { return null; } } // The match is confirmed, add the match length to `i`, // and consume any extra white-space characters (' ' || '\n') // which come after that. The reason for this is that LeSS's // grammar is mostly white-space insensitive. if (match) { var mem = i += length; endIndex = i + chunks[j].length - length; while (i < endIndex) { c = input.charCodeAt(i); if (! (c === 32 || c === 10 || c === 9)) { break; } i++; } chunks[j] = chunks[j].slice(length + (i - mem)); current = i; if (chunks[j].length === 0 && j < chunks.length - 1) { j++; } if (typeof(match) === 'string') { return match; } else { return match.length === 1 ? match[0] : match; } } } // Same as $(), but don't change the state of the parser, // just return the match. function peek(tok) { if (typeof(tok) === 'string') { return input.charAt(i) === tok; } else { return !!tok.test(chunks[j]); } } function extractErrorLine(style, errorIndex) { return (style.slice(0, errorIndex).match(/\n/g) || '').length + 1; } // Make an error object from a passed set of properties. // Accepted properties: // - `message`: Text of the error message. // - `filename`: Filename where the error occurred. // - `index`: Char. index where the error occurred. function makeError(err) { var einput; _(err).defaults({ index: furthest, filename: env.filename, message: 'Parse error.', line: 0, column: -1 }); if (err.filename && that.env.inputs && that.env.inputs[err.filename]) { einput = that.env.inputs[err.filename]; } else { einput = input; } err.line = extractErrorLine(einput, err.index); for (var n = err.index; n >= 0 && einput.charAt(n) !== '\n'; n--) { err.column++; } return new Error(_('<%=filename%>:<%=line%>:<%=column%> <%=message%>').template(err)); } this.env = env = env || {}; this.env.filename = this.env.filename || null; this.env.inputs = this.env.inputs || {}; // The Parser parser = { extractErrorLine: extractErrorLine, // // Parse an input string into an abstract syntax tree. // Throws an error on parse errors. parse: function(str) { var root, start, end, zone, line, lines, buff = [], c, error = null; i = j = current = furthest = 0; chunks = []; input = str.replace(/\r\n/g, '\n'); if (env.filename) { that.env.inputs[env.filename] = input; } var early_exit = false; // Split the input into chunks. chunks = (function (chunks) { var j = 0, skip = /(?:@\{[\w-]+\}|[^"'`\{\}\/\(\)\\])+/g, comment = /\/\*(?:[^*]|\*+[^\/*])*\*+\/|\/\/.*/g, string = /"((?:[^"\\\r\n]|\\.)*)"|'((?:[^'\\\r\n]|\\.)*)'|`((?:[^`]|\\.)*)`/g, level = 0, match, chunk = chunks[0], inParam; for (var i = 0, c, cc; i < input.length;) { skip.lastIndex = i; if (match = skip.exec(input)) { if (match.index === i) { i += match[0].length; chunk.push(match[0]); } } c = input.charAt(i); comment.lastIndex = string.lastIndex = i; if (match = string.exec(input)) { if (match.index === i) { i += match[0].length; chunk.push(match[0]); continue; } } if (!inParam && c === '/') { cc = input.charAt(i + 1); if (cc === '/' || cc === '*') { if (match = comment.exec(input)) { if (match.index === i) { i += match[0].length; chunk.push(match[0]); continue; } } } } switch (c) { case '{': if (! inParam) { level ++; chunk.push(c); break; } case '}': if (! inParam) { level --; chunk.push(c); chunks[++j] = chunk = []; break; } case '(': if (! inParam) { inParam = true; chunk.push(c); break; } case ')': if ( inParam) { inParam = false; chunk.push(c); break; } default: chunk.push(c); } i++; } if (level !== 0) { error = { index: i - 1, type: 'Parse', message: (level > 0) ? "missing closing `}`" : "missing opening `{`" }; } return chunks.map(function (c) { return c.join(''); }); })([[]]); if (error) { throw makeError(error); } // Start with the primary rule. // The whole syntax tree is held under a Ruleset node, // with the `root` property set to true, so no `{}` are // output. root = new tree.Ruleset([], $(this.parsers.primary)); root.root = true; // Get an array of Ruleset objects, flattened // and sorted according to specificitySort root.toList = (function() { var line, lines, column; return function(env) { env.error = function(e) { if (!env.errors) env.errors = new Error(''); if (env.errors.message) { env.errors.message += '\n' + makeError(e).message; } else { env.errors.message = makeError(e).message; } }; env.frames = env.frames || []; // call populates Invalid-caused errors var definitions = this.flatten([], [], env); definitions.sort(specificitySort); return definitions; }; })(); // Sort rules by specificity: this function expects selectors to be // split already. // // Written to be used as a .sort(Function); // argument. // // [1, 0, 0, 467] > [0, 0, 1, 520] var specificitySort = function(a, b) { var as = a.specificity; var bs = b.specificity; if (as[0] != bs[0]) return bs[0] - as[0]; if (as[1] != bs[1]) return bs[1] - as[1]; if (as[2] != bs[2]) return bs[2] - as[2]; return bs[3] - as[3]; }; return root; }, // Here in, the parsing rules/functions // // The basic structure of the syntax tree generated is as follows: // // Ruleset -> Rule -> Value -> Expression -> Entity // // In general, most rules will try to parse a token with the `$()` function, and if the return // value is truly, will return a new node, of the relevant type. Sometimes, we need to check // first, before parsing, that's when we use `peek()`. parsers: { // The `primary` rule is the *entry* and *exit* point of the parser. // The rules here can appear at any level of the parse tree. // // The recursive nature of the grammar is an interplay between the `block` // rule, which represents `{ ... }`, the `ruleset` rule, and this `primary` rule, // as represented by this simplified grammar: // // primary → (ruleset | rule)+ // ruleset → selector+ block // block → '{' primary '}' // // Only at one point is the primary rule not called from the // block rule: at the root level. primary: function() { var node, root = []; while ((node = $(this.rule) || $(this.ruleset) || $(this.comment)) || $(/^[\s\n]+/) || (node = $(this.invalid))) { if (node) root.push(node); } return root; }, invalid: function () { var chunk = $(/^[^;\n]*[;\n]/); // To fail gracefully, match everything until a semicolon or linebreak. if (chunk) { return new tree.Invalid(chunk, memo); } }, // We create a Comment node for CSS comments `/* */`, // but keep the LeSS comments `//` silent, by just skipping // over them. comment: function() { var comment; if (input.charAt(i) !== '/') return; if (input.charAt(i + 1) === '/') { return new tree.Comment($(/^\/\/.*/), true); } else if (comment = $(/^\/\*(?:[^*]|\*+[^\/*])*\*+\/\n?/)) { return new tree.Comment(comment); } }, // Entities are tokens which can be found inside an Expression entities: { // A string, which supports escaping " and ' "milky way" 'he\'s the one!' quoted: function() { if (input.charAt(i) !== '"' && input.charAt(i) !== "'") return; var str = $(/^"((?:[^"\\\r\n]|\\.)*)"|'((?:[^'\\\r\n]|\\.)*)'/); if (str) { return new tree.Quoted(str[1] || str[2]); } }, // A reference to a Mapnik field, like [NAME] // Behind the scenes, this has the same representation, but Carto // needs to be careful to warn when unsupported operations are used. field: function() { if (! $('[')) return; var field_name = $(/(^[^\]]+)/); if (! $(']')) return; if (field_name) return new tree.Field(field_name[1]); }, // This is a comparison operator comparison: function() { var str = $(/^=~|=|!=|<=|>=|<|>/); if (str) { return str; } }, // A catch-all word, such as: hard-light // These can start with either a letter or a dash (-), // and then contain numbers, underscores, and letters. keyword: function() { var k = $(/^[A-Za-z-]+[A-Za-z-0-9_]*/); if (k) { return new tree.Keyword(k); } }, // A function call like rgb(255, 0, 255) // The arguments are parsed with the `entities.arguments` parser. call: function() { var name, args; if (!(name = /^([\w\-]+|%)\(/.exec(chunks[j]))) return; name = name[1]; if (name === 'url') { // url() is handled by the url parser instead return null; } else { i += name.length; } $('('); // Parse the '(' and consume whitespace. args = $(this.entities['arguments']); if (!$(')')) return; if (name) { return new tree.Call(name, args, i); } }, // Arguments are comma-separated expressions 'arguments': function() { var args = [], arg; while (arg = $(this.expression)) { args.push(arg); if (! $(',')) { break; } } return args; }, literal: function() { return $(this.entities.dimension) || $(this.entities.keywordcolor) || $(this.entities.hexcolor) || $(this.entities.quoted); }, // Parse url() tokens // // We use a specific rule for urls, because they don't really behave like // standard function calls. The difference is that the argument doesn't have // to be enclosed within a string, so it can't be parsed as an Expression. url: function() { var value; if (input.charAt(i) !== 'u' || !$(/^url\(/)) return; value = $(this.entities.quoted) || $(this.entities.variable) || $(/^[\-\w%@$\/.&=:;#+?~]+/) || ''; if (! $(')')) { return new tree.Invalid(value, memo, 'Missing closing ) in URL.'); } else { return new tree.URL((typeof value.value !== 'undefined' || value instanceof tree.Variable) ? value : new tree.Quoted(value)); } }, // A Variable entity, such as `@fink`, in // // width: @fink + 2px // // We use a different parser for variable definitions, // see `parsers.variable`. variable: function() { var name, index = i; if (input.charAt(i) === '@' && (name = $(/^@[\w-]+/))) { return new tree.Variable(name, index, env.filename); } }, hexcolor: function() { var rgb; if (input.charAt(i) === '#' && (rgb = $(/^#([a-fA-F0-9]{6}|[a-fA-F0-9]{3})/))) { return new tree.Color(rgb[1]); } }, keywordcolor: function() { var rgb = chunks[j].match(/^[a-z]+/); if (rgb && rgb[0] in tree.Reference.data.colors) { return new tree.Color(tree.Reference.data.colors[$(/^[a-z]+/)]); } }, // A Dimension, that is, a number and a unit. The only // unit that has an effect is % dimension: function() { var c = input.charCodeAt(i); if ((c > 57 || c < 45) || c === 47) return; var value = $(/^(-?\d*\.?\d+(?:[eE][-+]?\d+)?)(\%|\w+)?/); if (value) { return new tree.Dimension(value[1], value[2], memo); } } }, // The variable part of a variable definition. // Used in the `rule` parser. Like @fink: variable: function() { var name; if (input.charAt(i) === '@' && (name = $(/^(@[\w-]+)\s*:/))) { return name[1]; } }, // Entities are the smallest recognized token, // and can be found inside a rule's value. entity: function() { return $(this.entities.call) || $(this.entities.literal) || $(this.entities.field) || $(this.entities.variable) || $(this.entities.url) || $(this.entities.keyword); }, // A Rule terminator. Note that we use `peek()` to check for '}', // because the `block` rule will be expecting it, but we still need to make sure // it's there, if ';' was ommitted. end: function() { return $(';') || peek('}'); }, // Elements are the building blocks for Selectors. They consist of // an element name, such as a tag a class, or `*`. element: function() { var e = $(/^(?:[.#][\w\-]+|\*|Map)/); if (e) return new tree.Element(e); }, // Attachments allow adding multiple lines, polygons etc. to an // object. There can only be one attachment per selector. attachment: function() { var s = $(/^::([\w\-]+(?:\/[\w\-]+)*)/); if (s) return s[1]; }, // Selectors are made out of one or more Elements, see above. selector: function() { var a, attachment, e, elements = [], f, filters = new tree.Filterset(), z, zooms = [], frame_offset = tree.FrameOffset.none; segments = 0, conditions = 0; while ( (e = $(this.element)) || (z = $(this.zoom)) || (fo = $(this.frame_offset)) || (f = $(this.filter)) || (a = $(this.attachment)) ) { segments++; if (e) { elements.push(e); } else if (z) { zooms.push(z); conditions++; } else if (fo) { frame_offset = fo; conditions++; } else if (f) { var err = filters.add(f); if (err) { throw makeError({ message: err, index: i - 1 }); } conditions++; } else if (attachment) { throw makeError({ message: 'Encountered second attachment name.', index: i - 1 }); } else { attachment = a; } var c = input.charAt(i); if (c === '{' || c === '}' || c === ';' || c === ',') { break; } } if (segments) { return new tree.Selector(filters, zooms, frame_offset, elements, attachment, conditions, memo); } }, filter: function() { save(); var key, op, val; if (! $('[')) return; if (key = $(/^[a-zA-Z0-9\-_]+/) || $(this.entities.quoted) || $(this.entities.variable) || $(this.entities.keyword) || $(this.entities.field)) { // TODO: remove at 1.0.0 if (key instanceof tree.Quoted) { key = new tree.Field(key.toString()); } if ((op = $(this.entities.comparison)) && (val = $(this.entities.quoted) || $(this.entities.variable) || $(this.entities.dimension) || $(this.entities.keyword) || $(this.entities.field))) { if (! $(']')) { throw makeError({ message: 'Missing closing ] of filter.', index: memo - 1 }); } if (!key.is) key = new tree.Field(key); return new tree.Filter(key, op, val, memo, env.filename); } } }, frame_offset: function() { save(); var op, val; if ($(/^\[\s*frame-offset/g) && (op = $(this.entities.comparison)) && (val = $(/^\d+/)) && $(']')) { return tree.FrameOffset(op, val, memo); } }, zoom: function() { save(); var op, val; if ($(/^\[\s*zoom/g) && (op = $(this.entities.comparison)) && (val = $(this.entities.variable) || $(this.entities.dimension)) && $(']')) { return new tree.Zoom(op, val, memo); } else { // backtrack restore(); } }, // The `block` rule is used by `ruleset` // It's a wrapper around the `primary` rule, with added `{}`. block: function() { var content; if ($('{') && (content = $(this.primary)) && $('}')) { return content; } }, // div, .class, body > p {...} ruleset: function() { var selectors = [], s, f, l, rules, filters = []; save(); while (s = $(this.selector)) { selectors.push(s); while ($(this.comment)) {} if (! $(',')) { break; } while ($(this.comment)) {} } if (s) { while ($(this.comment)) {} } if (selectors.length > 0 && (rules = $(this.block))) { if (selectors.length === 1 && selectors[0].elements.length && selectors[0].elements[0].value === 'Map') { var rs = new tree.Ruleset(selectors, rules); rs.isMap = true; return rs; } return new tree.Ruleset(selectors, rules); } else { // Backtrack restore(); } }, rule: function() { var name, value, c = input.charAt(i); save(); if (c === '.' || c === '#') { return; } if (name = $(this.variable) || $(this.property)) { value = $(this.value); if (value && $(this.end)) { return new tree.Rule(name, value, memo, env.filename); } else { furthest = i; restore(); } } }, font: function() { var value = [], expression = [], weight, font, e; while (e = $(this.entity)) { expression.push(e); } value.push(new tree.Expression(expression)); if ($(',')) { while (e = $(this.expression)) { value.push(e); if (! $(',')) { break; } } } return new tree.Value(value); }, // A Value is a comma-delimited list of Expressions // In a Rule, a Value represents everything after the `:`, // and before the `;`. value: function() { var e, expressions = []; while (e = $(this.expression)) { expressions.push(e); if (! $(',')) { break; } } if (expressions.length > 1) { return new tree.Value(expressions.map(function(e) { return e.value[0]; })); } else if (expressions.length === 1) { return new tree.Value(expressions); } }, // A sub-expression, contained by parenthensis sub: function() { var e; if ($('(') && (e = $(this.expression)) && $(')')) { return e; } }, // This is a misnomer because it actually handles multiplication // and division. multiplication: function() { var m, a, op, operation; if (m = $(this.operand)) { while ((op = ($('/') || $('*') || $('%'))) && (a = $(this.operand))) { operation = new tree.Operation(op, [operation || m, a], memo); } return operation || m; } }, addition: function() { var m, a, op, operation; if (m = $(this.multiplication)) { while ((op = $(/^[-+]\s+/) || (input.charAt(i - 1) != ' ' && ($('+') || $('-')))) && (a = $(this.multiplication))) { operation = new tree.Operation(op, [operation || m, a], memo); } return operation || m; } }, // An operand is anything that can be part of an operation, // such as a Color, or a Variable operand: function() { return $(this.sub) || $(this.entity); }, // Expressions either represent mathematical operations, // or white-space delimited Entities. @var * 2 expression: function() { var e, delim, entities = [], d; while (e = $(this.addition) || $(this.entity)) { entities.push(e); } if (entities.length > 0) { return new tree.Expression(entities); } }, property: function() { var name = $(/^(([a-z][-a-z_0-9]*\/)?\*?-?[-a-z_0-9]+)\s*:/); if (name) return name[1]; } } }; return parser; }; }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"./tree":41,"underscore":71}],38:[function(require,module,exports){ (function (global){ var _ = global._ || require('underscore'); var carto = require('./index'); carto.Renderer = function Renderer(env, options) { this.env = env || {}; this.options = options || {}; this.options.mapnik_version = this.options.mapnik_version || '3.0.0'; }; /** * Prepare a MSS document (given as an string) into a * XML Style fragment (mostly useful for debugging) * * @param {String} data the mss contents as a string. */ carto.Renderer.prototype.renderMSS = function render(data) { // effects is a container for side-effects, which currently // are limited to FontSets. var env = _(this.env).defaults({ benchmark: false, validation_data: false, effects: [] }); if (!carto.tree.Reference.setVersion(this.options.mapnik_version)) { throw new Error("Could not set mapnik version to " + this.options.mapnik_version); } var output = []; var styles = []; if (env.benchmark) console.time('Parsing MSS'); var parser = (carto.Parser(env)).parse(data); if (env.benchmark) console.timeEnd('Parsing MSS'); if (env.benchmark) console.time('Rule generation'); var rule_list = parser.toList(env); if (env.benchmark) console.timeEnd('Rule generation'); if (env.benchmark) console.time('Rule inheritance'); var rules = inheritDefinitions(rule_list, env); if (env.benchmark) console.timeEnd('Rule inheritance'); if (env.benchmark) console.time('Style sort'); var sorted = sortStyles(rules,env); if (env.benchmark) console.timeEnd('Style sort'); if (env.benchmark) console.time('Total Style generation'); for (var k = 0, rule, style_name; k < sorted.length; k++) { rule = sorted[k]; style_name = 'style' + (rule.attachment !== '__default__' ? '-' + rule.attachment : ''); styles.push(style_name); var bench_name = '\tStyle "'+style_name+'" (#'+k+') toXML'; if (env.benchmark) console.time(bench_name); // env.effects can be modified by this call output.push(carto.tree.StyleXML(style_name, rule.attachment, rule, env)); if (env.benchmark) console.timeEnd(bench_name); } if (env.benchmark) console.timeEnd('Total Style generation'); if (env.errors) throw env.errors; return output.join('\n'); }; /** * Prepare a MML document (given as an object) into a * fully-localized XML file ready for Mapnik2 consumption * * @param {String} m - the JSON file as a string. */ carto.Renderer.prototype.render = function render(m) { // effects is a container for side-effects, which currently // are limited to FontSets. var env = _(this.env).defaults({ benchmark: false, validation_data: false, effects: [], ppi: 90.714 }); if (!carto.tree.Reference.setVersion(this.options.mapnik_version)) { throw new Error("Could not set mapnik version to " + this.options.mapnik_version); } var output = []; // Transform stylesheets into definitions. var definitions = _(m.Stylesheet).chain() .map(function(s) { if (typeof s == 'string') { throw new Error("Stylesheet object is expected not a string: '" + s + "'"); } // Passing the environment from stylesheet to stylesheet, // allows frames and effects to be maintained. env = _(env).extend({filename:s.id}); var time = +new Date(), root = (carto.Parser(env)).parse(s.data); if (env.benchmark) console.warn('Parsing time: ' + (new Date() - time) + 'ms'); return root.toList(env); }) .flatten() .value(); function appliesTo(name, classIndex) { return function(definition) { return definition.appliesTo(l.name, classIndex); }; } // Iterate through layers and create styles custom-built // for each of them, and apply those styles to the layers. var styles, l, classIndex, rules, sorted, matching; for (var i = 0; i < m.Layer.length; i++) { l = m.Layer[i]; styles = []; classIndex = {}; if (env.benchmark) console.warn('processing layer: ' + l.id); // Classes are given as space-separated alphanumeric strings. var classes = (l['class'] || '').split(/\s+/g); for (var j = 0; j < classes.length; j++) { classIndex[classes[j]] = true; } matching = definitions.filter(appliesTo(l.name, classIndex)); rules = inheritDefinitions(matching, env); sorted = sortStyles(rules, env); for (var k = 0, rule, style_name; k < sorted.length; k++) { rule = sorted[k]; style_name = l.name + (rule.attachment !== '__default__' ? '-' + rule.attachment : ''); // env.effects can be modified by this call var styleXML = carto.tree.StyleXML(style_name, rule.attachment, rule, env); if (styleXML) { output.push(styleXML); styles.push(style_name); } } output.push(carto.tree.LayerXML(l, styles)); } output.unshift(env.effects.map(function(e) { return e.toXML(env); }).join('\n')); var map_properties = getMapProperties(m, definitions, env); // Exit on errors. if (env.errors) throw env.errors; // Pass TileJSON and other custom parameters through to Mapnik XML. var parameters = _(m).reduce(function(memo, v, k) { if (!v && v !== 0) return memo; switch (k) { // Known skippable properties. case 'srs': case 'Layer': case 'Stylesheet': break; // Non URL-bound TileJSON properties. case 'bounds': case 'center': case 'minzoom': case 'maxzoom': case 'version': memo.push(' ' + v + ''); break; // Properties that require CDATA. case 'name': case 'description': case 'legend': case 'attribution': case 'template': memo.push(' '); break; // Mapnik image format. case 'format': memo.push(' ' + v + ''); break; // Mapnik interactivity settings. case 'interactivity': memo.push(' ' + v.layer + ''); memo.push(' ' + v.fields + ''); break; // Support any additional scalar properties. default: if ('string' === typeof v) { memo.push(' '); } else if ('number' === typeof v) { memo.push(' ' + v + ''); } else if ('boolean' === typeof v) { memo.push(' ' + v + ''); } break; } return memo; }, []); if (parameters.length) output.unshift( '\n' + parameters.join('\n') + '\n\n' ); var properties = _(map_properties).map(function(v) { return ' ' + v; }).join(''); output.unshift( '\n' + '\n' + '\n'); output.push(''); return output.join('\n'); }; /** * This function currently modifies 'current' * @param {Array} current current list of rules * @param {Object} definition a Definition object to add to the rules * @param {Object} byFilter an object/dictionary of existing filters. This is * actually keyed `attachment->filter` * @param {Object} env the current environment */ function addRules(current, definition, byFilter, env) { var newFilters = definition.filters, newRules = definition.rules, updatedFilters, clone, previous; // The current definition might have been split up into // multiple definitions already. for (var k = 0; k < current.length; k++) { updatedFilters = current[k].filters.cloneWith(newFilters); if (updatedFilters) { previous = byFilter[updatedFilters]; if (previous) { // There's already a definition with those exact // filters. Add the current definitions' rules // and stop processing it as the existing rule // has already gone down the inheritance chain. previous.addRules(newRules); } else { clone = current[k].clone(updatedFilters); // Make sure that we're only maintaining the clone // when we did actually add rules. If not, there's // no need to keep the clone around. if (clone.addRules(newRules)) { // We inserted an element before this one, so we need // to make sure that in the next loop iteration, we're // not performing the same task for this element again, // hence the k++. byFilter[updatedFilters] = clone; current.splice(k, 0, clone); k++; } } } else if (updatedFilters === null) { // if updatedFilters is null, then adding the filters doesn't // invalidate or split the selector, so we addRules to the // combined selector // Filters can be added, but they don't change the // filters. This means we don't have to split the // definition. // // this is cloned here because of shared classes, see // sharedclass.mss current[k] = current[k].clone(); current[k].addRules(newRules); } // if updatedFeatures is false, then the filters split the rule, // so they aren't the same inheritance chain } return current; } /** * Apply inherited styles from their ancestors to them. * * called either once per render (in the case of mss) or per layer * (for mml) * * @param {Object} definitions - a list of definitions objects * that contain .rules * @param {Object} env - the environment * @return {Array} an array of arrays is returned, * in which each array refers to a specific attachment */ function inheritDefinitions(definitions, env) { var inheritTime = +new Date(); // definitions are ordered by specificity, // high (index 0) to low var byAttachment = {}, byFilter = {}; var result = []; var current, previous, attachment; // Evaluate the filters specified by each definition with the given // environment to correctly resolve variable references definitions.forEach(function(d) { d.filters.ev(env); }); for (var i = 0; i < definitions.length; i++) { attachment = definitions[i].attachment; current = [definitions[i]]; if (!byAttachment[attachment]) { byAttachment[attachment] = []; byAttachment[attachment].attachment = attachment; byFilter[attachment] = {}; result.push(byAttachment[attachment]); } // Iterate over all subsequent rules. for (var j = i + 1; j < definitions.length; j++) { if (definitions[j].attachment === attachment) { // Only inherit rules from the same attachment. current = addRules(current, definitions[j], byFilter[attachment], env); } } for (var k = 0; k < current.length; k++) { byFilter[attachment][current[k].filters] = current[k]; byAttachment[attachment].push(current[k]); } } if (env.benchmark) console.warn('Inheritance time: ' + ((new Date() - inheritTime)) + 'ms'); return result; } // Sort styles by the minimum index of their rules. // This sorts a slice of the styles, so it returns a sorted // array but does not change the input. function sortStylesIndex(a, b) { return b.index - a.index; } function sortStyles(styles, env) { for (var i = 0; i < styles.length; i++) { var style = styles[i]; style.index = Infinity; for (var b = 0; b < style.length; b++) { var rules = style[b].rules; for (var r = 0; r < rules.length; r++) { var rule = rules[r]; if (rule.index < style.index) { style.index = rule.index; } } } } var result = styles.slice(); result.sort(sortStylesIndex); return result; } /** * Find a rule like Map { background-color: #fff; }, * if any, and return a list of properties to be inserted * into the = minzoom - 1e-6 and scale < maxzoom + 1e-6" }, "maxzoom": { "default-value": "1.79769e+308", "type":"float", "default-meaning": "The layer will be visible at the maximum possible scale", "doc": "The maximum scale denominator that this layer will be visible at. The default is the numeric limit of the C++ double type, which may vary slightly by system, but is likely a massive number like 1.79769e+308 and ensures that this layer will always be visible unless the value is reduced. A layer's visibility is determined by whether its status is true and if the Map scale >= minzoom - 1e-6 and scale < maxzoom + 1e-6" }, "queryable": { "default-value": false, "type":"boolean", "default-meaning": "The layer will not be available for the direct querying of data values", "doc": "This property was added for GetFeatureInfo/WMS compatibility and is rarely used. It is off by default meaning that in a WMS context the layer will not be able to be queried unless the property is explicitly set to true" }, "clear-label-cache": { "default-value": false, "type":"boolean", "default-meaning": "The renderer's collision detector cache (used for avoiding duplicate labels and overlapping markers) will not be cleared immediately before processing this layer", "doc": "This property, by default off, can be enabled to allow a user to clear the collision detector cache before a given layer is processed. This may be desirable to ensure that a given layers data shows up on the map even if it normally would not because of collisions with previously rendered labels or markers" }, "group-by": { "default-value": "", "type":"string", "default-meaning": "No special layer grouping will be used during rendering", "doc": "https://github.com/mapnik/mapnik/wiki/Grouped-rendering" }, "buffer-size": { "default-value": "0", "type":"float", "default-meaning": "No buffer will be used", "doc": "Extra tolerance around the Layer extent (in pixels) used to when querying and (potentially) clipping the layer data during rendering" }, "maximum-extent": { "default-value": "none", "type":"bbox", "default-meaning": "No clipping extent will be used", "doc": "An extent to be used to limit the bounds used to query this specific layer data during rendering. Should be minx, miny, maxx, maxy in the coordinates of the Layer." } }, "symbolizers" : { "*": { "image-filters": { "css": "image-filters", "default-value": "none", "default-meaning": "no filters", "type": "functions", "functions": [ ["agg-stack-blur", 2], ["emboss", 0], ["blur", 0], ["gray", 0], ["sobel", 0], ["edge-detect", 0], ["x-gradient", 0], ["y-gradient", 0], ["invert", 0], ["sharpen", 0], ["colorize-alpha", -1], ["color-to-alpha", 1], ["scale-hsla", 8] ], "doc": "A list of image filters." }, "comp-op": { "css": "comp-op", "default-value": "src-over", "default-meaning": "add the current layer on top of other layers", "doc": "Composite operation. This defines how this layer should behave relative to layers atop or below it.", "type": ["clear", "src", "dst", "src-over", "source-over", // added for torque "dst-over", "src-in", "dst-in", "src-out", "dst-out", "src-atop", "dst-atop", "xor", "plus", "minus", "multiply", "screen", "overlay", "darken", "lighten", "lighter", // added for torque "color-dodge", "color-burn", "hard-light", "soft-light", "difference", "exclusion", "contrast", "invert", "invert-rgb", "grain-merge", "grain-extract", "hue", "saturation", "color", "value" ] }, "opacity": { "css": "opacity", "type": "float", "doc": "An alpha value for the style (which means an alpha applied to all features in separate buffer and then composited back to main buffer)", "default-value": 1, "default-meaning": "no separate buffer will be used and no alpha will be applied to the style after rendering" } }, "map": { "background-color": { "css": "background-color", "default-value": "none", "default-meaning": "transparent", "type": "color", "doc": "Map Background color" }, "background-image": { "css": "background-image", "type": "uri", "default-value": "", "default-meaning": "transparent", "doc": "An image that is repeated below all features on a map as a background.", "description": "Map Background image" }, "srs": { "css": "srs", "type": "string", "default-value": "+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs", "default-meaning": "The proj4 literal of EPSG:4326 is assumed to be the Map's spatial reference and all data from layers within this map will be plotted using this coordinate system. If any layers do not declare an srs value then they will be assumed to be in the same srs as the Map and not transformations will be needed to plot them in the Map's coordinate space", "doc": "Map spatial reference (proj4 string)" }, "buffer-size": { "css": "buffer-size", "default-value": "0", "type":"float", "default-meaning": "No buffer will be used", "doc": "Extra tolerance around the map (in pixels) used to ensure labels crossing tile boundaries are equally rendered in each tile (e.g. cut in each tile). Not intended to be used in combination with \"avoid-edges\"." }, "maximum-extent": { "css": "", "default-value": "none", "type":"bbox", "default-meaning": "No clipping extent will be used", "doc": "An extent to be used to limit the bounds used to query all layers during rendering. Should be minx, miny, maxx, maxy in the coordinates of the Map." }, "base": { "css": "base", "default-value": "", "default-meaning": "This base path defaults to an empty string meaning that any relative paths to files referenced in styles or layers will be interpreted relative to the application process.", "type": "string", "doc": "Any relative paths used to reference files will be understood as relative to this directory path if the map is loaded from an in memory object rather than from the filesystem. If the map is loaded from the filesystem and this option is not provided it will be set to the directory of the stylesheet." }, "paths-from-xml": { "css": "", "default-value": true, "default-meaning": "Paths read from XML will be interpreted from the location of the XML", "type": "boolean", "doc": "value to control whether paths in the XML will be interpreted from the location of the XML or from the working directory of the program that calls load_map()" }, "minimum-version": { "css": "", "default-value": "none", "default-meaning": "Mapnik version will not be detected and no error will be thrown about compatibility", "type": "string", "doc": "The minumum Mapnik version (e.g. 0.7.2) needed to use certain functionality in the stylesheet" }, "font-directory": { "css": "font-directory", "type": "uri", "default-value": "none", "default-meaning": "No map-specific fonts will be registered", "doc": "Path to a directory which holds fonts which should be registered when the Map is loaded (in addition to any fonts that may be automatically registered)." } }, "polygon": { "fill": { "css": "polygon-fill", "type": "color", "default-value": "rgba(128,128,128,1)", "default-meaning": "gray and fully opaque (alpha = 1), same as rgb(128,128,128)", "doc": "Fill color to assign to a polygon" }, "fill-opacity": { "css": "polygon-opacity", "type": "float", "doc": "The opacity of the polygon", "default-value": 1, "default-meaning": "opaque" }, "gamma": { "css": "polygon-gamma", "type": "float", "default-value": 1, "default-meaning": "fully antialiased", "range": "0-1", "doc": "Level of antialiasing of polygon edges" }, "gamma-method": { "css": "polygon-gamma-method", "type": [ "power", "linear", "none", "threshold", "multiply" ], "default-value": "power", "default-meaning": "pow(x,gamma) is used to calculate pixel gamma, which produces slightly smoother line and polygon antialiasing than the 'linear' method, while other methods are usually only used to disable AA", "doc": "An Antigrain Geometry specific rendering hint to control the quality of antialiasing. Under the hood in Mapnik this method is used in combination with the 'gamma' value (which defaults to 1). The methods are in the AGG source at https://github.com/mapnik/mapnik/blob/master/deps/agg/include/agg_gamma_functions.h" }, "clip": { "css": "polygon-clip", "type": "boolean", "default-value": true, "default-meaning": "geometry will be clipped to map bounds before rendering", "doc": "geometries are clipped to map bounds by default for best rendering performance. In some cases users may wish to disable this to avoid rendering artifacts." }, "smooth": { "css": "polygon-smooth", "type": "float", "default-value": 0, "default-meaning": "no smoothing", "range": "0-1", "doc": "Smooths out geometry angles. 0 is no smoothing, 1 is fully smoothed. Values greater than 1 will produce wild, looping geometries." }, "geometry-transform": { "css": "polygon-geometry-transform", "type": "functions", "default-value": "none", "default-meaning": "geometry will not be transformed", "doc": "Allows transformation functions to be applied to the geometry.", "functions": [ ["matrix", 6], ["translate", 2], ["scale", 2], ["rotate", 3], ["skewX", 1], ["skewY", 1] ] }, "comp-op": { "css": "polygon-comp-op", "default-value": "src-over", "default-meaning": "add the current symbolizer on top of other symbolizer", "doc": "Composite operation. This defines how this symbolizer should behave relative to symbolizers atop or below it.", "type": ["clear", "src", "dst", "src-over", "dst-over", "src-in", "dst-in", "src-out", "dst-out", "src-atop", "dst-atop", "xor", "plus", "minus", "multiply", "screen", "overlay", "darken", "lighten", "color-dodge", "color-burn", "hard-light", "soft-light", "difference", "exclusion", "contrast", "invert", "invert-rgb", "grain-merge", "grain-extract", "hue", "saturation", "color", "value" ] } }, "line": { "stroke": { "css": "line-color", "default-value": "rgba(0,0,0,1)", "type": "color", "default-meaning": "black and fully opaque (alpha = 1), same as rgb(0,0,0)", "doc": "The color of a drawn line" }, "stroke-width": { "css": "line-width", "default-value": 1, "type": "float", "doc": "The width of a line in pixels" }, "stroke-opacity": { "css": "line-opacity", "default-value": 1, "type": "float", "default-meaning": "opaque", "doc": "The opacity of a line" }, "stroke-linejoin": { "css": "line-join", "default-value": "miter", "type": [ "miter", "round", "bevel" ], "doc": "The behavior of lines when joining" }, "stroke-linecap": { "css": "line-cap", "default-value": "butt", "type": [ "butt", "round", "square" ], "doc": "The display of line endings" }, "stroke-gamma": { "css": "line-gamma", "type": "float", "default-value": 1, "default-meaning": "fully antialiased", "range": "0-1", "doc": "Level of antialiasing of stroke line" }, "stroke-gamma-method": { "css": "line-gamma-method", "type": [ "power", "linear", "none", "threshold", "multiply" ], "default-value": "power", "default-meaning": "pow(x,gamma) is used to calculate pixel gamma, which produces slightly smoother line and polygon antialiasing than the 'linear' method, while other methods are usually only used to disable AA", "doc": "An Antigrain Geometry specific rendering hint to control the quality of antialiasing. Under the hood in Mapnik this method is used in combination with the 'gamma' value (which defaults to 1). The methods are in the AGG source at https://github.com/mapnik/mapnik/blob/master/deps/agg/include/agg_gamma_functions.h" }, "stroke-dasharray": { "css": "line-dasharray", "type": "numbers", "doc": "A pair of length values [a,b], where (a) is the dash length and (b) is the gap length respectively. More than two values are supported for more complex patterns.", "default-value": "none", "default-meaning": "solid line" }, "stroke-dashoffset": { "css": "line-dash-offset", "type": "numbers", "doc": "valid parameter but not currently used in renderers (only exists for experimental svg support in Mapnik which is not yet enabled)", "default-value": "none", "default-meaning": "solid line" }, "stroke-miterlimit": { "css": "line-miterlimit", "type": "float", "doc": "The limit on the ratio of the miter length to the stroke-width. Used to automatically convert miter joins to bevel joins for sharp angles to avoid the miter extending beyond the thickness of the stroking path. Normally will not need to be set, but a larger value can sometimes help avoid jaggy artifacts.", "default-value": 4.0, "default-meaning": "Will auto-convert miters to bevel line joins when theta is less than 29 degrees as per the SVG spec: 'miterLength / stroke-width = 1 / sin ( theta / 2 )'" }, "clip": { "css": "line-clip", "type": "boolean", "default-value": true, "default-meaning": "geometry will be clipped to map bounds before rendering", "doc": "geometries are clipped to map bounds by default for best rendering performance. In some cases users may wish to disable this to avoid rendering artifacts." }, "smooth": { "css": "line-smooth", "type": "float", "default-value": 0, "default-meaning": "no smoothing", "range": "0-1", "doc": "Smooths out geometry angles. 0 is no smoothing, 1 is fully smoothed. Values greater than 1 will produce wild, looping geometries." }, "offset": { "css": "line-offset", "type": "float", "default-value": 0, "default-meaning": "no offset", "doc": "Offsets a line a number of pixels parallel to its actual path. Postive values move the line left, negative values move it right (relative to the directionality of the line)." }, "rasterizer": { "css": "line-rasterizer", "type": [ "full", "fast" ], "default-value": "full", "doc": "Exposes an alternate AGG rendering method that sacrifices some accuracy for speed." }, "geometry-transform": { "css": "line-geometry-transform", "type": "functions", "default-value": "none", "default-meaning": "geometry will not be transformed", "doc": "Allows transformation functions to be applied to the geometry.", "functions": [ ["matrix", 6], ["translate", 2], ["scale", 2], ["rotate", 3], ["skewX", 1], ["skewY", 1] ] }, "comp-op": { "css": "line-comp-op", "default-value": "src-over", "default-meaning": "add the current symbolizer on top of other symbolizer", "doc": "Composite operation. This defines how this symbolizer should behave relative to symbolizers atop or below it.", "type": ["clear", "src", "dst", "src-over", "dst-over", "src-in", "dst-in", "src-out", "dst-out", "src-atop", "dst-atop", "xor", "plus", "minus", "multiply", "screen", "overlay", "darken", "lighten", "color-dodge", "color-burn", "hard-light", "soft-light", "difference", "exclusion", "contrast", "invert", "invert-rgb", "grain-merge", "grain-extract", "hue", "saturation", "color", "value" ] } }, "markers": { "file": { "css": "marker-file", "doc": "An SVG file that this marker shows at each placement. If no file is given, the marker will show an ellipse.", "default-value": "", "default-meaning": "An ellipse or circle, if width equals height", "type": "uri" }, "opacity": { "css": "marker-opacity", "doc": "The overall opacity of the marker, if set, overrides both the opacity of both the fill and stroke", "default-value": 1, "default-meaning": "The stroke-opacity and fill-opacity will be used", "type": "float" }, "fill-opacity": { "css": "marker-fill-opacity", "doc": "The fill opacity of the marker", "default-value": 1, "default-meaning": "opaque", "type": "float" }, "stroke": { "css": "marker-line-color", "doc": "The color of the stroke around a marker shape.", "default-value": "black", "type": "color" }, "stroke-width": { "css": "marker-line-width", "doc": "The width of the stroke around a marker shape, in pixels. This is positioned on the boundary, so high values can cover the area itself.", "type": "float" }, "stroke-opacity": { "css": "marker-line-opacity", "default-value": 1, "default-meaning": "opaque", "doc": "The opacity of a line", "type": "float" }, "placement": { "css": "marker-placement", "type": [ "point", "line", "interior" ], "default-value": "point", "default-meaning": "Place markers at the center point (centroid) of the geometry", "doc": "Attempt to place markers on a point, in the center of a polygon, or if markers-placement:line, then multiple times along a line. 'interior' placement can be used to ensure that points placed on polygons are forced to be inside the polygon interior" }, "multi-policy": { "css": "marker-multi-policy", "type": [ "each", "whole", "largest" ], "default-value": "each", "default-meaning": "If a feature contains multiple geometries and the placement type is either point or interior then a marker will be rendered for each", "doc": "A special setting to allow the user to control rendering behavior for 'multi-geometries' (when a feature contains multiple geometries). This setting does not apply to markers placed along lines. The 'each' policy is default and means all geometries will get a marker. The 'whole' policy means that the aggregate centroid between all geometries will be used. The 'largest' policy means that only the largest (by bounding box areas) feature will get a rendered marker (this is how text labeling behaves by default)." }, "marker-type": { "css": "marker-type", "type": [ "arrow", "ellipse", "rectangle" ], "default-value": "ellipse", "doc": "The default marker-type. If a SVG file is not given as the marker-file parameter, the renderer provides either an arrow or an ellipse (a circle if height is equal to width)" }, "width": { "css": "marker-width", "default-value": 10, "doc": "The width of the marker, if using one of the default types.", "type": "float", "expression": true }, "height": { "css": "marker-height", "default-value": 10, "doc": "The height of the marker, if using one of the default types.", "type": "float", "expression": true }, "fill": { "css": "marker-fill", "default-value": "blue", "doc": "The color of the area of the marker.", "type": "color" }, "allow-overlap": { "css": "marker-allow-overlap", "type": "boolean", "default-value": false, "doc": "Control whether overlapping markers are shown or hidden.", "default-meaning": "Do not allow makers to overlap with each other - overlapping markers will not be shown." }, "ignore-placement": { "css": "marker-ignore-placement", "type": "boolean", "default-value": false, "default-meaning": "do not store the bbox of this geometry in the collision detector cache", "doc": "value to control whether the placement of the feature will prevent the placement of other features" }, "spacing": { "css": "marker-spacing", "doc": "Space between repeated labels", "default-value": 100, "type": "float" }, "max-error": { "css": "marker-max-error", "type": "float", "default-value": 0.2, "doc": "The maximum difference between actual marker placement and the marker-spacing parameter. Setting a high value can allow the renderer to try to resolve placement conflicts with other symbolizers." }, "transform": { "css": "marker-transform", "type": "functions", "functions": [ ["matrix", 6], ["translate", 2], ["scale", 2], ["rotate", 3], ["skewX", 1], ["skewY", 1] ], "default-value": "", "default-meaning": "No transformation", "doc": "SVG transformation definition" }, "clip": { "css": "marker-clip", "type": "boolean", "default-value": true, "default-meaning": "geometry will be clipped to map bounds before rendering", "doc": "geometries are clipped to map bounds by default for best rendering performance. In some cases users may wish to disable this to avoid rendering artifacts." }, "smooth": { "css": "marker-smooth", "type": "float", "default-value": 0, "default-meaning": "no smoothing", "range": "0-1", "doc": "Smooths out geometry angles. 0 is no smoothing, 1 is fully smoothed. Values greater than 1 will produce wild, looping geometries." }, "geometry-transform": { "css": "marker-geometry-transform", "type": "functions", "default-value": "none", "default-meaning": "geometry will not be transformed", "doc": "Allows transformation functions to be applied to the geometry.", "functions": [ ["matrix", 6], ["translate", 2], ["scale", 2], ["rotate", 3], ["skewX", 1], ["skewY", 1] ] }, "comp-op": { "css": "marker-comp-op", "default-value": "src-over", "default-meaning": "add the current symbolizer on top of other symbolizer", "doc": "Composite operation. This defines how this symbolizer should behave relative to symbolizers atop or below it.", "type": ["clear", "src", "dst", "src-over", "dst-over", "src-in", "dst-in", "src-out", "dst-out", "src-atop", "dst-atop", "xor", "plus", "minus", "multiply", "screen", "overlay", "darken", "lighten", "color-dodge", "color-burn", "hard-light", "soft-light", "difference", "exclusion", "contrast", "invert", "invert-rgb", "grain-merge", "grain-extract", "hue", "saturation", "color", "value" ] } }, "shield": { "name": { "css": "shield-name", "type": "string", "expression": true, "serialization": "content", "doc": "Value to use for a shield\"s text label. Data columns are specified using brackets like [column_name]" }, "file": { "css": "shield-file", "required": true, "type": "uri", "default-value": "none", "doc": "Image file to render behind the shield text" }, "face-name": { "css": "shield-face-name", "type": "string", "validate": "font", "doc": "Font name and style to use for the shield text", "default-value": "", "required": true }, "unlock-image": { "css": "shield-unlock-image", "type": "boolean", "doc": "This parameter should be set to true if you are trying to position text beside rather than on top of the shield image", "default-value": false, "default-meaning": "text alignment relative to the shield image uses the center of the image as the anchor for text positioning." }, "size": { "css": "shield-size", "type": "float", "doc": "The size of the shield text in pixels" }, "fill": { "css": "shield-fill", "type": "color", "doc": "The color of the shield text" }, "placement": { "css": "shield-placement", "type": [ "point", "line", "vertex", "interior" ], "default-value": "point", "doc": "How this shield should be placed. Point placement attempts to place it on top of points, line places along lines multiple times per feature, vertex places on the vertexes of polygons, and interior attempts to place inside of polygons." }, "avoid-edges": { "css": "shield-avoid-edges", "doc": "Tell positioning algorithm to avoid labeling near intersection edges.", "type": "boolean", "default-value": false }, "allow-overlap": { "css": "shield-allow-overlap", "type": "boolean", "default-value": false, "doc": "Control whether overlapping shields are shown or hidden.", "default-meaning": "Do not allow shields to overlap with other map elements already placed." }, "minimum-distance": { "css": "shield-min-distance", "type": "float", "default-value": 0, "doc": "Minimum distance to the next shield symbol, not necessarily the same shield." }, "spacing": { "css": "shield-spacing", "type": "float", "default-value": 0, "doc": "The spacing between repeated occurrences of the same shield on a line" }, "minimum-padding": { "css": "shield-min-padding", "default-value": 0, "doc": "Determines the minimum amount of padding that a shield gets relative to other shields", "type": "float" }, "wrap-width": { "css": "shield-wrap-width", "type": "unsigned", "default-value": 0, "doc": "Length of a chunk of text in characters before wrapping text" }, "wrap-before": { "css": "shield-wrap-before", "type": "boolean", "default-value": false, "doc": "Wrap text before wrap-width is reached. If false, wrapped lines will be a bit longer than wrap-width." }, "wrap-character": { "css": "shield-wrap-character", "type": "string", "default-value": " ", "doc": "Use this character instead of a space to wrap long names." }, "halo-fill": { "css": "shield-halo-fill", "type": "color", "default-value": "#FFFFFF", "default-meaning": "white", "doc": "Specifies the color of the halo around the text." }, "halo-radius": { "css": "shield-halo-radius", "doc": "Specify the radius of the halo in pixels", "default-value": 0, "default-meaning": "no halo", "type": "float" }, "character-spacing": { "css": "shield-character-spacing", "type": "unsigned", "default-value": 0, "doc": "Horizontal spacing between characters (in pixels). Currently works for point placement only, not line placement." }, "line-spacing": { "css": "shield-line-spacing", "doc": "Vertical spacing between lines of multiline labels (in pixels)", "type": "unsigned" }, "dx": { "css": "shield-text-dx", "type": "float", "doc": "Displace text within shield by fixed amount, in pixels, +/- along the X axis. A positive value will shift the text right", "default-value": 0 }, "dy": { "css": "shield-text-dy", "type": "float", "doc": "Displace text within shield by fixed amount, in pixels, +/- along the Y axis. A positive value will shift the text down", "default-value": 0 }, "shield-dx": { "css": "shield-dx", "type": "float", "doc": "Displace shield by fixed amount, in pixels, +/- along the X axis. A positive value will shift the text right", "default-value": 0 }, "shield-dy": { "css": "shield-dy", "type": "float", "doc": "Displace shield by fixed amount, in pixels, +/- along the Y axis. A positive value will shift the text down", "default-value": 0 }, "opacity": { "css": "shield-opacity", "type": "float", "doc": "(Default 1.0) - opacity of the image used for the shield", "default-value": 1 }, "text-opacity": { "css": "shield-text-opacity", "type": "float", "doc": "(Default 1.0) - opacity of the text placed on top of the shield", "default-value": 1 }, "horizontal-alignment": { "css": "shield-horizontal-alignment", "type": [ "left", "middle", "right", "auto" ], "doc": "The shield's horizontal alignment from its centerpoint", "default-value": "auto" }, "vertical-alignment": { "css": "shield-vertical-alignment", "type": [ "top", "middle", "bottom", "auto" ], "doc": "The shield's vertical alignment from its centerpoint", "default-value": "middle" }, "text-transform": { "css": "shield-text-transform", "type": [ "none", "uppercase", "lowercase", "capitalize" ], "doc": "Transform the case of the characters", "default-value": "none" }, "justify-alignment": { "css": "shield-justify-alignment", "type": [ "left", "center", "right", "auto" ], "doc": "Define how text in a shield's label is justified", "default-value": "auto" }, "clip": { "css": "shield-clip", "type": "boolean", "default-value": true, "default-meaning": "geometry will be clipped to map bounds before rendering", "doc": "geometries are clipped to map bounds by default for best rendering performance. In some cases users may wish to disable this to avoid rendering artifacts." }, "comp-op": { "css": "shield-comp-op", "default-value": "src-over", "default-meaning": "add the current symbolizer on top of other symbolizer", "doc": "Composite operation. This defines how this symbolizer should behave relative to symbolizers atop or below it.", "type": ["clear", "src", "dst", "src-over", "dst-over", "src-in", "dst-in", "src-out", "dst-out", "src-atop", "dst-atop", "xor", "plus", "minus", "multiply", "screen", "overlay", "darken", "lighten", "color-dodge", "color-burn", "hard-light", "soft-light", "difference", "exclusion", "contrast", "invert", "invert-rgb", "grain-merge", "grain-extract", "hue", "saturation", "color", "value" ] } }, "line-pattern": { "file": { "css": "line-pattern-file", "type": "uri", "default-value": "none", "required": true, "doc": "An image file to be repeated and warped along a line" }, "clip": { "css": "line-pattern-clip", "type": "boolean", "default-value": true, "default-meaning": "geometry will be clipped to map bounds before rendering", "doc": "geometries are clipped to map bounds by default for best rendering performance. In some cases users may wish to disable this to avoid rendering artifacts." }, "smooth": { "css": "line-pattern-smooth", "type": "float", "default-value": 0, "default-meaning": "no smoothing", "range": "0-1", "doc": "Smooths out geometry angles. 0 is no smoothing, 1 is fully smoothed. Values greater than 1 will produce wild, looping geometries." }, "geometry-transform": { "css": "line-pattern-geometry-transform", "type": "functions", "default-value": "none", "default-meaning": "geometry will not be transformed", "doc": "Allows transformation functions to be applied to the geometry.", "functions": [ ["matrix", 6], ["translate", 2], ["scale", 2], ["rotate", 3], ["skewX", 1], ["skewY", 1] ] }, "comp-op": { "css": "line-pattern-comp-op", "default-value": "src-over", "default-meaning": "add the current symbolizer on top of other symbolizer", "doc": "Composite operation. This defines how this symbolizer should behave relative to symbolizers atop or below it.", "type": ["clear", "src", "dst", "src-over", "dst-over", "src-in", "dst-in", "src-out", "dst-out", "src-atop", "dst-atop", "xor", "plus", "minus", "multiply", "screen", "overlay", "darken", "lighten", "color-dodge", "color-burn", "hard-light", "soft-light", "difference", "exclusion", "contrast", "invert", "invert-rgb", "grain-merge", "grain-extract", "hue", "saturation", "color", "value" ] } }, "polygon-pattern": { "file": { "css": "polygon-pattern-file", "type": "uri", "default-value": "none", "required": true, "doc": "Image to use as a repeated pattern fill within a polygon" }, "alignment": { "css": "polygon-pattern-alignment", "type": [ "local", "global" ], "default-value": "local", "doc": "Specify whether to align pattern fills to the layer or to the map." }, "gamma": { "css": "polygon-pattern-gamma", "type": "float", "default-value": 1, "default-meaning": "fully antialiased", "range": "0-1", "doc": "Level of antialiasing of polygon pattern edges" }, "opacity": { "css": "polygon-pattern-opacity", "type": "float", "doc": "(Default 1.0) - Apply an opacity level to the image used for the pattern", "default-value": 1, "default-meaning": "The image is rendered without modifications" }, "clip": { "css": "polygon-pattern-clip", "type": "boolean", "default-value": true, "default-meaning": "geometry will be clipped to map bounds before rendering", "doc": "geometries are clipped to map bounds by default for best rendering performance. In some cases users may wish to disable this to avoid rendering artifacts." }, "smooth": { "css": "polygon-pattern-smooth", "type": "float", "default-value": 0, "default-meaning": "no smoothing", "range": "0-1", "doc": "Smooths out geometry angles. 0 is no smoothing, 1 is fully smoothed. Values greater than 1 will produce wild, looping geometries." }, "geometry-transform": { "css": "polygon-pattern-geometry-transform", "type": "functions", "default-value": "none", "default-meaning": "geometry will not be transformed", "doc": "Allows transformation functions to be applied to the geometry.", "functions": [ ["matrix", 6], ["translate", 2], ["scale", 2], ["rotate", 3], ["skewX", 1], ["skewY", 1] ] }, "comp-op": { "css": "polygon-pattern-comp-op", "default-value": "src-over", "default-meaning": "add the current symbolizer on top of other symbolizer", "doc": "Composite operation. This defines how this symbolizer should behave relative to symbolizers atop or below it.", "type": ["clear", "src", "dst", "src-over", "dst-over", "src-in", "dst-in", "src-out", "dst-out", "src-atop", "dst-atop", "xor", "plus", "minus", "multiply", "screen", "overlay", "darken", "lighten", "color-dodge", "color-burn", "hard-light", "soft-light", "difference", "exclusion", "contrast", "invert", "invert-rgb", "grain-merge", "grain-extract", "hue", "saturation", "color", "value" ] } }, "raster": { "opacity": { "css": "raster-opacity", "default-value": 1, "default-meaning": "opaque", "type": "float", "doc": "The opacity of the raster symbolizer on top of other symbolizers." }, "filter-factor": { "css": "raster-filter-factor", "default-value": -1, "default-meaning": "Allow the datasource to choose appropriate downscaling.", "type": "float", "doc": "This is used by the Raster or Gdal datasources to pre-downscale images using overviews. Higher numbers can sometimes cause much better scaled image output, at the cost of speed." }, "scaling": { "css": "raster-scaling", "type": [ "near", "fast", "bilinear", "bilinear8", "bicubic", "spline16", "spline36", "hanning", "hamming", "hermite", "kaiser", "quadric", "catrom", "gaussian", "bessel", "mitchell", "sinc", "lanczos", "blackman" ], "default-value": "near", "doc": "The scaling algorithm used to making different resolution versions of this raster layer. Bilinear is a good compromise between speed and accuracy, while lanczos gives the highest quality." }, "mesh-size": { "css": "raster-mesh-size", "default-value": 16, "default-meaning": "Reprojection mesh will be 1/16 of the resolution of the source image", "type": "unsigned", "doc": "A reduced resolution mesh is used for raster reprojection, and the total image size is divided by the mesh-size to determine the quality of that mesh. Values for mesh-size larger than the default will result in faster reprojection but might lead to distortion." }, "comp-op": { "css": "raster-comp-op", "default-value": "src-over", "default-meaning": "add the current symbolizer on top of other symbolizer", "doc": "Composite operation. This defines how this symbolizer should behave relative to symbolizers atop or below it.", "type": ["clear", "src", "dst", "src-over", "dst-over", "src-in", "dst-in", "src-out", "dst-out", "src-atop", "dst-atop", "xor", "plus", "minus", "multiply", "screen", "overlay", "darken", "lighten", "color-dodge", "color-burn", "hard-light", "soft-light", "difference", "exclusion", "contrast", "invert", "invert-rgb", "grain-merge", "grain-extract", "hue", "saturation", "color", "value" ] } }, "point": { "file": { "css": "point-file", "type": "uri", "required": false, "default-value": "none", "doc": "Image file to represent a point" }, "allow-overlap": { "css": "point-allow-overlap", "type": "boolean", "default-value": false, "doc": "Control whether overlapping points are shown or hidden.", "default-meaning": "Do not allow points to overlap with each other - overlapping markers will not be shown." }, "ignore-placement": { "css": "point-ignore-placement", "type": "boolean", "default-value": false, "default-meaning": "do not store the bbox of this geometry in the collision detector cache", "doc": "value to control whether the placement of the feature will prevent the placement of other features" }, "opacity": { "css": "point-opacity", "type": "float", "default-value": 1.0, "default-meaning": "Fully opaque", "doc": "A value from 0 to 1 to control the opacity of the point" }, "placement": { "css": "point-placement", "type": [ "centroid", "interior" ], "doc": "How this point should be placed. Centroid calculates the geometric center of a polygon, which can be outside of it, while interior always places inside of a polygon.", "default-value": "centroid" }, "transform": { "css": "point-transform", "type": "functions", "functions": [ ["matrix", 6], ["translate", 2], ["scale", 2], ["rotate", 3], ["skewX", 1], ["skewY", 1] ], "default-value": "", "default-meaning": "No transformation", "doc": "SVG transformation definition" }, "comp-op": { "css": "point-comp-op", "default-value": "src-over", "default-meaning": "add the current symbolizer on top of other symbolizer", "doc": "Composite operation. This defines how this symbolizer should behave relative to symbolizers atop or below it.", "type": ["clear", "src", "dst", "src-over", "dst-over", "src-in", "dst-in", "src-out", "dst-out", "src-atop", "dst-atop", "xor", "plus", "minus", "multiply", "screen", "overlay", "darken", "lighten", "color-dodge", "color-burn", "hard-light", "soft-light", "difference", "exclusion", "contrast", "invert", "invert-rgb", "grain-merge", "grain-extract", "hue", "saturation", "color", "value" ] } }, "text": { "name": { "css": "text-name", "type": "string", "expression": true, "required": true, "default-value": "", "serialization": "content", "doc": "Value to use for a text label. Data columns are specified using brackets like [column_name]" }, "face-name": { "css": "text-face-name", "type": "string", "validate": "font", "doc": "Font name and style to render a label in", "required": true }, "size": { "css": "text-size", "type": "float", "default-value": 10, "doc": "Text size in pixels" }, "text-ratio": { "css": "text-ratio", "doc": "Define the amount of text (of the total) present on successive lines when wrapping occurs", "default-value": 0, "type": "unsigned" }, "wrap-width": { "css": "text-wrap-width", "doc": "Length of a chunk of text in characters before wrapping text", "default-value": 0, "type": "unsigned" }, "wrap-before": { "css": "text-wrap-before", "type": "boolean", "default-value": false, "doc": "Wrap text before wrap-width is reached. If false, wrapped lines will be a bit longer than wrap-width." }, "wrap-character": { "css": "text-wrap-character", "type": "string", "default-value": " ", "doc": "Use this character instead of a space to wrap long text." }, "spacing": { "css": "text-spacing", "type": "unsigned", "doc": "Distance between repeated text labels on a line (aka. label-spacing)" }, "character-spacing": { "css": "text-character-spacing", "type": "float", "default-value": 0, "doc": "Horizontal spacing adjustment between characters in pixels" }, "line-spacing": { "css": "text-line-spacing", "default-value": 0, "type": "unsigned", "doc": "Vertical spacing adjustment between lines in pixels" }, "label-position-tolerance": { "css": "text-label-position-tolerance", "default-value": 0, "type": "unsigned", "doc": "Allows the label to be displaced from its ideal position by a number of pixels (only works with placement:line)" }, "max-char-angle-delta": { "css": "text-max-char-angle-delta", "type": "float", "default-value": "22.5", "doc": "The maximum angle change, in degrees, allowed between adjacent characters in a label. This value internally is converted to radians to the default is 22.5*math.pi/180.0. The higher the value the fewer labels will be placed around around sharp corners." }, "fill": { "css": "text-fill", "doc": "Specifies the color for the text", "default-value": "#000000", "type": "color" }, "opacity": { "css": "text-opacity", "doc": "A number from 0 to 1 specifying the opacity for the text", "default-value": 1.0, "default-meaning": "Fully opaque", "type": "float" }, "halo-fill": { "css": "text-halo-fill", "type": "color", "default-value": "#FFFFFF", "default-meaning": "white", "doc": "Specifies the color of the halo around the text." }, "halo-radius": { "css": "text-halo-radius", "doc": "Specify the radius of the halo in pixels", "default-value": 0, "default-meaning": "no halo", "type": "float" }, "dx": { "css": "text-dx", "type": "float", "doc": "Displace text by fixed amount, in pixels, +/- along the X axis. A positive value will shift the text right", "default-value": 0 }, "dy": { "css": "text-dy", "type": "float", "doc": "Displace text by fixed amount, in pixels, +/- along the Y axis. A positive value will shift the text down", "default-value": 0 }, "vertical-alignment": { "css": "text-vertical-alignment", "type": [ "top", "middle", "bottom", "auto" ], "doc": "Position of label relative to point position.", "default-value": "auto", "default-meaning": "Default affected by value of dy; \"bottom\" for dy>0, \"top\" for dy<0." }, "avoid-edges": { "css": "text-avoid-edges", "doc": "Tell positioning algorithm to avoid labeling near intersection edges.", "default-value": false, "type": "boolean" }, "minimum-distance": { "css": "text-min-distance", "doc": "Minimum permitted distance to the next text symbolizer.", "type": "float" }, "minimum-padding": { "css": "text-min-padding", "doc": "Determines the minimum amount of padding that a text symbolizer gets relative to other text", "type": "float" }, "minimum-path-length": { "css": "text-min-path-length", "type": "float", "default-value": 0, "default-meaning": "place labels on all paths", "doc": "Place labels only on paths longer than this value." }, "allow-overlap": { "css": "text-allow-overlap", "type": "boolean", "default-value": false, "doc": "Control whether overlapping text is shown or hidden.", "default-meaning": "Do not allow text to overlap with other text - overlapping markers will not be shown." }, "orientation": { "css": "text-orientation", "type": "float", "expression": true, "doc": "Rotate the text." }, "placement": { "css": "text-placement", "type": [ "point", "line", "vertex", "interior" ], "default-value": "point", "doc": "Control the style of placement of a point versus the geometry it is attached to." }, "placement-type": { "css": "text-placement-type", "doc": "Re-position and/or re-size text to avoid overlaps. \"simple\" for basic algorithm (using text-placements string,) \"dummy\" to turn this feature off.", "type": [ "dummy", "simple" ], "default-value": "dummy" }, "placements": { "css": "text-placements", "type": "string", "default-value": "", "doc": "If \"placement-type\" is set to \"simple\", use this \"POSITIONS,[SIZES]\" string. An example is `text-placements: \"E,NE,SE,W,NW,SW\";` " }, "text-transform": { "css": "text-transform", "type": [ "none", "uppercase", "lowercase", "capitalize" ], "doc": "Transform the case of the characters", "default-value": "none" }, "horizontal-alignment": { "css": "text-horizontal-alignment", "type": [ "left", "middle", "right", "auto" ], "doc": "The text's horizontal alignment from its centerpoint", "default-value": "auto" }, "justify-alignment": { "css": "text-align", "type": [ "left", "right", "center", "auto" ], "doc": "Define how text is justified", "default-value": "auto", "default-meaning": "Auto alignment means that text will be centered by default except when using the `placement-type` parameter - in that case either right or left justification will be used automatically depending on where the text could be fit given the `text-placements` directives" }, "clip": { "css": "text-clip", "type": "boolean", "default-value": true, "default-meaning": "geometry will be clipped to map bounds before rendering", "doc": "geometries are clipped to map bounds by default for best rendering performance. In some cases users may wish to disable this to avoid rendering artifacts." }, "comp-op": { "css": "text-comp-op", "default-value": "src-over", "default-meaning": "add the current symbolizer on top of other symbolizer", "doc": "Composite operation. This defines how this symbolizer should behave relative to symbolizers atop or below it.", "type": ["clear", "src", "dst", "src-over", "dst-over", "src-in", "dst-in", "src-out", "dst-out", "src-atop", "dst-atop", "xor", "plus", "minus", "multiply", "screen", "overlay", "darken", "lighten", "color-dodge", "color-burn", "hard-light", "soft-light", "difference", "exclusion", "contrast", "invert", "invert-rgb", "grain-merge", "grain-extract", "hue", "saturation", "color", "value" ] } }, "building": { "fill": { "css": "building-fill", "default-value": "#FFFFFF", "doc": "The color of the buildings walls.", "type": "color" }, "fill-opacity": { "css": "building-fill-opacity", "type": "float", "doc": "The opacity of the building as a whole, including all walls.", "default-value": 1 }, "height": { "css": "building-height", "doc": "The height of the building in pixels.", "type": "float", "expression": true, "default-value": "0" } }, "torque": { "-torque-clear-color": { "css": "-torque-clear-color", "type": "color", "default-value": "rgba(255, 255, 255, 0)", "default-meaning": "full clear", "doc": "color used to clear canvas on each frame" }, "-torque-frame-count": { "css": "-torque-frame-count", "default-value": "128", "type":"float", "default-meaning": "the data is broken into 128 time frames", "doc": "Number of animation steps/frames used in the animation. If the data contains a fewere number of total frames, the lesser value will be used." }, "-torque-resolution": { "css": "-torque-resolution", "default-value": "2", "type":"float", "default-meaning": "", "doc": "Spatial resolution in pixels. A resolution of 1 means no spatial aggregation of the data. Any other resolution of N results in spatial aggregation into cells of NxN pixels. The value N must be power of 2" }, "-torque-animation-duration": { "css": "-torque-animation-duration", "default-value": "30", "type":"float", "default-meaning": "the animation lasts 30 seconds", "doc": "Animation duration in seconds" }, "-torque-aggregation-function": { "css": "-torque-aggregation-function", "default-value": "count(cartodb_id)", "type": "string", "default-meaning": "the value for each cell is the count of points in that cell", "doc": "A function used to calculate a value from the aggregate data for each cell. See -torque-resolution" }, "-torque-time-attribute": { "css": "-torque-time-attribute", "default-value": "time", "type": "string", "default-meaning": "the data column in your table that is of a time based type", "doc": "The table column that contains the time information used create the animation" }, "-torque-data-aggregation": { "css": "-torque-data-aggregation", "default-value": "linear", "type": [ "linear", "cumulative" ], "default-meaning": "previous values are discarded", "doc": "A linear animation will discard previous values while a cumulative animation will accumulate them until it restarts" } } }, "colors": { "aliceblue": [240, 248, 255], "antiquewhite": [250, 235, 215], "aqua": [0, 255, 255], "aquamarine": [127, 255, 212], "azure": [240, 255, 255], "beige": [245, 245, 220], "bisque": [255, 228, 196], "black": [0, 0, 0], "blanchedalmond": [255,235,205], "blue": [0, 0, 255], "blueviolet": [138, 43, 226], "brown": [165, 42, 42], "burlywood": [222, 184, 135], "cadetblue": [95, 158, 160], "chartreuse": [127, 255, 0], "chocolate": [210, 105, 30], "coral": [255, 127, 80], "cornflowerblue": [100, 149, 237], "cornsilk": [255, 248, 220], "crimson": [220, 20, 60], "cyan": [0, 255, 255], "darkblue": [0, 0, 139], "darkcyan": [0, 139, 139], "darkgoldenrod": [184, 134, 11], "darkgray": [169, 169, 169], "darkgreen": [0, 100, 0], "darkgrey": [169, 169, 169], "darkkhaki": [189, 183, 107], "darkmagenta": [139, 0, 139], "darkolivegreen": [85, 107, 47], "darkorange": [255, 140, 0], "darkorchid": [153, 50, 204], "darkred": [139, 0, 0], "darksalmon": [233, 150, 122], "darkseagreen": [143, 188, 143], "darkslateblue": [72, 61, 139], "darkslategrey": [47, 79, 79], "darkturquoise": [0, 206, 209], "darkviolet": [148, 0, 211], "deeppink": [255, 20, 147], "deepskyblue": [0, 191, 255], "dimgray": [105, 105, 105], "dimgrey": [105, 105, 105], "dodgerblue": [30, 144, 255], "firebrick": [178, 34, 34], "floralwhite": [255, 250, 240], "forestgreen": [34, 139, 34], "fuchsia": [255, 0, 255], "gainsboro": [220, 220, 220], "ghostwhite": [248, 248, 255], "gold": [255, 215, 0], "goldenrod": [218, 165, 32], "gray": [128, 128, 128], "grey": [128, 128, 128], "green": [0, 128, 0], "greenyellow": [173, 255, 47], "honeydew": [240, 255, 240], "hotpink": [255, 105, 180], "indianred": [205, 92, 92], "indigo": [75, 0, 130], "ivory": [255, 255, 240], "khaki": [240, 230, 140], "lavender": [230, 230, 250], "lavenderblush": [255, 240, 245], "lawngreen": [124, 252, 0], "lemonchiffon": [255, 250, 205], "lightblue": [173, 216, 230], "lightcoral": [240, 128, 128], "lightcyan": [224, 255, 255], "lightgoldenrodyellow": [250, 250, 210], "lightgray": [211, 211, 211], "lightgreen": [144, 238, 144], "lightgrey": [211, 211, 211], "lightpink": [255, 182, 193], "lightsalmon": [255, 160, 122], "lightseagreen": [32, 178, 170], "lightskyblue": [135, 206, 250], "lightslategray": [119, 136, 153], "lightslategrey": [119, 136, 153], "lightsteelblue": [176, 196, 222], "lightyellow": [255, 255, 224], "lime": [0, 255, 0], "limegreen": [50, 205, 50], "linen": [250, 240, 230], "magenta": [255, 0, 255], "maroon": [128, 0, 0], "mediumaquamarine": [102, 205, 170], "mediumblue": [0, 0, 205], "mediumorchid": [186, 85, 211], "mediumpurple": [147, 112, 219], "mediumseagreen": [60, 179, 113], "mediumslateblue": [123, 104, 238], "mediumspringgreen": [0, 250, 154], "mediumturquoise": [72, 209, 204], "mediumvioletred": [199, 21, 133], "midnightblue": [25, 25, 112], "mintcream": [245, 255, 250], "mistyrose": [255, 228, 225], "moccasin": [255, 228, 181], "navajowhite": [255, 222, 173], "navy": [0, 0, 128], "oldlace": [253, 245, 230], "olive": [128, 128, 0], "olivedrab": [107, 142, 35], "orange": [255, 165, 0], "orangered": [255, 69, 0], "orchid": [218, 112, 214], "palegoldenrod": [238, 232, 170], "palegreen": [152, 251, 152], "paleturquoise": [175, 238, 238], "palevioletred": [219, 112, 147], "papayawhip": [255, 239, 213], "peachpuff": [255, 218, 185], "peru": [205, 133, 63], "pink": [255, 192, 203], "plum": [221, 160, 221], "powderblue": [176, 224, 230], "purple": [128, 0, 128], "red": [255, 0, 0], "rosybrown": [188, 143, 143], "royalblue": [65, 105, 225], "saddlebrown": [139, 69, 19], "salmon": [250, 128, 114], "sandybrown": [244, 164, 96], "seagreen": [46, 139, 87], "seashell": [255, 245, 238], "sienna": [160, 82, 45], "silver": [192, 192, 192], "skyblue": [135, 206, 235], "slateblue": [106, 90, 205], "slategray": [112, 128, 144], "slategrey": [112, 128, 144], "snow": [255, 250, 250], "springgreen": [0, 255, 127], "steelblue": [70, 130, 180], "tan": [210, 180, 140], "teal": [0, 128, 128], "thistle": [216, 191, 216], "tomato": [255, 99, 71], "turquoise": [64, 224, 208], "violet": [238, 130, 238], "wheat": [245, 222, 179], "white": [255, 255, 255], "whitesmoke": [245, 245, 245], "yellow": [255, 255, 0], "yellowgreen": [154, 205, 50], "transparent": [0, 0, 0, 0] }, "filter": { "value": [ "true", "false", "null", "point", "linestring", "polygon", "collection" ] } } module.exports = { version: { latest: _mapnik_reference_latest, '2.1.1': _mapnik_reference_latest } }; },{}],41:[function(require,module,exports){ /** * TODO: document this. What does this do? */ if(typeof(module) !== "undefined") { module.exports.find = function (obj, fun) { for (var i = 0, r; i < obj.length; i++) { if (r = fun.call(obj, obj[i])) { return r; } } return null; }; } },{}],42:[function(require,module,exports){ (function (global){ (function(tree) { var _ = global._ || require('underscore'); tree.Call = function Call(name, args, index) { this.name = name; this.args = args; this.index = index; }; tree.Call.prototype = { is: 'call', // When evuating a function call, // we either find the function in `tree.functions` [1], // in which case we call it, passing the evaluated arguments, // or we simply print it out as it appeared originally [2]. // The *functions.js* file contains the built-in functions. // The reason why we evaluate the arguments, is in the case where // we try to pass a variable to a function, like: `saturate(@color)`. // The function should receive the value, not the variable. 'ev': function(env) { var args = this.args.map(function(a) { return a.ev(env); }); for (var i = 0; i < args.length; i++) { if (args[i].is === 'undefined') { return { is: 'undefined', value: 'undefined' }; } } if (this.name in tree.functions) { if (tree.functions[this.name].length <= args.length) { var val = tree.functions[this.name].apply(tree.functions, args); if (val === null) { env.error({ message: 'incorrect arguments given to ' + this.name + '()', index: this.index, type: 'runtime', filename: this.filename }); return { is: 'undefined', value: 'undefined' }; } return val; } else { env.error({ message: 'incorrect number of arguments for ' + this.name + '(). ' + tree.functions[this.name].length + ' expected.', index: this.index, type: 'runtime', filename: this.filename }); return { is: 'undefined', value: 'undefined' }; } } else { var fn = tree.Reference.mapnikFunctions[this.name]; if (fn === undefined) { var functions = _.pairs(tree.Reference.mapnikFunctions); // cheap closest, needs improvement. var name = this.name; var mean = functions.map(function(f) { return [f[0], tree.Reference.editDistance(name, f[0]), f[1]]; }).sort(function(a, b) { return a[1] - b[1]; }); env.error({ message: 'unknown function ' + this.name + '(), did you mean ' + mean[0][0] + '(' + mean[0][2] + ')', index: this.index, type: 'runtime', filename: this.filename }); return { is: 'undefined', value: 'undefined' }; } if (fn !== args.length && !(Array.isArray(fn) && _.include(fn, args.length)) && // support variable-arg functions like `colorize-alpha` fn !== -1) { env.error({ message: 'function ' + this.name + '() takes ' + fn + ' arguments and was given ' + args.length, index: this.index, type: 'runtime', filename: this.filename }); return { is: 'undefined', value: 'undefined' }; } else { // Save the evaluated versions of arguments this.args = args; return this; } } }, toString: function(env, format) { if (this.args.length) { return this.name + '(' + this.args.join(',') + ')'; } else { return this.name; } } }; })(require('../tree')); }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"../tree":41,"underscore":71}],43:[function(require,module,exports){ (function(tree) { // RGB Colors - #ff0014, #eee // can be initialized with a 3 or 6 char string or a 3 or 4 element // numerical array tree.Color = function Color(rgb, a) { // The end goal here, is to parse the arguments // into an integer triplet, such as `128, 255, 0` // // This facilitates operations and conversions. if (Array.isArray(rgb)) { this.rgb = rgb.slice(0, 3); } else if (rgb.length == 6) { this.rgb = rgb.match(/.{2}/g).map(function(c) { return parseInt(c, 16); }); } else { this.rgb = rgb.split('').map(function(c) { return parseInt(c + c, 16); }); } if (typeof(a) === 'number') { this.alpha = a; } else if (rgb.length === 4) { this.alpha = rgb[3]; } else { this.alpha = 1; } }; tree.Color.prototype = { is: 'color', 'ev': function() { return this; }, // If we have some transparency, the only way to represent it // is via `rgba`. Otherwise, we use the hex representation, // which has better compatibility with older browsers. // Values are capped between `0` and `255`, rounded and zero-padded. toString: function() { if (this.alpha < 1.0) { return 'rgba(' + this.rgb.map(function(c) { return Math.round(c); }).concat(this.alpha).join(', ') + ')'; } else { return '#' + this.rgb.map(function(i) { i = Math.round(i); i = (i > 255 ? 255 : (i < 0 ? 0 : i)).toString(16); return i.length === 1 ? '0' + i : i; }).join(''); } }, // Operations have to be done per-channel, if not, // channels will spill onto each other. Once we have // our result, in the form of an integer triplet, // we create a new Color node to hold the result. operate: function(env, op, other) { var result = []; if (! (other instanceof tree.Color)) { other = other.toColor(); } for (var c = 0; c < 3; c++) { result[c] = tree.operate(op, this.rgb[c], other.rgb[c]); } return new tree.Color(result); }, toHSL: function() { var r = this.rgb[0] / 255, g = this.rgb[1] / 255, b = this.rgb[2] / 255, a = this.alpha; var max = Math.max(r, g, b), min = Math.min(r, g, b); var h, s, l = (max + min) / 2, d = max - min; if (max === min) { h = s = 0; } else { s = l > 0.5 ? d / (2 - max - min) : d / (max + min); switch (max) { case r: h = (g - b) / d + (g < b ? 6 : 0); break; case g: h = (b - r) / d + 2; break; case b: h = (r - g) / d + 4; break; } h /= 6; } return { h: h * 360, s: s, l: l, a: a }; } }; })(require('../tree')); },{"../tree":41}],44:[function(require,module,exports){ (function(tree) { tree.Comment = function Comment(value, silent) { this.value = value; this.silent = !!silent; }; tree.Comment.prototype = { toString: function(env) { return ''; }, 'ev': function() { return this; } }; })(require('../tree')); },{"../tree":41}],45:[function(require,module,exports){ (function (global){ (function(tree) { var assert = require('assert'), _ = global._ || require('underscore'); // A definition is the combination of a selector and rules, like // #foo { // polygon-opacity:1.0; // } // // The selector can have filters tree.Definition = function Definition(selector, rules) { this.elements = selector.elements; assert.ok(selector.filters instanceof tree.Filterset); this.rules = rules; this.ruleIndex = {}; for (var i = 0; i < this.rules.length; i++) { if ('zoom' in this.rules[i]) this.rules[i] = this.rules[i].clone(); this.rules[i].zoom = selector.zoom; this.ruleIndex[this.rules[i].updateID()] = true; } this.filters = selector.filters; this.zoom = selector.zoom; this.frame_offset = selector.frame_offset; this.attachment = selector.attachment || '__default__'; this.specificity = selector.specificity(); }; tree.Definition.prototype.toString = function() { var str = this.filters.toString(); for (var i = 0; i < this.rules.length; i++) { str += '\n ' + this.rules[i]; } return str; }; tree.Definition.prototype.clone = function(filters) { if (filters) assert.ok(filters instanceof tree.Filterset); var clone = Object.create(tree.Definition.prototype); clone.rules = this.rules.slice(); clone.ruleIndex = _.clone(this.ruleIndex); clone.filters = filters ? filters : this.filters.clone(); clone.attachment = this.attachment; return clone; }; tree.Definition.prototype.addRules = function(rules) { var added = 0; // Add only unique rules. for (var i = 0; i < rules.length; i++) { if (!this.ruleIndex[rules[i].id]) { this.rules.push(rules[i]); this.ruleIndex[rules[i].id] = true; added++; } } return added; }; // Determine whether this selector matches a given id // and array of classes, by determining whether // all elements it contains match. tree.Definition.prototype.appliesTo = function(id, classes) { for (var i = 0, l = this.elements.length; i < l; i++) { var elem = this.elements[i]; if (!(elem.wildcard || (elem.type === 'class' && classes[elem.clean]) || (elem.type === 'id' && id === elem.clean))) return false; } return true; }; function symbolizerName(symbolizer) { function capitalize(str) { return str[1].toUpperCase(); } return symbolizer.charAt(0).toUpperCase() + symbolizer.slice(1).replace(/\-./, capitalize) + 'Symbolizer'; } // Get a simple list of the symbolizers, in order function symbolizerList(sym_order) { return sym_order.sort(function(a, b) { return a[1] - b[1]; }) .map(function(v) { return v[0]; }); } tree.Definition.prototype.symbolizersToXML = function(env, symbolizers, zoom) { var xml = zoom.toXML(env).join('') + this.filters.toXML(env); // Sort symbolizers by the index of their first property definition var sym_order = [], indexes = []; for (var key in symbolizers) { indexes = []; for (var prop in symbolizers[key]) { indexes.push(symbolizers[key][prop].index); } var min_idx = Math.min.apply(Math, indexes); sym_order.push([key, min_idx]); } sym_order = symbolizerList(sym_order); var sym_count = 0; for (var i = 0; i < sym_order.length; i++) { var attributes = symbolizers[sym_order[i]]; var symbolizer = sym_order[i].split('/').pop(); // Skip the magical * symbolizer which is used for universal properties // which are bubbled up to Style elements intead of Symbolizer elements. if (symbolizer === '*') continue; sym_count++; var fail = tree.Reference.requiredProperties(symbolizer, attributes); if (fail) { var rule = attributes[Object.keys(attributes).shift()]; env.error({ message: fail, index: rule.index, filename: rule.filename }); } var name = symbolizerName(symbolizer); var selfclosing = true, tagcontent; xml += ' <' + name + ' '; for (var j in attributes) { if (symbolizer === 'map') env.error({ message: 'Map properties are not permitted in other rules', index: attributes[j].index, filename: attributes[j].filename }); var x = tree.Reference.selector(attributes[j].name); if (x && x.serialization && x.serialization === 'content') { selfclosing = false; tagcontent = attributes[j].ev(env).toXML(env, true); } else if (x && x.serialization && x.serialization === 'tag') { selfclosing = false; tagcontent = attributes[j].ev(env).toXML(env, true); } else { xml += attributes[j].ev(env).toXML(env) + ' '; } } if (selfclosing) { xml += '/>\n'; } else if (typeof tagcontent !== "undefined") { if (tagcontent.indexOf('<') != -1) { xml += '>' + tagcontent + '\n'; } else { xml += '>\n'; } } } if (!sym_count || !xml) return ''; return ' \n' + xml + ' \n'; }; // Take a zoom range of zooms and 'i', the index of a rule in this.rules, // and finds all applicable symbolizers tree.Definition.prototype.collectSymbolizers = function(zooms, i) { var symbolizers = {}, child; for (var j = i; j < this.rules.length; j++) { child = this.rules[j]; var key = child.instance + '/' + child.symbolizer; if (zooms.current & child.zoom && (!(key in symbolizers) || (!(child.name in symbolizers[key])))) { zooms.current &= child.zoom; if (!(key in symbolizers)) { symbolizers[key] = {}; } symbolizers[key][child.name] = child; } } if (Object.keys(symbolizers).length) { zooms.rule &= (zooms.available &= ~zooms.current); return symbolizers; } }; // The tree.Zoom.toString function ignores the holes in zoom ranges and outputs // scaledenominators that cover the whole range from the first to last bit set. // This algorithm can produces zoom ranges that may have holes. However, // when using the filter-mode="first", more specific zoom filters will always // end up before broader ranges. The filter-mode will pick those first before // resorting to the zoom range with the hole and stop processing further rules. tree.Definition.prototype.toXML = function(env, existing) { var filter = this.filters.toString(); if (!(filter in existing)) existing[filter] = tree.Zoom.all; var available = tree.Zoom.all, xml = '', zoom, symbolizers, zooms = { available: tree.Zoom.all }; for (var i = 0; i < this.rules.length && available; i++) { zooms.rule = this.rules[i].zoom; if (!(existing[filter] & zooms.rule)) continue; while (zooms.current = zooms.rule & available) { if (symbolizers = this.collectSymbolizers(zooms, i)) { if (!(existing[filter] & zooms.current)) continue; xml += this.symbolizersToXML(env, symbolizers, (new tree.Zoom()).setZoom(existing[filter] & zooms.current)); existing[filter] &= ~zooms.current; } } } return xml; }; tree.Definition.prototype.toJS = function(env) { var shaderAttrs = {}; // merge conditions from filters with zoom condition of the // definition var zoom = "(" + this.zoom + " & (1 << ctx.zoom))"; var frame_offset = this.frame_offset; var _if = this.filters.toJS(env); var filters = [zoom]; if(_if) filters.push(_if); if(frame_offset) filters.push('ctx["frame-offset"] === ' + frame_offset); _if = filters.join(" && "); _.each(this.rules, function(rule) { if(rule instanceof tree.Rule) { shaderAttrs[rule.name] = shaderAttrs[rule.name] || []; var r = { index: rule.index, symbolizer: rule.symbolizer }; if (_if) { r.js = "if(" + _if + "){" + rule.value.toJS(env) + "}" } else { r.js = rule.value.toJS(env); } r.constant = rule.value.ev(env).is !== 'field'; r.filtered = !!_if; shaderAttrs[rule.name].push(r); } else { throw new Error("Ruleset not supported"); //if (rule instanceof tree.Ruleset) { //var sh = rule.toJS(env); //for(var v in sh) { //shaderAttrs[v] = shaderAttrs[v] || []; //for(var attr in sh[v]) { //shaderAttrs[v].push(sh[v][attr]); //} //} //} } }); return shaderAttrs; }; })(require('../tree')); }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"../tree":41,"assert":29,"underscore":71}],46:[function(require,module,exports){ (function (global){ (function(tree) { var _ = global._ || require('underscore'); // // A number with a unit // tree.Dimension = function Dimension(value, unit, index) { this.value = parseFloat(value); this.unit = unit || null; this.index = index; }; tree.Dimension.prototype = { is: 'float', physical_units: ['m', 'cm', 'in', 'mm', 'pt', 'pc'], screen_units: ['px', '%'], all_units: ['m', 'cm', 'in', 'mm', 'pt', 'pc', 'px', '%'], densities: { m: 0.0254, mm: 25.4, cm: 2.54, pt: 72, pc: 6 }, ev: function (env) { if (this.unit && !_.contains(this.all_units, this.unit)) { env.error({ message: "Invalid unit: '" + this.unit + "'", index: this.index }); return { is: 'undefined', value: 'undefined' }; } // normalize units which are not px or % if (this.unit && _.contains(this.physical_units, this.unit)) { if (!env.ppi) { env.error({ message: "ppi is not set, so metric units can't be used", index: this.index }); return { is: 'undefined', value: 'undefined' }; } // convert all units to inch // convert inch to px using ppi this.value = (this.value / this.densities[this.unit]) * env.ppi; this.unit = 'px'; } return this; }, round: function() { this.value = Math.round(this.value); return this; }, toColor: function() { return new tree.Color([this.value, this.value, this.value]); }, round: function() { this.value = Math.round(this.value); return this; }, toString: function() { return this.value.toString(); }, operate: function(env, op, other) { if (this.unit === '%' && other.unit !== '%') { env.error({ message: 'If two operands differ, the first must not be %', index: this.index }); return { is: 'undefined', value: 'undefined' }; } if (this.unit !== '%' && other.unit === '%') { if (op === '*' || op === '/' || op === '%') { env.error({ message: 'Percent values can only be added or subtracted from other values', index: this.index }); return { is: 'undefined', value: 'undefined' }; } return new tree.Dimension(tree.operate(op, this.value, this.value * other.value * 0.01), this.unit); } //here the operands are either the same (% or undefined or px), or one is undefined and the other is px return new tree.Dimension(tree.operate(op, this.value, other.value), this.unit || other.unit); } }; })(require('../tree')); }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"../tree":41,"underscore":71}],47:[function(require,module,exports){ (function(tree) { // An element is an id or class selector tree.Element = function Element(value) { this.value = value.trim(); if (this.value[0] === '#') { this.type = 'id'; this.clean = this.value.replace(/^#/, ''); } if (this.value[0] === '.') { this.type = 'class'; this.clean = this.value.replace(/^\./, ''); } if (this.value.indexOf('*') !== -1) { this.type = 'wildcard'; } }; // Determine the 'specificity matrix' of this // specific selector tree.Element.prototype.specificity = function() { return [ (this.type === 'id') ? 1 : 0, // a (this.type === 'class') ? 1 : 0 // b ]; }; tree.Element.prototype.toString = function() { return this.value; }; })(require('../tree')); },{"../tree":41}],48:[function(require,module,exports){ (function(tree) { tree.Expression = function Expression(value) { this.value = value; }; tree.Expression.prototype = { is: 'expression', ev: function(env) { if (this.value.length > 1) { return new tree.Expression(this.value.map(function(e) { return e.ev(env); })); } else { return this.value[0].ev(env); } }, toString: function(env) { return this.value.map(function(e) { return e.toString(env); }).join(' '); } }; })(require('../tree')); },{"../tree":41}],49:[function(require,module,exports){ (function(tree) { tree.Field = function Field(content) { this.value = content || ''; }; tree.Field.prototype = { is: 'field', toString: function() { return '[' + this.value + ']'; }, 'ev': function() { return this; } }; })(require('../tree')); },{"../tree":41}],50:[function(require,module,exports){ (function(tree) { tree.Filter = function Filter(key, op, val, index, filename) { this.key = key; this.op = op; this.val = val; this.index = index; this.filename = filename; this.id = this.key + this.op + this.val; }; // xmlsafe, numeric, suffix var ops = { '<': [' < ', 'numeric'], '>': [' > ', 'numeric'], '=': [' = ', 'both'], '!=': [' != ', 'both'], '<=': [' <= ', 'numeric'], '>=': [' >= ', 'numeric'], '=~': ['.match(', 'string', ')'] }; tree.Filter.prototype.ev = function(env) { this.key = this.key.ev(env); this.val = this.val.ev(env); return this; }; tree.Filter.prototype.toXML = function(env) { if (tree.Reference.data.filter) { if (this.key.is === 'keyword' && -1 === tree.Reference.data.filter.value.indexOf(this.key.toString())) { env.error({ message: this.key.toString() + ' is not a valid keyword in a filter expression', index: this.index, filename: this.filename }); } if (this.val.is === 'keyword' && -1 === tree.Reference.data.filter.value.indexOf(this.val.toString())) { env.error({ message: this.val.toString() + ' is not a valid keyword in a filter expression', index: this.index, filename: this.filename }); } } var key = this.key.toString(false); var val = this.val.toString(this.val.is == 'string'); if ( (ops[this.op][1] == 'numeric' && isNaN(val) && this.val.is !== 'field') || (ops[this.op][1] == 'string' && (val)[0] != "'") ) { env.error({ message: 'Cannot use operator "' + this.op + '" with value ' + this.val, index: this.index, filename: this.filename }); } return key + ops[this.op][0] + val + (ops[this.op][2] || ''); }; tree.Filter.prototype.toString = function() { return '[' + this.id + ']'; }; })(require('../tree')); },{"../tree":41}],51:[function(require,module,exports){ (function (global){ var tree = require('../tree'); var _ = global._ || require('underscore'); tree.Filterset = function Filterset() { this.filters = {}; }; tree.Filterset.prototype.toXML = function(env) { var filters = []; for (var id in this.filters) { filters.push('(' + this.filters[id].toXML(env).trim() + ')'); } if (filters.length) { return ' ' + filters.join(' and ') + '\n'; } else { return ''; } }; tree.Filterset.prototype.toString = function() { var arr = []; for (var id in this.filters) arr.push(this.filters[id].id); return arr.sort().join('\t'); }; tree.Filterset.prototype.ev = function(env) { for (var i in this.filters) { this.filters[i].ev(env); } return this; }; tree.Filterset.prototype.clone = function() { var clone = new tree.Filterset(); for (var id in this.filters) { clone.filters[id] = this.filters[id]; } return clone; }; // Note: other has to be a tree.Filterset. tree.Filterset.prototype.cloneWith = function(other) { var additions = []; for (var id in other.filters) { var status = this.addable(other.filters[id]); // status is true, false or null. if it's null we don't fail this // clone nor do we add the filter. if (status === false) { return false; } if (status === true) { // Adding the filter will override another value. additions.push(other.filters[id]); } } // Adding the other filters doesn't make this filterset invalid, but it // doesn't add anything to it either. if (!additions.length) { return null; } // We can successfully add all filters. Now clone the filterset and add the // new rules. var clone = new tree.Filterset(); // We can add the rules that are already present without going through the // add function as a Filterset is always in it's simplest canonical form. for (id in this.filters) { clone.filters[id] = this.filters[id]; } // Only add new filters that actually change the filter. while (id = additions.shift()) { clone.add(id); } return clone; }; tree.Filterset.prototype.toJS = function(env) { var opMap = { '=': '===' }; return _.map(this.filters, function(filter) { var op = filter.op; if(op in opMap) { op = opMap[op]; } var val = filter.val; if(filter._val !== undefined) { val = filter._val.toString(true); } var attrs = "data"; return attrs + "." + filter.key.value + " " + op + " " + (val.is === 'string' ? "'"+ val +"'" : val); }).join(' && '); }; // Returns true when the new filter can be added, false otherwise. // It can also return null, and on the other side we test for === true or // false tree.Filterset.prototype.addable = function(filter) { var key = filter.key.toString(), value = filter.val.toString(); if (value.match(/^[0-9]+(\.[0-9]*)?$/)) value = parseFloat(value); switch (filter.op) { case '=': // if there is already foo= and we're adding foo= if (this.filters[key + '='] !== undefined) { if (this.filters[key + '='].val.toString() != value) { return false; } else { return null; } } if (this.filters[key + '!=' + value] !== undefined) return false; if (this.filters[key + '>'] !== undefined && this.filters[key + '>'].val >= value) return false; if (this.filters[key + '<'] !== undefined && this.filters[key + '<'].val <= value) return false; if (this.filters[key + '>='] !== undefined && this.filters[key + '>='].val > value) return false; if (this.filters[key + '<='] !== undefined && this.filters[key + '<='].val < value) return false; return true; case '=~': return true; case '!=': if (this.filters[key + '='] !== undefined) return (this.filters[key + '='].val == value) ? false : null; if (this.filters[key + '!=' + value] !== undefined) return null; if (this.filters[key + '>'] !== undefined && this.filters[key + '>'].val >= value) return null; if (this.filters[key + '<'] !== undefined && this.filters[key + '<'].val <= value) return null; if (this.filters[key + '>='] !== undefined && this.filters[key + '>='].val > value) return null; if (this.filters[key + '<='] !== undefined && this.filters[key + '<='].val < value) return null; return true; case '>': if (key + '=' in this.filters) { if (this.filters[key + '='].val <= value) { return false; } else { return null; } } if (this.filters[key + '<'] !== undefined && this.filters[key + '<'].val <= value) return false; if (this.filters[key + '<='] !== undefined && this.filters[key + '<='].val <= value) return false; if (this.filters[key + '>'] !== undefined && this.filters[key + '>'].val >= value) return null; if (this.filters[key + '>='] !== undefined && this.filters[key + '>='].val > value) return null; return true; case '>=': if (this.filters[key + '=' ] !== undefined) return (this.filters[key + '='].val < value) ? false : null; if (this.filters[key + '<' ] !== undefined && this.filters[key + '<'].val <= value) return false; if (this.filters[key + '<='] !== undefined && this.filters[key + '<='].val < value) return false; if (this.filters[key + '>' ] !== undefined && this.filters[key + '>'].val >= value) return null; if (this.filters[key + '>='] !== undefined && this.filters[key + '>='].val >= value) return null; return true; case '<': if (this.filters[key + '=' ] !== undefined) return (this.filters[key + '='].val >= value) ? false : null; if (this.filters[key + '>' ] !== undefined && this.filters[key + '>'].val >= value) return false; if (this.filters[key + '>='] !== undefined && this.filters[key + '>='].val >= value) return false; if (this.filters[key + '<' ] !== undefined && this.filters[key + '<'].val <= value) return null; if (this.filters[key + '<='] !== undefined && this.filters[key + '<='].val < value) return null; return true; case '<=': if (this.filters[key + '=' ] !== undefined) return (this.filters[key + '='].val > value) ? false : null; if (this.filters[key + '>' ] !== undefined && this.filters[key + '>'].val >= value) return false; if (this.filters[key + '>='] !== undefined && this.filters[key + '>='].val > value) return false; if (this.filters[key + '<' ] !== undefined && this.filters[key + '<'].val <= value) return null; if (this.filters[key + '<='] !== undefined && this.filters[key + '<='].val <= value) return null; return true; } }; // Does the new filter constitute a conflict? tree.Filterset.prototype.conflict = function(filter) { var key = filter.key.toString(), value = filter.val.toString(); if (!isNaN(parseFloat(value))) value = parseFloat(value); // if (a=b) && (a=c) // if (a=b) && (a!=b) // or (a!=b) && (a=b) if ((filter.op === '=' && this.filters[key + '='] !== undefined && value != this.filters[key + '='].val.toString()) || (filter.op === '!=' && this.filters[key + '='] !== undefined && value == this.filters[key + '='].val.toString()) || (filter.op === '=' && this.filters[key + '!='] !== undefined && value == this.filters[key + '!='].val.toString())) { return filter.toString() + ' added to ' + this.toString() + ' produces an invalid filter'; } return false; }; // Only call this function for filters that have been cleared by .addable(). tree.Filterset.prototype.add = function(filter, env) { var key = filter.key.toString(), id, op = filter.op, conflict = this.conflict(filter), numval; if (conflict) return conflict; if (op === '=') { for (var i in this.filters) { if (this.filters[i].key == key) delete this.filters[i]; } this.filters[key + '='] = filter; } else if (op === '!=') { this.filters[key + '!=' + filter.val] = filter; } else if (op === '=~') { this.filters[key + '=~' + filter.val] = filter; } else if (op === '>') { // If there are other filters that are also > // but are less than this one, they don't matter, so // remove them. for (var j in this.filters) { if (this.filters[j].key == key && this.filters[j].val <= filter.val) { delete this.filters[j]; } } this.filters[key + '>'] = filter; } else if (op === '>=') { for (var k in this.filters) { numval = (+this.filters[k].val.toString()); if (this.filters[k].key == key && numval < filter.val) { delete this.filters[k]; } } if (this.filters[key + '!=' + filter.val] !== undefined) { delete this.filters[key + '!=' + filter.val]; filter.op = '>'; this.filters[key + '>'] = filter; } else { this.filters[key + '>='] = filter; } } else if (op === '<') { for (var l in this.filters) { numval = (+this.filters[l].val.toString()); if (this.filters[l].key == key && numval >= filter.val) { delete this.filters[l]; } } this.filters[key + '<'] = filter; } else if (op === '<=') { for (var m in this.filters) { numval = (+this.filters[m].val.toString()); if (this.filters[m].key == key && numval > filter.val) { delete this.filters[m]; } } if (this.filters[key + '!=' + filter.val] !== undefined) { delete this.filters[key + '!=' + filter.val]; filter.op = '<'; this.filters[key + '<'] = filter; } else { this.filters[key + '<='] = filter; } } }; }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"../tree":41,"underscore":71}],52:[function(require,module,exports){ (function(tree) { tree._getFontSet = function(env, fonts) { var fontKey = fonts.join(''); if (env._fontMap && env._fontMap[fontKey]) { return env._fontMap[fontKey]; } var new_fontset = new tree.FontSet(env, fonts); env.effects.push(new_fontset); if (!env._fontMap) env._fontMap = {}; env._fontMap[fontKey] = new_fontset; return new_fontset; }; tree.FontSet = function FontSet(env, fonts) { this.fonts = fonts; this.name = 'fontset-' + env.effects.length; }; tree.FontSet.prototype.toXML = function(env) { return '\n' + this.fonts.map(function(f) { return ' '; }).join('\n') + '\n'; }; })(require('../tree')); },{"../tree":41}],53:[function(require,module,exports){ var tree = require('../tree'); // Storage for Frame offset value // and stores them as bit-sequences so that they can be combined, // inverted, and compared quickly. tree.FrameOffset = function(op, value, index) { value = parseInt(value, 10); if (value > tree.FrameOffset.max || value <= 0) { throw { message: 'Only frame-offset levels between 1 and ' + tree.FrameOffset.max + ' supported.', index: index }; } if (op !== '=') { throw { message: 'only = operator is supported for frame-offset', index: index }; } return value; }; tree.FrameOffset.max = 32; tree.FrameOffset.none = 0; },{"../tree":41}],54:[function(require,module,exports){ (function(tree) { tree.ImageFilter = function ImageFilter(filter, args) { this.filter = filter; this.args = args || null; }; tree.ImageFilter.prototype = { is: 'imagefilter', ev: function() { return this; }, toString: function() { if (this.args) { return this.filter + '(' + this.args.join(',') + ')'; } else { return this.filter; } } }; })(require('../tree')); },{"../tree":41}],55:[function(require,module,exports){ (function (tree) { tree.Invalid = function Invalid(chunk, index, message) { this.chunk = chunk; this.index = index; this.type = 'syntax'; this.message = message || "Invalid code: " + this.chunk; }; tree.Invalid.prototype.is = 'invalid'; tree.Invalid.prototype.ev = function(env) { env.error({ chunk: this.chunk, index: this.index, type: 'syntax', message: this.message || "Invalid code: " + this.chunk }); return { is: 'undefined' }; }; })(require('../tree')); },{"../tree":41}],56:[function(require,module,exports){ (function(tree) { tree.Keyword = function Keyword(value) { this.value = value; var special = { 'transparent': 'color', 'true': 'boolean', 'false': 'boolean' }; this.is = special[value] ? special[value] : 'keyword'; }; tree.Keyword.prototype = { ev: function() { return this; }, toString: function() { return this.value; } }; })(require('../tree')); },{"../tree":41}],57:[function(require,module,exports){ (function(tree) { tree.LayerXML = function(obj, styles) { var dsoptions = []; for (var i in obj.Datasource) { dsoptions.push(''); } var prop_string = ''; for (var prop in obj.properties) { if (prop === 'minzoom') { prop_string += ' maxzoom="' + tree.Zoom.ranges[obj.properties[prop]] + '"\n'; } else if (prop === 'maxzoom') { prop_string += ' minzoom="' + tree.Zoom.ranges[obj.properties[prop]+1] + '"\n'; } else { prop_string += ' ' + prop + '="' + obj.properties[prop] + '"\n'; } } return '\n ' + styles.reverse().map(function(s) { return '' + s + ''; }).join('\n ') + (dsoptions.length ? '\n \n ' + dsoptions.join('\n ') + '\n \n' : '') + ' \n'; }; })(require('../tree')); },{"../tree":41}],58:[function(require,module,exports){ // A literal is a literal string for Mapnik - the // result of the combination of a `tree.Field` with any // other type. (function(tree) { tree.Literal = function Field(content) { this.value = content || ''; this.is = 'field'; }; tree.Literal.prototype = { toString: function() { return this.value; }, 'ev': function() { return this; } }; })(require('../tree')); },{"../tree":41}],59:[function(require,module,exports){ // An operation is an expression with an op in between two operands, // like 2 + 1. (function(tree) { tree.Operation = function Operation(op, operands, index) { this.op = op.trim(); this.operands = operands; this.index = index; }; tree.Operation.prototype.is = 'operation'; tree.Operation.prototype.ev = function(env) { var a = this.operands[0].ev(env), b = this.operands[1].ev(env), temp; if (a.is === 'undefined' || b.is === 'undefined') { return { is: 'undefined', value: 'undefined' }; } if (a instanceof tree.Dimension && b instanceof tree.Color) { if (this.op === '*' || this.op === '+') { temp = b, b = a, a = temp; } else { env.error({ name: "OperationError", message: "Can't substract or divide a color from a number", index: this.index }); } } // Only concatenate plain strings, because this is easily // pre-processed if (a instanceof tree.Quoted && b instanceof tree.Quoted && this.op !== '+') { env.error({ message: "Can't subtract, divide, or multiply strings.", index: this.index, type: 'runtime', filename: this.filename }); return { is: 'undefined', value: 'undefined' }; } // Fields, literals, dimensions, and quoted strings can be combined. if (a instanceof tree.Field || b instanceof tree.Field || a instanceof tree.Literal || b instanceof tree.Literal) { if (a.is === 'color' || b.is === 'color') { env.error({ message: "Can't subtract, divide, or multiply colors in expressions.", index: this.index, type: 'runtime', filename: this.filename }); return { is: 'undefined', value: 'undefined' }; } else { return new tree.Literal(a.ev(env).toString(true) + this.op + b.ev(env).toString(true)); } } if (a.operate === undefined) { env.error({ message: 'Cannot do math with type ' + a.is + '.', index: this.index, type: 'runtime', filename: this.filename }); return { is: 'undefined', value: 'undefined' }; } return a.operate(env, this.op, b); }; tree.operate = function(op, a, b) { switch (op) { case '+': return a + b; case '-': return a - b; case '*': return a * b; case '%': return a % b; case '/': return a / b; } }; })(require('../tree')); },{"../tree":41}],60:[function(require,module,exports){ (function(tree) { tree.Quoted = function Quoted(content) { this.value = content || ''; }; tree.Quoted.prototype = { is: 'string', toString: function(quotes) { var escapedValue = this.value .replace(/&/g, '&') var xmlvalue = escapedValue .replace(/\'/g, '\\\'') .replace(/\"/g, '"') .replace(//g, '>'); return (quotes === true) ? "'" + xmlvalue + "'" : escapedValue; }, 'ev': function() { return this; }, operate: function(env, op, other) { return new tree.Quoted(tree.operate(op, this.toString(), other.toString(this.contains_field))); } }; })(require('../tree')); },{"../tree":41}],61:[function(require,module,exports){ (function (global){ // Carto pulls in a reference from the `mapnik-reference` // module. This file builds indexes from that file for its various // options, and provides validation methods for property: value // combinations. (function(tree) { var _ = global._ || require('underscore'), ref = {}; ref.setData = function(data) { ref.data = data; ref.selector_cache = generateSelectorCache(data); ref.mapnikFunctions = generateMapnikFunctions(data); ref.mapnikFunctions.matrix = [6]; ref.mapnikFunctions.translate = [1, 2]; ref.mapnikFunctions.scale = [1, 2]; ref.mapnikFunctions.rotate = [1, 3]; ref.mapnikFunctions.skewX = [1]; ref.mapnikFunctions.skewY = [1]; ref.required_cache = generateRequiredProperties(data); }; ref.setVersion = function(version) { var mapnik_reference = require('mapnik-reference'); if (mapnik_reference.version.hasOwnProperty(version)) { ref.setData(mapnik_reference.version[version]); return true; } else { return false; } }; ref.selectorData = function(selector, i) { if (ref.selector_cache[selector]) return ref.selector_cache[selector][i]; }; ref.validSelector = function(selector) { return !!ref.selector_cache[selector]; }; ref.selectorName = function(selector) { return ref.selectorData(selector, 2); }; ref.selector = function(selector) { return ref.selectorData(selector, 0); }; ref.symbolizer = function(selector) { return ref.selectorData(selector, 1); }; function generateSelectorCache(data) { var index = {}; for (var i in data.symbolizers) { for (var j in data.symbolizers[i]) { if (data.symbolizers[i][j].hasOwnProperty('css')) { index[data.symbolizers[i][j].css] = [data.symbolizers[i][j], i, j]; } } } return index; } function generateMapnikFunctions(data) { var functions = {}; for (var i in data.symbolizers) { for (var j in data.symbolizers[i]) { if (data.symbolizers[i][j].type === 'functions') { for (var k = 0; k < data.symbolizers[i][j].functions.length; k++) { var fn = data.symbolizers[i][j].functions[k]; functions[fn[0]] = fn[1]; } } } } return functions; } function generateRequiredProperties(data) { var cache = {}; for (var symbolizer_name in data.symbolizers) { cache[symbolizer_name] = []; for (var j in data.symbolizers[symbolizer_name]) { if (data.symbolizers[symbolizer_name][j].required) { cache[symbolizer_name].push(data.symbolizers[symbolizer_name][j].css); } } } return cache; } ref.requiredProperties = function(symbolizer_name, rules) { var req = ref.required_cache[symbolizer_name]; for (var i in req) { if (!(req[i] in rules)) { return 'Property ' + req[i] + ' required for defining ' + symbolizer_name + ' styles.'; } } }; // TODO: finish implementation - this is dead code ref._validateValue = { 'font': function(env, value) { if (env.validation_data && env.validation_data.fonts) { return env.validation_data.fonts.indexOf(value) != -1; } else { return true; } } }; ref.isFont = function(selector) { return ref.selector(selector).validate == 'font'; }; // https://gist.github.com/982927 ref.editDistance = function(a, b){ if (a.length === 0) return b.length; if (b.length === 0) return a.length; var matrix = []; for (var i = 0; i <= b.length; i++) { matrix[i] = [i]; } for (var j = 0; j <= a.length; j++) { matrix[0][j] = j; } for (i = 1; i <= b.length; i++) { for (j = 1; j <= a.length; j++) { if (b.charAt(i-1) == a.charAt(j-1)) { matrix[i][j] = matrix[i-1][j-1]; } else { matrix[i][j] = Math.min(matrix[i-1][j-1] + 1, // substitution Math.min(matrix[i][j-1] + 1, // insertion matrix[i-1][j] + 1)); // deletion } } } return matrix[b.length][a.length]; }; function validateFunctions(value, selector) { if (value.value[0].is === 'string') return true; for (var i in value.value) { for (var j in value.value[i].value) { if (value.value[i].value[j].is !== 'call') return false; var f = _.find(ref .selector(selector).functions, function(x) { return x[0] == value.value[i].value[j].name; }); if (!(f && f[1] == -1)) { // This filter is unknown or given an incorrect number of arguments if (!f || f[1] !== value.value[i].value[j].args.length) return false; } } } return true; } function validateKeyword(value, selector) { if (typeof ref.selector(selector).type === 'object') { return ref.selector(selector).type .indexOf(value.value[0].value) !== -1; } else { // allow unquoted keywords as strings return ref.selector(selector).type === 'string'; } } ref.validValue = function(env, selector, value) { var i, j; // TODO: handle in reusable way if (!ref.selector(selector)) { return false; } else if (value.value[0].is == 'keyword') { return validateKeyword(value, selector); } else if (value.value[0].is == 'undefined') { // caught earlier in the chain - ignore here so that // error is not overridden return true; } else if (ref.selector(selector).type == 'numbers') { for (i in value.value) { if (value.value[i].is !== 'float') { return false; } } return true; } else if (ref.selector(selector).type == 'tags') { if (!value.value) return false; if (!value.value[0].value) { return value.value[0].is === 'tag'; } for (i = 0; i < value.value[0].value.length; i++) { if (value.value[0].value[i].is !== 'tag') return false; } return true; } else if (ref.selector(selector).type == 'functions') { // For backwards compatibility, you can specify a string for `functions`-compatible // values, though they will not be validated. return validateFunctions(value, selector); } else if (ref.selector(selector).type === 'unsigned') { if (value.value[0].is === 'float') { value.value[0].round(); return true; } else { return false; } } else if ((ref.selector(selector).expression)) { return true; } else { if (ref.selector(selector).validate) { var valid = false; for (i = 0; i < value.value.length; i++) { if (ref.selector(selector).type == value.value[i].is && ref ._validateValue [ref.selector(selector).validate] (env, value.value[i].value)) { return true; } } return valid; } else { return ref.selector(selector).type == value.value[0].is; } } }; tree.Reference = ref; })(require('../tree')); }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"../tree":41,"mapnik-reference":70,"underscore":71}],62:[function(require,module,exports){ (function(tree) { // a rule is a single property and value combination, or variable // name and value combination, like // polygon-opacity: 1.0; or @opacity: 1.0; tree.Rule = function Rule(name, value, index, filename) { var parts = name.split('/'); this.name = parts.pop(); this.instance = parts.length ? parts[0] : '__default__'; this.value = (value instanceof tree.Value) ? value : new tree.Value([value]); this.index = index; this.symbolizer = tree.Reference.symbolizer(this.name); this.filename = filename; this.variable = (name.charAt(0) === '@'); }; tree.Rule.prototype.is = 'rule'; tree.Rule.prototype.clone = function() { var clone = Object.create(tree.Rule.prototype); clone.name = this.name; clone.value = this.value; clone.index = this.index; clone.instance = this.instance; clone.symbolizer = this.symbolizer; clone.filename = this.filename; clone.variable = this.variable; return clone; }; tree.Rule.prototype.updateID = function() { return this.id = this.zoom + '#' + this.instance + '#' + this.name; }; tree.Rule.prototype.toString = function() { return '[' + tree.Zoom.toString(this.zoom) + '] ' + this.name + ': ' + this.value; }; function getMean(name) { return Object.keys(tree.Reference.selector_cache).map(function(f) { return [f, tree.Reference.editDistance(name, f)]; }).sort(function(a, b) { return a[1] - b[1]; }); } // second argument, if true, outputs the value of this // rule without the usual attribute="content" wrapping. Right // now this is just for the TextSymbolizer, but applies to other // properties in reference.json which specify serialization=content tree.Rule.prototype.toXML = function(env, content, sep, format) { if (!tree.Reference.validSelector(this.name)) { var mean = getMean(this.name); var mean_message = ''; if (mean[0][1] < 3) { mean_message = '. Did you mean ' + mean[0][0] + '?'; } return env.error({ message: "Unrecognized rule: " + this.name + mean_message, index: this.index, type: 'syntax', filename: this.filename }); } if ((this.value instanceof tree.Value) && !tree.Reference.validValue(env, this.name, this.value)) { if (!tree.Reference.selector(this.name)) { return env.error({ message: 'Unrecognized property: ' + this.name, index: this.index, type: 'syntax', filename: this.filename }); } else { var typename; if (tree.Reference.selector(this.name).validate) { typename = tree.Reference.selector(this.name).validate; } else if (typeof tree.Reference.selector(this.name).type === 'object') { typename = 'keyword (options: ' + tree.Reference.selector(this.name).type.join(', ') + ')'; } else { typename = tree.Reference.selector(this.name).type; } return env.error({ message: 'Invalid value for ' + this.name + ', the type ' + typename + ' is expected. ' + this.value + ' (of type ' + this.value.value[0].is + ') ' + ' was given.', index: this.index, type: 'syntax', filename: this.filename }); } } if (this.variable) { return ''; } else if (tree.Reference.isFont(this.name) && this.value.value.length > 1) { var f = tree._getFontSet(env, this.value.value); return 'fontset-name="' + f.name + '"'; } else if (content) { return this.value.toString(env, this.name, sep); } else { return tree.Reference.selectorName(this.name) + '="' + this.value.toString(env, this.name) + '"'; } }; // TODO: Rule ev chain should add fontsets to env.frames tree.Rule.prototype.ev = function(context) { return new tree.Rule(this.name, this.value.ev(context), this.index, this.filename); }; })(require('../tree')); },{"../tree":41}],63:[function(require,module,exports){ (function(tree) { tree.Ruleset = function Ruleset(selectors, rules) { this.selectors = selectors; this.rules = rules; // static cache of find() function this._lookups = {}; }; tree.Ruleset.prototype = { is: 'ruleset', 'ev': function(env) { var i, ruleset = new tree.Ruleset(this.selectors, this.rules.slice(0)); ruleset.root = this.root; // push the current ruleset to the frames stack env.frames.unshift(ruleset); // Evaluate everything else for (i = 0, rule; i < ruleset.rules.length; i++) { rule = ruleset.rules[i]; ruleset.rules[i] = rule.ev ? rule.ev(env) : rule; } // Pop the stack env.frames.shift(); return ruleset; }, match: function(args) { return !args || args.length === 0; }, variables: function() { if (this._variables) { return this._variables; } else { return this._variables = this.rules.reduce(function(hash, r) { if (r instanceof tree.Rule && r.variable === true) { hash[r.name] = r; } return hash; }, {}); } }, variable: function(name) { return this.variables()[name]; }, rulesets: function() { if (this._rulesets) { return this._rulesets; } else { return this._rulesets = this.rules.filter(function(r) { return (r instanceof tree.Ruleset); }); } }, find: function(selector, self) { self = self || this; var rules = [], rule, match, key = selector.toString(); if (key in this._lookups) { return this._lookups[key]; } this.rulesets().forEach(function(rule) { if (rule !== self) { for (var j = 0; j < rule.selectors.length; j++) { match = selector.match(rule.selectors[j]); if (match) { if (selector.elements.length > 1) { Array.prototype.push.apply(rules, rule.find( new tree.Selector(null, null, null, selector.elements.slice(1)), self)); } else { rules.push(rule); } break; } } } }); return this._lookups[key] = rules; }, // Zooms can use variables. This replaces tree.Zoom objects on selectors // with simple bit-arrays that we can compare easily. evZooms: function(env) { for (var i = 0; i < this.selectors.length; i++) { var zval = tree.Zoom.all; for (var z = 0; z < this.selectors[i].zoom.length; z++) { zval = zval & this.selectors[i].zoom[z].ev(env).zoom; } this.selectors[i].zoom = zval; } }, flatten: function(result, parents, env) { var selectors = [], i, j; if (this.selectors.length === 0) { env.frames = env.frames.concat(this.rules); } // evaluate zoom variables on this object. this.evZooms(env); for (i = 0; i < this.selectors.length; i++) { var child = this.selectors[i]; if (!child.filters) { // TODO: is this internal inconsistency? // This is an invalid filterset. continue; } if (parents.length) { for (j = 0; j < parents.length; j++) { var parent = parents[j]; var mergedFilters = parent.filters.cloneWith(child.filters); if (mergedFilters === null) { // Filters could be added, but they didn't change the // filters. This means that we only have to clone when // the zoom levels or the attachment is different too. if (parent.zoom === (parent.zoom & child.zoom) && parent.frame_offset === child.frame_offset && parent.attachment === child.attachment && parent.elements.join() === child.elements.join()) { selectors.push(parent); continue; } else { mergedFilters = parent.filters; } } else if (!mergedFilters) { // The merged filters are invalid, that means we don't // have to clone. continue; } var clone = Object.create(tree.Selector.prototype); clone.filters = mergedFilters; clone.zoom = parent.zoom & child.zoom; clone.frame_offset = child.frame_offset; clone.elements = parent.elements.concat(child.elements); if (parent.attachment && child.attachment) { clone.attachment = parent.attachment + '/' + child.attachment; } else clone.attachment = child.attachment || parent.attachment; clone.conditions = parent.conditions + child.conditions; clone.index = child.index; selectors.push(clone); } } else { selectors.push(child); } } var rules = []; for (i = 0; i < this.rules.length; i++) { var rule = this.rules[i]; // Recursively flatten any nested rulesets if (rule instanceof tree.Ruleset) { rule.flatten(result, selectors, env); } else if (rule instanceof tree.Rule) { rules.push(rule); } else if (rule instanceof tree.Invalid) { env.error(rule); } } var index = rules.length ? rules[0].index : false; for (i = 0; i < selectors.length; i++) { // For specificity sort, use the position of the first rule to allow // defining attachments that are under current element as a descendant // selector. if (index !== false) { selectors[i].index = index; } result.push(new tree.Definition(selectors[i], rules.slice())); } return result; } }; })(require('../tree')); },{"../tree":41}],64:[function(require,module,exports){ (function(tree) { tree.Selector = function Selector(filters, zoom, frame_offset, elements, attachment, conditions, index) { this.elements = elements || []; this.attachment = attachment; this.filters = filters || {}; this.frame_offset = frame_offset; this.zoom = typeof zoom !== 'undefined' ? zoom : tree.Zoom.all; this.conditions = conditions; this.index = index; }; // Determine the specificity of this selector // based on the specificity of its elements - calling // Element.specificity() in order to do so // // [ID, Class, Filters, Position in document] tree.Selector.prototype.specificity = function() { return this.elements.reduce(function(memo, e) { var spec = e.specificity(); memo[0] += spec[0]; memo[1] += spec[1]; return memo; }, [0, 0, this.conditions, this.index]); }; })(require('../tree')); },{"../tree":41}],65:[function(require,module,exports){ (function (global){ (function(tree) { var _ = global._ || require('underscore'); // Given a style's name, attachment, definitions, and an environment object, // return a stringified style for Mapnik tree.StyleXML = function(name, attachment, definitions, env) { var existing = {}; var image_filters = [], image_filters_inflate = [], direct_image_filters = [], comp_op = [], opacity = []; for (var i = 0; i < definitions.length; i++) { for (var j = 0; j < definitions[i].rules.length; j++) { if (definitions[i].rules[j].name === 'image-filters') { image_filters.push(definitions[i].rules[j]); } if (definitions[i].rules[j].name === 'image-filters-inflate') { image_filters_inflate.push(definitions[i].rules[j]); } if (definitions[i].rules[j].name === 'direct-image-filters') { direct_image_filters.push(definitions[i].rules[j]); } if (definitions[i].rules[j].name === 'comp-op') { comp_op.push(definitions[i].rules[j]); } if (definitions[i].rules[j].name === 'opacity') { opacity.push(definitions[i].rules[j]); } } } var rules = definitions.map(function(definition) { return definition.toXML(env, existing); }); var attrs_xml = ''; if (image_filters.length) { attrs_xml += ' image-filters="' + _.chain(image_filters) // prevent identical filters from being duplicated in the style .uniq(function(i) { return i.id; }).map(function(f) { return f.ev(env).toXML(env, true, ',', 'image-filter'); }).value().join(',') + '"'; } if (image_filters_inflate.length) { attrs_xml += ' image-filters-inflate="' + image_filters_inflate[0].value.ev(env).toString() + '"'; } if (direct_image_filters.length) { attrs_xml += ' direct-image-filters="' + _.chain(direct_image_filters) // prevent identical filters from being duplicated in the style .uniq(function(i) { return i.id; }).map(function(f) { return f.ev(env).toXML(env, true, ',', 'direct-image-filter'); }).value().join(',') + '"'; } if (comp_op.length && comp_op[0].value.ev(env).value != 'src-over') { attrs_xml += ' comp-op="' + comp_op[0].value.ev(env).toString() + '"'; } if (opacity.length && opacity[0].value.ev(env).value != 1) { attrs_xml += ' opacity="' + opacity[0].value.ev(env).toString() + '"'; } var rule_string = rules.join(''); if (!attrs_xml && !rule_string) return ''; return ''; }; })(require('../tree')); }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"../tree":41,"underscore":71}],66:[function(require,module,exports){ (function(tree) { tree.URL = function URL(val, paths) { this.value = val; this.paths = paths; }; tree.URL.prototype = { is: 'uri', toString: function() { return this.value.toString(); }, ev: function(ctx) { return new tree.URL(this.value.ev(ctx), this.paths); } }; })(require('../tree')); },{"../tree":41}],67:[function(require,module,exports){ (function(tree) { tree.Value = function Value(value) { this.value = value; }; tree.Value.prototype = { is: 'value', ev: function(env) { if (this.value.length === 1) { return this.value[0].ev(env); } else { return new tree.Value(this.value.map(function(v) { return v.ev(env); })); } }, toString: function(env, selector, sep, format) { return this.value.map(function(e) { return e.toString(env, format); }).join(sep || ', '); }, clone: function() { var obj = Object.create(tree.Value.prototype); if (Array.isArray(obj)) obj.value = this.value.slice(); else obj.value = this.value; obj.is = this.is; return obj; }, toJS: function(env) { //var v = this.value[0].value[0]; var val = this.ev(env); var v = val.toString(); if(val.is === "color" || val.is === 'uri' || val.is === 'string' || val.is === 'keyword') { v = "'" + v + "'"; } else if (val.is === 'field') { // replace [variable] by ctx['variable'] v = v.replace(/\[(.*)\]/g, "data['$1']"); }else if (val.is === 'call') { v = JSON.stringify({ name: val.name, args: val.args }) } return "_value = " + v + ";"; } }; })(require('../tree')); },{"../tree":41}],68:[function(require,module,exports){ (function(tree) { tree.Variable = function Variable(name, index, filename) { this.name = name; this.index = index; this.filename = filename; }; tree.Variable.prototype = { is: 'variable', toString: function() { return this.name; }, ev: function(env) { var variable, v, name = this.name; if (this._css) return this._css; var thisframe = env.frames.filter(function(f) { return f.name == this.name; }.bind(this)); if (thisframe.length) { return thisframe[0].value.ev(env); } else { env.error({ message: 'variable ' + this.name + ' is undefined', index: this.index, type: 'runtime', filename: this.filename }); return { is: 'undefined', value: 'undefined' }; } } }; })(require('../tree')); },{"../tree":41}],69:[function(require,module,exports){ var tree = require('../tree'); // Storage for zoom ranges. Only supports continuous ranges, // and stores them as bit-sequences so that they can be combined, // inverted, and compared quickly. tree.Zoom = function(op, value, index) { this.op = op; this.value = value; this.index = index; }; tree.Zoom.prototype.setZoom = function(zoom) { this.zoom = zoom; return this; }; tree.Zoom.prototype.ev = function(env) { var start = 0, end = Infinity, value = parseInt(this.value.ev(env).toString(), 10), zoom = 0; if (value > tree.Zoom.maxZoom || value < 0) { env.error({ message: 'Only zoom levels between 0 and ' + tree.Zoom.maxZoom + ' supported.', index: this.index }); } switch (this.op) { case '=': this.zoom = 1 << value; return this; case '>': start = value + 1; break; case '>=': start = value; break; case '<': end = value - 1; break; case '<=': end = value; break; } for (var i = 0; i <= tree.Zoom.maxZoom; i++) { if (i >= start && i <= end) { zoom |= (1 << i); } } this.zoom = zoom; return this; }; tree.Zoom.prototype.toString = function() { return this.zoom; }; // Covers all zoomlevels from 0 to 22 tree.Zoom.all = 0x7FFFFF; tree.Zoom.maxZoom = 22; tree.Zoom.ranges = { 0: 1000000000, 1: 500000000, 2: 200000000, 3: 100000000, 4: 50000000, 5: 25000000, 6: 12500000, 7: 6500000, 8: 3000000, 9: 1500000, 10: 750000, 11: 400000, 12: 200000, 13: 100000, 14: 50000, 15: 25000, 16: 12500, 17: 5000, 18: 2500, 19: 1500, 20: 750, 21: 500, 22: 250, 23: 100 }; // Only works for single range zooms. `[XXX....XXXXX.........]` is invalid. tree.Zoom.prototype.toXML = function() { var conditions = []; if (this.zoom != tree.Zoom.all) { var start = null, end = null; for (var i = 0; i <= tree.Zoom.maxZoom; i++) { if (this.zoom & (1 << i)) { if (start === null) start = i; end = i; } } if (start > 0) conditions.push(' ' + tree.Zoom.ranges[start] + '\n'); if (end < 22) conditions.push(' ' + tree.Zoom.ranges[end + 1] + '\n'); } return conditions; }; tree.Zoom.prototype.toString = function() { var str = ''; for (var i = 0; i <= tree.Zoom.maxZoom; i++) { str += (this.zoom & (1 << i)) ? 'X' : '.'; } return str; }; },{"../tree":41}],70:[function(require,module,exports){ (function (__dirname){ var fs = require('fs'), path = require('path'), existsSync = require('fs').existsSync || require('path').existsSync; // Load all stated versions into the module exports module.exports.version = {}; var refs = [ '2.0.0', '2.0.1', '2.0.2', '2.1.0', '2.1.1', '2.2.0', '2.3.0', '3.0.0' ]; refs.map(function(version) { module.exports.version[version] = require(path.join(__dirname, version, 'reference.json')); var ds_path = path.join(__dirname, version, 'datasources.json'); if (existsSync(ds_path)) { module.exports.version[version].datasources = require(ds_path).datasources; } }); }).call(this,"/node_modules/carto/node_modules/mapnik-reference") },{"fs":28,"path":31}],71:[function(require,module,exports){ // Underscore.js 1.6.0 // http://underscorejs.org // (c) 2009-2014 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors // Underscore may be freely distributed under the MIT license. (function() { // Baseline setup // -------------- // Establish the root object, `window` in the browser, or `exports` on the server. var root = this; // Save the previous value of the `_` variable. var previousUnderscore = root._; // Establish the object that gets returned to break out of a loop iteration. var breaker = {}; // Save bytes in the minified (but not gzipped) version: var ArrayProto = Array.prototype, ObjProto = Object.prototype, FuncProto = Function.prototype; // Create quick reference variables for speed access to core prototypes. var push = ArrayProto.push, slice = ArrayProto.slice, concat = ArrayProto.concat, toString = ObjProto.toString, hasOwnProperty = ObjProto.hasOwnProperty; // All **ECMAScript 5** native function implementations that we hope to use // are declared here. var nativeForEach = ArrayProto.forEach, nativeMap = ArrayProto.map, nativeReduce = ArrayProto.reduce, nativeReduceRight = ArrayProto.reduceRight, nativeFilter = ArrayProto.filter, nativeEvery = ArrayProto.every, nativeSome = ArrayProto.some, nativeIndexOf = ArrayProto.indexOf, nativeLastIndexOf = ArrayProto.lastIndexOf, nativeIsArray = Array.isArray, nativeKeys = Object.keys, nativeBind = FuncProto.bind; // Create a safe reference to the Underscore object for use below. var _ = function(obj) { if (obj instanceof _) return obj; if (!(this instanceof _)) return new _(obj); this._wrapped = obj; }; // Export the Underscore object for **Node.js**, with // backwards-compatibility for the old `require()` API. If we're in // the browser, add `_` as a global object via a string identifier, // for Closure Compiler "advanced" mode. if (typeof exports !== 'undefined') { if (typeof module !== 'undefined' && module.exports) { exports = module.exports = _; } exports._ = _; } else { root._ = _; } // Current version. _.VERSION = '1.6.0'; // Collection Functions // -------------------- // The cornerstone, an `each` implementation, aka `forEach`. // Handles objects with the built-in `forEach`, arrays, and raw objects. // Delegates to **ECMAScript 5**'s native `forEach` if available. var each = _.each = _.forEach = function(obj, iterator, context) { if (obj == null) return obj; if (nativeForEach && obj.forEach === nativeForEach) { obj.forEach(iterator, context); } else if (obj.length === +obj.length) { for (var i = 0, length = obj.length; i < length; i++) { if (iterator.call(context, obj[i], i, obj) === breaker) return; } } else { var keys = _.keys(obj); for (var i = 0, length = keys.length; i < length; i++) { if (iterator.call(context, obj[keys[i]], keys[i], obj) === breaker) return; } } return obj; }; // Return the results of applying the iterator to each element. // Delegates to **ECMAScript 5**'s native `map` if available. _.map = _.collect = function(obj, iterator, context) { var results = []; if (obj == null) return results; if (nativeMap && obj.map === nativeMap) return obj.map(iterator, context); each(obj, function(value, index, list) { results.push(iterator.call(context, value, index, list)); }); return results; }; var reduceError = 'Reduce of empty array with no initial value'; // **Reduce** builds up a single result from a list of values, aka `inject`, // or `foldl`. Delegates to **ECMAScript 5**'s native `reduce` if available. _.reduce = _.foldl = _.inject = function(obj, iterator, memo, context) { var initial = arguments.length > 2; if (obj == null) obj = []; if (nativeReduce && obj.reduce === nativeReduce) { if (context) iterator = _.bind(iterator, context); return initial ? obj.reduce(iterator, memo) : obj.reduce(iterator); } each(obj, function(value, index, list) { if (!initial) { memo = value; initial = true; } else { memo = iterator.call(context, memo, value, index, list); } }); if (!initial) throw new TypeError(reduceError); return memo; }; // The right-associative version of reduce, also known as `foldr`. // Delegates to **ECMAScript 5**'s native `reduceRight` if available. _.reduceRight = _.foldr = function(obj, iterator, memo, context) { var initial = arguments.length > 2; if (obj == null) obj = []; if (nativeReduceRight && obj.reduceRight === nativeReduceRight) { if (context) iterator = _.bind(iterator, context); return initial ? obj.reduceRight(iterator, memo) : obj.reduceRight(iterator); } var length = obj.length; if (length !== +length) { var keys = _.keys(obj); length = keys.length; } each(obj, function(value, index, list) { index = keys ? keys[--length] : --length; if (!initial) { memo = obj[index]; initial = true; } else { memo = iterator.call(context, memo, obj[index], index, list); } }); if (!initial) throw new TypeError(reduceError); return memo; }; // Return the first value which passes a truth test. Aliased as `detect`. _.find = _.detect = function(obj, predicate, context) { var result; any(obj, function(value, index, list) { if (predicate.call(context, value, index, list)) { result = value; return true; } }); return result; }; // Return all the elements that pass a truth test. // Delegates to **ECMAScript 5**'s native `filter` if available. // Aliased as `select`. _.filter = _.select = function(obj, predicate, context) { var results = []; if (obj == null) return results; if (nativeFilter && obj.filter === nativeFilter) return obj.filter(predicate, context); each(obj, function(value, index, list) { if (predicate.call(context, value, index, list)) results.push(value); }); return results; }; // Return all the elements for which a truth test fails. _.reject = function(obj, predicate, context) { return _.filter(obj, function(value, index, list) { return !predicate.call(context, value, index, list); }, context); }; // Determine whether all of the elements match a truth test. // Delegates to **ECMAScript 5**'s native `every` if available. // Aliased as `all`. _.every = _.all = function(obj, predicate, context) { predicate || (predicate = _.identity); var result = true; if (obj == null) return result; if (nativeEvery && obj.every === nativeEvery) return obj.every(predicate, context); each(obj, function(value, index, list) { if (!(result = result && predicate.call(context, value, index, list))) return breaker; }); return !!result; }; // Determine if at least one element in the object matches a truth test. // Delegates to **ECMAScript 5**'s native `some` if available. // Aliased as `any`. var any = _.some = _.any = function(obj, predicate, context) { predicate || (predicate = _.identity); var result = false; if (obj == null) return result; if (nativeSome && obj.some === nativeSome) return obj.some(predicate, context); each(obj, function(value, index, list) { if (result || (result = predicate.call(context, value, index, list))) return breaker; }); return !!result; }; // Determine if the array or object contains a given value (using `===`). // Aliased as `include`. _.contains = _.include = function(obj, target) { if (obj == null) return false; if (nativeIndexOf && obj.indexOf === nativeIndexOf) return obj.indexOf(target) != -1; return any(obj, function(value) { return value === target; }); }; // Invoke a method (with arguments) on every item in a collection. _.invoke = function(obj, method) { var args = slice.call(arguments, 2); var isFunc = _.isFunction(method); return _.map(obj, function(value) { return (isFunc ? method : value[method]).apply(value, args); }); }; // Convenience version of a common use case of `map`: fetching a property. _.pluck = function(obj, key) { return _.map(obj, _.property(key)); }; // Convenience version of a common use case of `filter`: selecting only objects // containing specific `key:value` pairs. _.where = function(obj, attrs) { return _.filter(obj, _.matches(attrs)); }; // Convenience version of a common use case of `find`: getting the first object // containing specific `key:value` pairs. _.findWhere = function(obj, attrs) { return _.find(obj, _.matches(attrs)); }; // Return the maximum element or (element-based computation). // Can't optimize arrays of integers longer than 65,535 elements. // See [WebKit Bug 80797](https://bugs.webkit.org/show_bug.cgi?id=80797) _.max = function(obj, iterator, context) { if (!iterator && _.isArray(obj) && obj[0] === +obj[0] && obj.length < 65535) { return Math.max.apply(Math, obj); } var result = -Infinity, lastComputed = -Infinity; each(obj, function(value, index, list) { var computed = iterator ? iterator.call(context, value, index, list) : value; if (computed > lastComputed) { result = value; lastComputed = computed; } }); return result; }; // Return the minimum element (or element-based computation). _.min = function(obj, iterator, context) { if (!iterator && _.isArray(obj) && obj[0] === +obj[0] && obj.length < 65535) { return Math.min.apply(Math, obj); } var result = Infinity, lastComputed = Infinity; each(obj, function(value, index, list) { var computed = iterator ? iterator.call(context, value, index, list) : value; if (computed < lastComputed) { result = value; lastComputed = computed; } }); return result; }; // Shuffle an array, using the modern version of the // [Fisher-Yates shuffle](http://en.wikipedia.org/wiki/Fisher–Yates_shuffle). _.shuffle = function(obj) { var rand; var index = 0; var shuffled = []; each(obj, function(value) { rand = _.random(index++); shuffled[index - 1] = shuffled[rand]; shuffled[rand] = value; }); return shuffled; }; // Sample **n** random values from a collection. // If **n** is not specified, returns a single random element. // The internal `guard` argument allows it to work with `map`. _.sample = function(obj, n, guard) { if (n == null || guard) { if (obj.length !== +obj.length) obj = _.values(obj); return obj[_.random(obj.length - 1)]; } return _.shuffle(obj).slice(0, Math.max(0, n)); }; // An internal function to generate lookup iterators. var lookupIterator = function(value) { if (value == null) return _.identity; if (_.isFunction(value)) return value; return _.property(value); }; // Sort the object's values by a criterion produced by an iterator. _.sortBy = function(obj, iterator, context) { iterator = lookupIterator(iterator); return _.pluck(_.map(obj, function(value, index, list) { return { value: value, index: index, criteria: iterator.call(context, value, index, list) }; }).sort(function(left, right) { var a = left.criteria; var b = right.criteria; if (a !== b) { if (a > b || a === void 0) return 1; if (a < b || b === void 0) return -1; } return left.index - right.index; }), 'value'); }; // An internal function used for aggregate "group by" operations. var group = function(behavior) { return function(obj, iterator, context) { var result = {}; iterator = lookupIterator(iterator); each(obj, function(value, index) { var key = iterator.call(context, value, index, obj); behavior(result, key, value); }); return result; }; }; // Groups the object's values by a criterion. Pass either a string attribute // to group by, or a function that returns the criterion. _.groupBy = group(function(result, key, value) { _.has(result, key) ? result[key].push(value) : result[key] = [value]; }); // Indexes the object's values by a criterion, similar to `groupBy`, but for // when you know that your index values will be unique. _.indexBy = group(function(result, key, value) { result[key] = value; }); // Counts instances of an object that group by a certain criterion. Pass // either a string attribute to count by, or a function that returns the // criterion. _.countBy = group(function(result, key) { _.has(result, key) ? result[key]++ : result[key] = 1; }); // Use a comparator function to figure out the smallest index at which // an object should be inserted so as to maintain order. Uses binary search. _.sortedIndex = function(array, obj, iterator, context) { iterator = lookupIterator(iterator); var value = iterator.call(context, obj); var low = 0, high = array.length; while (low < high) { var mid = (low + high) >>> 1; iterator.call(context, array[mid]) < value ? low = mid + 1 : high = mid; } return low; }; // Safely create a real, live array from anything iterable. _.toArray = function(obj) { if (!obj) return []; if (_.isArray(obj)) return slice.call(obj); if (obj.length === +obj.length) return _.map(obj, _.identity); return _.values(obj); }; // Return the number of elements in an object. _.size = function(obj) { if (obj == null) return 0; return (obj.length === +obj.length) ? obj.length : _.keys(obj).length; }; // Array Functions // --------------- // Get the first element of an array. Passing **n** will return the first N // values in the array. Aliased as `head` and `take`. The **guard** check // allows it to work with `_.map`. _.first = _.head = _.take = function(array, n, guard) { if (array == null) return void 0; if ((n == null) || guard) return array[0]; if (n < 0) return []; return slice.call(array, 0, n); }; // Returns everything but the last entry of the array. Especially useful on // the arguments object. Passing **n** will return all the values in // the array, excluding the last N. The **guard** check allows it to work with // `_.map`. _.initial = function(array, n, guard) { return slice.call(array, 0, array.length - ((n == null) || guard ? 1 : n)); }; // Get the last element of an array. Passing **n** will return the last N // values in the array. The **guard** check allows it to work with `_.map`. _.last = function(array, n, guard) { if (array == null) return void 0; if ((n == null) || guard) return array[array.length - 1]; return slice.call(array, Math.max(array.length - n, 0)); }; // Returns everything but the first entry of the array. Aliased as `tail` and `drop`. // Especially useful on the arguments object. Passing an **n** will return // the rest N values in the array. The **guard** // check allows it to work with `_.map`. _.rest = _.tail = _.drop = function(array, n, guard) { return slice.call(array, (n == null) || guard ? 1 : n); }; // Trim out all falsy values from an array. _.compact = function(array) { return _.filter(array, _.identity); }; // Internal implementation of a recursive `flatten` function. var flatten = function(input, shallow, output) { if (shallow && _.every(input, _.isArray)) { return concat.apply(output, input); } each(input, function(value) { if (_.isArray(value) || _.isArguments(value)) { shallow ? push.apply(output, value) : flatten(value, shallow, output); } else { output.push(value); } }); return output; }; // Flatten out an array, either recursively (by default), or just one level. _.flatten = function(array, shallow) { return flatten(array, shallow, []); }; // Return a version of the array that does not contain the specified value(s). _.without = function(array) { return _.difference(array, slice.call(arguments, 1)); }; // Split an array into two arrays: one whose elements all satisfy the given // predicate, and one whose elements all do not satisfy the predicate. _.partition = function(array, predicate) { var pass = [], fail = []; each(array, function(elem) { (predicate(elem) ? pass : fail).push(elem); }); return [pass, fail]; }; // Produce a duplicate-free version of the array. If the array has already // been sorted, you have the option of using a faster algorithm. // Aliased as `unique`. _.uniq = _.unique = function(array, isSorted, iterator, context) { if (_.isFunction(isSorted)) { context = iterator; iterator = isSorted; isSorted = false; } var initial = iterator ? _.map(array, iterator, context) : array; var results = []; var seen = []; each(initial, function(value, index) { if (isSorted ? (!index || seen[seen.length - 1] !== value) : !_.contains(seen, value)) { seen.push(value); results.push(array[index]); } }); return results; }; // Produce an array that contains the union: each distinct element from all of // the passed-in arrays. _.union = function() { return _.uniq(_.flatten(arguments, true)); }; // Produce an array that contains every item shared between all the // passed-in arrays. _.intersection = function(array) { var rest = slice.call(arguments, 1); return _.filter(_.uniq(array), function(item) { return _.every(rest, function(other) { return _.contains(other, item); }); }); }; // Take the difference between one array and a number of other arrays. // Only the elements present in just the first array will remain. _.difference = function(array) { var rest = concat.apply(ArrayProto, slice.call(arguments, 1)); return _.filter(array, function(value){ return !_.contains(rest, value); }); }; // Zip together multiple lists into a single array -- elements that share // an index go together. _.zip = function() { var length = _.max(_.pluck(arguments, 'length').concat(0)); var results = new Array(length); for (var i = 0; i < length; i++) { results[i] = _.pluck(arguments, '' + i); } return results; }; // Converts lists into objects. Pass either a single array of `[key, value]` // pairs, or two parallel arrays of the same length -- one of keys, and one of // the corresponding values. _.object = function(list, values) { if (list == null) return {}; var result = {}; for (var i = 0, length = list.length; i < length; i++) { if (values) { result[list[i]] = values[i]; } else { result[list[i][0]] = list[i][1]; } } return result; }; // If the browser doesn't supply us with indexOf (I'm looking at you, **MSIE**), // we need this function. Return the position of the first occurrence of an // item in an array, or -1 if the item is not included in the array. // Delegates to **ECMAScript 5**'s native `indexOf` if available. // If the array is large and already in sort order, pass `true` // for **isSorted** to use binary search. _.indexOf = function(array, item, isSorted) { if (array == null) return -1; var i = 0, length = array.length; if (isSorted) { if (typeof isSorted == 'number') { i = (isSorted < 0 ? Math.max(0, length + isSorted) : isSorted); } else { i = _.sortedIndex(array, item); return array[i] === item ? i : -1; } } if (nativeIndexOf && array.indexOf === nativeIndexOf) return array.indexOf(item, isSorted); for (; i < length; i++) if (array[i] === item) return i; return -1; }; // Delegates to **ECMAScript 5**'s native `lastIndexOf` if available. _.lastIndexOf = function(array, item, from) { if (array == null) return -1; var hasIndex = from != null; if (nativeLastIndexOf && array.lastIndexOf === nativeLastIndexOf) { return hasIndex ? array.lastIndexOf(item, from) : array.lastIndexOf(item); } var i = (hasIndex ? from : array.length); while (i--) if (array[i] === item) return i; return -1; }; // Generate an integer Array containing an arithmetic progression. A port of // the native Python `range()` function. See // [the Python documentation](http://docs.python.org/library/functions.html#range). _.range = function(start, stop, step) { if (arguments.length <= 1) { stop = start || 0; start = 0; } step = arguments[2] || 1; var length = Math.max(Math.ceil((stop - start) / step), 0); var idx = 0; var range = new Array(length); while(idx < length) { range[idx++] = start; start += step; } return range; }; // Function (ahem) Functions // ------------------ // Reusable constructor function for prototype setting. var ctor = function(){}; // Create a function bound to a given object (assigning `this`, and arguments, // optionally). Delegates to **ECMAScript 5**'s native `Function.bind` if // available. _.bind = function(func, context) { var args, bound; if (nativeBind && func.bind === nativeBind) return nativeBind.apply(func, slice.call(arguments, 1)); if (!_.isFunction(func)) throw new TypeError; args = slice.call(arguments, 2); return bound = function() { if (!(this instanceof bound)) return func.apply(context, args.concat(slice.call(arguments))); ctor.prototype = func.prototype; var self = new ctor; ctor.prototype = null; var result = func.apply(self, args.concat(slice.call(arguments))); if (Object(result) === result) return result; return self; }; }; // Partially apply a function by creating a version that has had some of its // arguments pre-filled, without changing its dynamic `this` context. _ acts // as a placeholder, allowing any combination of arguments to be pre-filled. _.partial = function(func) { var boundArgs = slice.call(arguments, 1); return function() { var position = 0; var args = boundArgs.slice(); for (var i = 0, length = args.length; i < length; i++) { if (args[i] === _) args[i] = arguments[position++]; } while (position < arguments.length) args.push(arguments[position++]); return func.apply(this, args); }; }; // Bind a number of an object's methods to that object. Remaining arguments // are the method names to be bound. Useful for ensuring that all callbacks // defined on an object belong to it. _.bindAll = function(obj) { var funcs = slice.call(arguments, 1); if (funcs.length === 0) throw new Error('bindAll must be passed function names'); each(funcs, function(f) { obj[f] = _.bind(obj[f], obj); }); return obj; }; // Memoize an expensive function by storing its results. _.memoize = function(func, hasher) { var memo = {}; hasher || (hasher = _.identity); return function() { var key = hasher.apply(this, arguments); return _.has(memo, key) ? memo[key] : (memo[key] = func.apply(this, arguments)); }; }; // Delays a function for the given number of milliseconds, and then calls // it with the arguments supplied. _.delay = function(func, wait) { var args = slice.call(arguments, 2); return setTimeout(function(){ return func.apply(null, args); }, wait); }; // Defers a function, scheduling it to run after the current call stack has // cleared. _.defer = function(func) { return _.delay.apply(_, [func, 1].concat(slice.call(arguments, 1))); }; // Returns a function, that, when invoked, will only be triggered at most once // during a given window of time. Normally, the throttled function will run // as much as it can, without ever going more than once per `wait` duration; // but if you'd like to disable the execution on the leading edge, pass // `{leading: false}`. To disable execution on the trailing edge, ditto. _.throttle = function(func, wait, options) { var context, args, result; var timeout = null; var previous = 0; options || (options = {}); var later = function() { previous = options.leading === false ? 0 : _.now(); timeout = null; result = func.apply(context, args); context = args = null; }; return function() { var now = _.now(); if (!previous && options.leading === false) previous = now; var remaining = wait - (now - previous); context = this; args = arguments; if (remaining <= 0) { clearTimeout(timeout); timeout = null; previous = now; result = func.apply(context, args); context = args = null; } else if (!timeout && options.trailing !== false) { timeout = setTimeout(later, remaining); } return result; }; }; // Returns a function, that, as long as it continues to be invoked, will not // be triggered. The function will be called after it stops being called for // N milliseconds. If `immediate` is passed, trigger the function on the // leading edge, instead of the trailing. _.debounce = function(func, wait, immediate) { var timeout, args, context, timestamp, result; var later = function() { var last = _.now() - timestamp; if (last < wait) { timeout = setTimeout(later, wait - last); } else { timeout = null; if (!immediate) { result = func.apply(context, args); context = args = null; } } }; return function() { context = this; args = arguments; timestamp = _.now(); var callNow = immediate && !timeout; if (!timeout) { timeout = setTimeout(later, wait); } if (callNow) { result = func.apply(context, args); context = args = null; } return result; }; }; // Returns a function that will be executed at most one time, no matter how // often you call it. Useful for lazy initialization. _.once = function(func) { var ran = false, memo; return function() { if (ran) return memo; ran = true; memo = func.apply(this, arguments); func = null; return memo; }; }; // Returns the first function passed as an argument to the second, // allowing you to adjust arguments, run code before and after, and // conditionally execute the original function. _.wrap = function(func, wrapper) { return _.partial(wrapper, func); }; // Returns a function that is the composition of a list of functions, each // consuming the return value of the function that follows. _.compose = function() { var funcs = arguments; return function() { var args = arguments; for (var i = funcs.length - 1; i >= 0; i--) { args = [funcs[i].apply(this, args)]; } return args[0]; }; }; // Returns a function that will only be executed after being called N times. _.after = function(times, func) { return function() { if (--times < 1) { return func.apply(this, arguments); } }; }; // Object Functions // ---------------- // Retrieve the names of an object's properties. // Delegates to **ECMAScript 5**'s native `Object.keys` _.keys = function(obj) { if (!_.isObject(obj)) return []; if (nativeKeys) return nativeKeys(obj); var keys = []; for (var key in obj) if (_.has(obj, key)) keys.push(key); return keys; }; // Retrieve the values of an object's properties. _.values = function(obj) { var keys = _.keys(obj); var length = keys.length; var values = new Array(length); for (var i = 0; i < length; i++) { values[i] = obj[keys[i]]; } return values; }; // Convert an object into a list of `[key, value]` pairs. _.pairs = function(obj) { var keys = _.keys(obj); var length = keys.length; var pairs = new Array(length); for (var i = 0; i < length; i++) { pairs[i] = [keys[i], obj[keys[i]]]; } return pairs; }; // Invert the keys and values of an object. The values must be serializable. _.invert = function(obj) { var result = {}; var keys = _.keys(obj); for (var i = 0, length = keys.length; i < length; i++) { result[obj[keys[i]]] = keys[i]; } return result; }; // Return a sorted list of the function names available on the object. // Aliased as `methods` _.functions = _.methods = function(obj) { var names = []; for (var key in obj) { if (_.isFunction(obj[key])) names.push(key); } return names.sort(); }; // Extend a given object with all the properties in passed-in object(s). _.extend = function(obj) { each(slice.call(arguments, 1), function(source) { if (source) { for (var prop in source) { obj[prop] = source[prop]; } } }); return obj; }; // Return a copy of the object only containing the whitelisted properties. _.pick = function(obj) { var copy = {}; var keys = concat.apply(ArrayProto, slice.call(arguments, 1)); each(keys, function(key) { if (key in obj) copy[key] = obj[key]; }); return copy; }; // Return a copy of the object without the blacklisted properties. _.omit = function(obj) { var copy = {}; var keys = concat.apply(ArrayProto, slice.call(arguments, 1)); for (var key in obj) { if (!_.contains(keys, key)) copy[key] = obj[key]; } return copy; }; // Fill in a given object with default properties. _.defaults = function(obj) { each(slice.call(arguments, 1), function(source) { if (source) { for (var prop in source) { if (obj[prop] === void 0) obj[prop] = source[prop]; } } }); return obj; }; // Create a (shallow-cloned) duplicate of an object. _.clone = function(obj) { if (!_.isObject(obj)) return obj; return _.isArray(obj) ? obj.slice() : _.extend({}, obj); }; // Invokes interceptor with the obj, and then returns obj. // The primary purpose of this method is to "tap into" a method chain, in // order to perform operations on intermediate results within the chain. _.tap = function(obj, interceptor) { interceptor(obj); return obj; }; // Internal recursive comparison function for `isEqual`. var eq = function(a, b, aStack, bStack) { // Identical objects are equal. `0 === -0`, but they aren't identical. // See the [Harmony `egal` proposal](http://wiki.ecmascript.org/doku.php?id=harmony:egal). if (a === b) return a !== 0 || 1 / a == 1 / b; // A strict comparison is necessary because `null == undefined`. if (a == null || b == null) return a === b; // Unwrap any wrapped objects. if (a instanceof _) a = a._wrapped; if (b instanceof _) b = b._wrapped; // Compare `[[Class]]` names. var className = toString.call(a); if (className != toString.call(b)) return false; switch (className) { // Strings, numbers, dates, and booleans are compared by value. case '[object String]': // Primitives and their corresponding object wrappers are equivalent; thus, `"5"` is // equivalent to `new String("5")`. return a == String(b); case '[object Number]': // `NaN`s are equivalent, but non-reflexive. An `egal` comparison is performed for // other numeric values. return a != +a ? b != +b : (a == 0 ? 1 / a == 1 / b : a == +b); case '[object Date]': case '[object Boolean]': // Coerce dates and booleans to numeric primitive values. Dates are compared by their // millisecond representations. Note that invalid dates with millisecond representations // of `NaN` are not equivalent. return +a == +b; // RegExps are compared by their source patterns and flags. case '[object RegExp]': return a.source == b.source && a.global == b.global && a.multiline == b.multiline && a.ignoreCase == b.ignoreCase; } if (typeof a != 'object' || typeof b != 'object') return false; // Assume equality for cyclic structures. The algorithm for detecting cyclic // structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`. var length = aStack.length; while (length--) { // Linear search. Performance is inversely proportional to the number of // unique nested structures. if (aStack[length] == a) return bStack[length] == b; } // Objects with different constructors are not equivalent, but `Object`s // from different frames are. var aCtor = a.constructor, bCtor = b.constructor; if (aCtor !== bCtor && !(_.isFunction(aCtor) && (aCtor instanceof aCtor) && _.isFunction(bCtor) && (bCtor instanceof bCtor)) && ('constructor' in a && 'constructor' in b)) { return false; } // Add the first object to the stack of traversed objects. aStack.push(a); bStack.push(b); var size = 0, result = true; // Recursively compare objects and arrays. if (className == '[object Array]') { // Compare array lengths to determine if a deep comparison is necessary. size = a.length; result = size == b.length; if (result) { // Deep compare the contents, ignoring non-numeric properties. while (size--) { if (!(result = eq(a[size], b[size], aStack, bStack))) break; } } } else { // Deep compare objects. for (var key in a) { if (_.has(a, key)) { // Count the expected number of properties. size++; // Deep compare each member. if (!(result = _.has(b, key) && eq(a[key], b[key], aStack, bStack))) break; } } // Ensure that both objects contain the same number of properties. if (result) { for (key in b) { if (_.has(b, key) && !(size--)) break; } result = !size; } } // Remove the first object from the stack of traversed objects. aStack.pop(); bStack.pop(); return result; }; // Perform a deep comparison to check if two objects are equal. _.isEqual = function(a, b) { return eq(a, b, [], []); }; // Is a given array, string, or object empty? // An "empty" object has no enumerable own-properties. _.isEmpty = function(obj) { if (obj == null) return true; if (_.isArray(obj) || _.isString(obj)) return obj.length === 0; for (var key in obj) if (_.has(obj, key)) return false; return true; }; // Is a given value a DOM element? _.isElement = function(obj) { return !!(obj && obj.nodeType === 1); }; // Is a given value an array? // Delegates to ECMA5's native Array.isArray _.isArray = nativeIsArray || function(obj) { return toString.call(obj) == '[object Array]'; }; // Is a given variable an object? _.isObject = function(obj) { return obj === Object(obj); }; // Add some isType methods: isArguments, isFunction, isString, isNumber, isDate, isRegExp. each(['Arguments', 'Function', 'String', 'Number', 'Date', 'RegExp'], function(name) { _['is' + name] = function(obj) { return toString.call(obj) == '[object ' + name + ']'; }; }); // Define a fallback version of the method in browsers (ahem, IE), where // there isn't any inspectable "Arguments" type. if (!_.isArguments(arguments)) { _.isArguments = function(obj) { return !!(obj && _.has(obj, 'callee')); }; } // Optimize `isFunction` if appropriate. if (typeof (/./) !== 'function') { _.isFunction = function(obj) { return typeof obj === 'function'; }; } // Is a given object a finite number? _.isFinite = function(obj) { return isFinite(obj) && !isNaN(parseFloat(obj)); }; // Is the given value `NaN`? (NaN is the only number which does not equal itself). _.isNaN = function(obj) { return _.isNumber(obj) && obj != +obj; }; // Is a given value a boolean? _.isBoolean = function(obj) { return obj === true || obj === false || toString.call(obj) == '[object Boolean]'; }; // Is a given value equal to null? _.isNull = function(obj) { return obj === null; }; // Is a given variable undefined? _.isUndefined = function(obj) { return obj === void 0; }; // Shortcut function for checking if an object has a given property directly // on itself (in other words, not on a prototype). _.has = function(obj, key) { return hasOwnProperty.call(obj, key); }; // Utility Functions // ----------------- // Run Underscore.js in *noConflict* mode, returning the `_` variable to its // previous owner. Returns a reference to the Underscore object. _.noConflict = function() { root._ = previousUnderscore; return this; }; // Keep the identity function around for default iterators. _.identity = function(value) { return value; }; _.constant = function(value) { return function () { return value; }; }; _.property = function(key) { return function(obj) { return obj[key]; }; }; // Returns a predicate for checking whether an object has a given set of `key:value` pairs. _.matches = function(attrs) { return function(obj) { if (obj === attrs) return true; //avoid comparing an object to itself. for (var key in attrs) { if (attrs[key] !== obj[key]) return false; } return true; } }; // Run a function **n** times. _.times = function(n, iterator, context) { var accum = Array(Math.max(0, n)); for (var i = 0; i < n; i++) accum[i] = iterator.call(context, i); return accum; }; // Return a random integer between min and max (inclusive). _.random = function(min, max) { if (max == null) { max = min; min = 0; } return min + Math.floor(Math.random() * (max - min + 1)); }; // A (possibly faster) way to get the current timestamp as an integer. _.now = Date.now || function() { return new Date().getTime(); }; // List of HTML entities for escaping. var entityMap = { escape: { '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' } }; entityMap.unescape = _.invert(entityMap.escape); // Regexes containing the keys and values listed immediately above. var entityRegexes = { escape: new RegExp('[' + _.keys(entityMap.escape).join('') + ']', 'g'), unescape: new RegExp('(' + _.keys(entityMap.unescape).join('|') + ')', 'g') }; // Functions for escaping and unescaping strings to/from HTML interpolation. _.each(['escape', 'unescape'], function(method) { _[method] = function(string) { if (string == null) return ''; return ('' + string).replace(entityRegexes[method], function(match) { return entityMap[method][match]; }); }; }); // If the value of the named `property` is a function then invoke it with the // `object` as context; otherwise, return it. _.result = function(object, property) { if (object == null) return void 0; var value = object[property]; return _.isFunction(value) ? value.call(object) : value; }; // Add your own custom functions to the Underscore object. _.mixin = function(obj) { each(_.functions(obj), function(name) { var func = _[name] = obj[name]; _.prototype[name] = function() { var args = [this._wrapped]; push.apply(args, arguments); return result.call(this, func.apply(_, args)); }; }); }; // Generate a unique integer id (unique within the entire client session). // Useful for temporary DOM ids. var idCounter = 0; _.uniqueId = function(prefix) { var id = ++idCounter + ''; return prefix ? prefix + id : id; }; // By default, Underscore uses ERB-style template delimiters, change the // following template settings to use alternative delimiters. _.templateSettings = { evaluate : /<%([\s\S]+?)%>/g, interpolate : /<%=([\s\S]+?)%>/g, escape : /<%-([\s\S]+?)%>/g }; // When customizing `templateSettings`, if you don't want to define an // interpolation, evaluation or escaping regex, we need one that is // guaranteed not to match. var noMatch = /(.)^/; // Certain characters need to be escaped so that they can be put into a // string literal. var escapes = { "'": "'", '\\': '\\', '\r': 'r', '\n': 'n', '\t': 't', '\u2028': 'u2028', '\u2029': 'u2029' }; var escaper = /\\|'|\r|\n|\t|\u2028|\u2029/g; // JavaScript micro-templating, similar to John Resig's implementation. // Underscore templating handles arbitrary delimiters, preserves whitespace, // and correctly escapes quotes within interpolated code. _.template = function(text, data, settings) { var render; settings = _.defaults({}, settings, _.templateSettings); // Combine delimiters into one regular expression via alternation. var matcher = new RegExp([ (settings.escape || noMatch).source, (settings.interpolate || noMatch).source, (settings.evaluate || noMatch).source ].join('|') + '|$', 'g'); // Compile the template source, escaping string literals appropriately. var index = 0; var source = "__p+='"; text.replace(matcher, function(match, escape, interpolate, evaluate, offset) { source += text.slice(index, offset) .replace(escaper, function(match) { return '\\' + escapes[match]; }); if (escape) { source += "'+\n((__t=(" + escape + "))==null?'':_.escape(__t))+\n'"; } if (interpolate) { source += "'+\n((__t=(" + interpolate + "))==null?'':__t)+\n'"; } if (evaluate) { source += "';\n" + evaluate + "\n__p+='"; } index = offset + match.length; return match; }); source += "';\n"; // If a variable is not specified, place data values in local scope. if (!settings.variable) source = 'with(obj||{}){\n' + source + '}\n'; source = "var __t,__p='',__j=Array.prototype.join," + "print=function(){__p+=__j.call(arguments,'');};\n" + source + "return __p;\n"; try { render = new Function(settings.variable || 'obj', '_', source); } catch (e) { e.source = source; throw e; } if (data) return render(data, _); var template = function(data) { return render.call(this, data, _); }; // Provide the compiled function source as a convenience for precompilation. template.source = 'function(' + (settings.variable || 'obj') + '){\n' + source + '}'; return template; }; // Add a "chain" function, which will delegate to the wrapper. _.chain = function(obj) { return _(obj).chain(); }; // OOP // --------------- // If Underscore is called as a function, it returns a wrapped object that // can be used OO-style. This wrapper holds altered versions of all the // underscore functions. Wrapped objects may be chained. // Helper function to continue chaining intermediate results. var result = function(obj) { return this._chain ? _(obj).chain() : obj; }; // Add all of the Underscore functions to the wrapper object. _.mixin(_); // Add all mutator Array functions to the wrapper. each(['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], function(name) { var method = ArrayProto[name]; _.prototype[name] = function() { var obj = this._wrapped; method.apply(obj, arguments); if ((name == 'shift' || name == 'splice') && obj.length === 0) delete obj[0]; return result.call(this, obj); }; }); // Add all accessor Array functions to the wrapper. each(['concat', 'join', 'slice'], function(name) { var method = ArrayProto[name]; _.prototype[name] = function() { return result.call(this, method.apply(this._wrapped, arguments)); }; }); _.extend(_.prototype, { // Start chaining a wrapped Underscore object. chain: function() { this._chain = true; return this; }, // Extracts the result from a wrapped and chained object. value: function() { return this._wrapped; } }); // AMD registration happens at the end for compatibility with AMD loaders // that may not enforce next-turn semantics on modules. Even though general // practice for AMD registration is to be anonymous, underscore registers // as a named module because, like jQuery, it is a base library that is // popular enough to be bundled in a third party lib, but not be part of // an AMD load request. Those cases could generate an error when an // anonymous define() is called outside of a loader request. if (typeof define === 'function' && define.amd) { define('underscore', [], function() { return _; }); } }).call(this); },{}],72:[function(require,module,exports){ module.exports={ "name": "carto", "version": "0.15.1-cdb1", "description": "CartoCSS Stylesheet Compiler", "url": "https://github.com/cartodb/carto", "repository": { "type": "git", "url": "http://github.com/cartodb/carto.git" }, "author": { "name": "CartoDB", "url": "http://cartodb.com/" }, "keywords": [ "maps", "css", "stylesheets" ], "contributors": [ { "name": "Tom MacWright", "email": "macwright@gmail.com" }, { "name": "Konstantin Käfer" }, { "name": "Alexis Sellier", "email": "self@cloudhead.net" }, { "name": "Raul Ochoa", "email": "rochoa@cartodb.com" }, { "name": "Javi Santana", "email": "jsantana@cartodb.com" } ], "licenses": [ { "type": "Apache" } ], "bin": { "carto": "./bin/carto" }, "man": [ "./man/carto.1" ], "main": "./lib/carto/index", "engines": { "node": ">=0.4.x" }, "dependencies": { "underscore": "~1.6.0", "mapnik-reference": "~6.0.2", "optimist": "~0.6.0" }, "devDependencies": { "mocha": "1.12.x", "jshint": "0.2.x", "sax": "0.1.x", "istanbul": "~0.2.14", "coveralls": "~2.10.1", "browserify": "~7.0.0", "uglify-js": "1.3.3" }, "scripts": { "pretest": "npm install", "test": "mocha -R spec", "coverage": "istanbul cover ./node_modules/.bin/_mocha && coveralls < ./coverage/lcov.info" }, "readme": "# CartoCSS\n\n[![Build Status](https://secure.travis-ci.org/mapbox/carto.png)](http://travis-ci.org/mapbox/carto)\n\nIs as stylesheet renderer for javascript, It's an evolution of the Mapnik renderer from Mapbox.\nPlease, see original [Mapbox repo](http://github.com/mapbox/carto) for more information and credits\n\n## Quick Start\n\n```javascript\n// shader is a CartoCSS object\n\nvar cartocss = [\n '#layer {',\n ' marker-width: [property]',\n ' marker-fill: red',\n '}'\n].join('')\nvar shader = new carto.RendererJS().render(cartocss);\nvar layers = shader.getLayers()\nfor (var i = 0; i < layers.length; ++i) {\n var layer = layers[i];\n console.log(\"layer name: \", layer.fullName())\n console.log(\"- frames: \", layer.frames())\n console.log(\"- attachment: \", layer.attachment())\n\n var layerShader = layer.getStyle({ property: 1 }, { zoom: 10 })\n console.log(layerShader['marker-width']) // 1\n console.log(layerShader['marker-fill']) // #FF0000\n}\n\n```\n\n# API\n\n## RendererJS\n\n### render(cartocss)\n\n## CartoCSS\n\ncompiled cartocss object\n\n### getLayers\n\nreturn the layers, an array of ``CartoCSS.Layer`` object\n\n### getDefault\n\nreturn the default layer (``CartoCSS.Layer``), usually the Map layer\n\n\n### findLayer(where)\n\nfind a layer using where object.\n\n```\nshader.findLayer({ name: 'test' })\n```\n\n## CartoCSS.Layer\n\n### getStyle(props, context)\n\nreturn the evaluated style:\n - props: object containing properties needed to render the style. If the cartocss style uses\n some variables they should be passed in this object\n - context: rendering context variables like ``zoom`` or animation ``frame``\n\n\n\n\n\n\n\n\n\n\n## Reference Documentation\n\n* [mapbox.com/carto](http://mapbox.com/carto/)\n\n\n", "readmeFilename": "README.md", "bugs": { "url": "https://github.com/cartodb/carto/issues" }, "homepage": "https://github.com/cartodb/carto", "_id": "carto@0.15.1-cdb1", "dist": { "shasum": "ab2cd136b72f8f05ac960987eea099cbedd6948e" }, "_from": "https://github.com/CartoDB/carto/archive/master.tar.gz", "_resolved": "https://github.com/CartoDB/carto/archive/master.tar.gz" } },{}]},{},[10])(10) });