code
stringlengths
2
1.05M
/* Copyright (c) 2006-2015 by OpenLayers Contributors (see authors.txt for * full list of contributors). Published under the 2-clause BSD license. * See license.txt in the OpenLayers distribution or repository for the * full text of the license. */ /** * @requires OpenLayers/Format/WFSCapabilities/v1.js */ /** * Class: OpenLayers.Format.WFSCapabilities/v1_0_0 * Read WFS Capabilities version 1.0.0. * * Inherits from: * - <OpenLayers.Format.WFSCapabilities.v1> */ OpenLayers.Format.WFSCapabilities.v1_0_0 = OpenLayers.Class( OpenLayers.Format.WFSCapabilities.v1, { /** * Constructor: OpenLayers.Format.WFSCapabilities.v1_0_0 * Create a new parser for WFS capabilities version 1.0.0. * * Parameters: * options - {Object} An optional object whose properties will be set on * this instance. */ /** * Property: readers * Contains public functions, grouped by namespace prefix, that will * be applied when a namespaced node is found matching the function * name. The function will be applied in the scope of this parser * with two arguments: the node being read and a context object passed * from the parent. */ readers: { "wfs": OpenLayers.Util.applyDefaults({ "Service": function(node, capabilities) { capabilities.service = {}; this.readChildNodes(node, capabilities.service); }, "Fees": function(node, service) { var fees = this.getChildValue(node); if (fees && fees.toLowerCase() != "none") { service.fees = fees; } }, "AccessConstraints": function(node, service) { var constraints = this.getChildValue(node); if (constraints && constraints.toLowerCase() != "none") { service.accessConstraints = constraints; } }, "OnlineResource": function(node, service) { var onlineResource = this.getChildValue(node); if (onlineResource && onlineResource.toLowerCase() != "none") { service.onlineResource = onlineResource; } }, "Keywords": function(node, service) { var keywords = this.getChildValue(node); if (keywords && keywords.toLowerCase() != "none") { service.keywords = keywords.split(', '); } }, "Capability": function(node, capabilities) { capabilities.capability = {}; this.readChildNodes(node, capabilities.capability); }, "Request": function(node, obj) { obj.request = {}; this.readChildNodes(node, obj.request); }, "GetFeature": function(node, request) { request.getfeature = { href: {}, // DCPType formats: [] // ResultFormat }; this.readChildNodes(node, request.getfeature); }, "ResultFormat": function(node, obj) { var children = node.childNodes; var childNode; for(var i=0; i<children.length; i++) { childNode = children[i]; if(childNode.nodeType == 1) { obj.formats.push(childNode.nodeName); } } }, "DCPType": function(node, obj) { this.readChildNodes(node, obj); }, "HTTP": function(node, obj) { this.readChildNodes(node, obj.href); }, "Get": function(node, obj) { obj.get = node.getAttribute("onlineResource"); }, "Post": function(node, obj) { obj.post = node.getAttribute("onlineResource"); }, "SRS": function(node, obj) { var srs = this.getChildValue(node); if (srs) { obj.srs = srs; } }, "LatLongBoundingBox": function(node, obj) { obj.latLongBoundingBox = [ parseFloat(node.getAttribute("minx")), parseFloat(node.getAttribute("miny")), parseFloat(node.getAttribute("maxx")), parseFloat(node.getAttribute("maxy")) ]; } }, OpenLayers.Format.WFSCapabilities.v1.prototype.readers["wfs"]) }, CLASS_NAME: "OpenLayers.Format.WFSCapabilities.v1_0_0" });
/** @license * @pnp/logging v1.0.0-beta.11 - pnp - light-weight, subscribable logging framework * MIT (https://github.com/pnp/pnp/blob/master/LICENSE) * Copyright (c) 2018 Microsoft * docs: http://officedev.github.io/PnP-JS-Core * source: https://github.com/pnp/pnp * bugs: https://github.com/pnp/pnp/issues */ (function webpackUniversalModuleDefinition(root, factory) { if(typeof exports === 'object' && typeof module === 'object') module.exports = factory(); else if(typeof define === 'function' && define.amd) define([], factory); else if(typeof exports === 'object') exports["pnp"] = factory(); else root["pnp"] = factory(); })(typeof self !== 'undefined' ? self : this, function() { return /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) { /******/ return installedModules[moduleId].exports; /******/ } /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ i: moduleId, /******/ l: false, /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ /******/ // Flag the module as loaded /******/ module.l = true; /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /******/ /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ /******/ // define getter function for harmony exports /******/ __webpack_require__.d = function(exports, name, getter) { /******/ if(!__webpack_require__.o(exports, name)) { /******/ Object.defineProperty(exports, name, { /******/ configurable: false, /******/ enumerable: true, /******/ get: getter /******/ }); /******/ } /******/ }; /******/ /******/ // getDefaultExport function for compatibility with non-harmony modules /******/ __webpack_require__.n = function(module) { /******/ var getter = module && module.__esModule ? /******/ function getDefault() { return module['default']; } : /******/ function getModuleExports() { return module; }; /******/ __webpack_require__.d(getter, 'a', getter); /******/ return getter; /******/ }; /******/ /******/ // Object.prototype.hasOwnProperty.call /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; /******/ /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(__webpack_require__.s = 0); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; Object.defineProperty(__webpack_exports__, "__esModule", { value: true }); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__src_logging__ = __webpack_require__(1); /* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "Logger", function() { return __WEBPACK_IMPORTED_MODULE_0__src_logging__["c"]; }); /* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "ConsoleListener", function() { return __WEBPACK_IMPORTED_MODULE_0__src_logging__["a"]; }); /* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "FunctionListener", function() { return __WEBPACK_IMPORTED_MODULE_0__src_logging__["b"]; }); //# sourceMappingURL=index.js.map /***/ }), /* 1 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__logger__ = __webpack_require__(2); /* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return __WEBPACK_IMPORTED_MODULE_0__logger__["a"]; }); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__listeners__ = __webpack_require__(3); /* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return __WEBPACK_IMPORTED_MODULE_1__listeners__["a"]; }); /* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return __WEBPACK_IMPORTED_MODULE_1__listeners__["b"]; }); //# sourceMappingURL=logging.js.map /***/ }), /* 2 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return Logger; }); /** * Class used to subscribe ILogListener and log messages throughout an application * */ var Logger = /** @class */ (function () { function Logger() { } Object.defineProperty(Logger, "activeLogLevel", { /** * Gets or sets the active log level to apply for log filtering */ get: function () { return Logger.instance.activeLogLevel; }, set: function (value) { Logger.instance.activeLogLevel = value; }, enumerable: true, configurable: true }); Object.defineProperty(Logger, "instance", { get: function () { if (typeof Logger._instance === "undefined" || Logger._instance === null) { Logger._instance = new LoggerImpl(); } return Logger._instance; }, enumerable: true, configurable: true }); /** * Adds ILogListener instances to the set of subscribed listeners * * @param listeners One or more listeners to subscribe to this log */ Logger.subscribe = function () { var listeners = []; for (var _i = 0; _i < arguments.length; _i++) { listeners[_i] = arguments[_i]; } listeners.map(function (listener) { return Logger.instance.subscribe(listener); }); }; /** * Clears the subscribers collection, returning the collection before modifiction */ Logger.clearSubscribers = function () { return Logger.instance.clearSubscribers(); }; Object.defineProperty(Logger, "count", { /** * Gets the current subscriber count */ get: function () { return Logger.instance.count; }, enumerable: true, configurable: true }); /** * Writes the supplied string to the subscribed listeners * * @param message The message to write * @param level [Optional] if supplied will be used as the level of the entry (Default: LogLevel.Verbose) */ Logger.write = function (message, level) { if (level === void 0) { level = 0 /* Verbose */; } Logger.instance.log({ level: level, message: message }); }; /** * Writes the supplied string to the subscribed listeners * * @param json The json object to stringify and write * @param level [Optional] if supplied will be used as the level of the entry (Default: LogLevel.Verbose) */ Logger.writeJSON = function (json, level) { if (level === void 0) { level = 0 /* Verbose */; } Logger.instance.log({ level: level, message: JSON.stringify(json) }); }; /** * Logs the supplied entry to the subscribed listeners * * @param entry The message to log */ Logger.log = function (entry) { Logger.instance.log(entry); }; /** * Logs an error object to the subscribed listeners * * @param err The error object */ Logger.error = function (err) { Logger.instance.log({ data: err, level: 3 /* Error */, message: "[" + err.name + "]::" + err.message }); }; return Logger; }()); var LoggerImpl = /** @class */ (function () { function LoggerImpl(activeLogLevel, subscribers) { if (activeLogLevel === void 0) { activeLogLevel = 2 /* Warning */; } if (subscribers === void 0) { subscribers = []; } this.activeLogLevel = activeLogLevel; this.subscribers = subscribers; } LoggerImpl.prototype.subscribe = function (listener) { this.subscribers.push(listener); }; LoggerImpl.prototype.clearSubscribers = function () { var s = this.subscribers.slice(0); this.subscribers.length = 0; return s; }; Object.defineProperty(LoggerImpl.prototype, "count", { get: function () { return this.subscribers.length; }, enumerable: true, configurable: true }); LoggerImpl.prototype.write = function (message, level) { if (level === void 0) { level = 0 /* Verbose */; } this.log({ level: level, message: message }); }; LoggerImpl.prototype.log = function (entry) { if (typeof entry !== "undefined" && this.activeLogLevel <= entry.level) { this.subscribers.map(function (subscriber) { return subscriber.log(entry); }); } }; return LoggerImpl; }()); //# sourceMappingURL=logger.js.map /***/ }), /* 3 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return ConsoleListener; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return FunctionListener; }); /** * Implementation of LogListener which logs to the console * */ var ConsoleListener = /** @class */ (function () { function ConsoleListener() { } /** * Any associated data that a given logging listener may choose to log or ignore * * @param entry The information to be logged */ ConsoleListener.prototype.log = function (entry) { var msg = this.format(entry); switch (entry.level) { case 0 /* Verbose */: case 1 /* Info */: console.log(msg); break; case 2 /* Warning */: console.warn(msg); break; case 3 /* Error */: console.error(msg); break; } }; /** * Formats the message * * @param entry The information to format into a string */ ConsoleListener.prototype.format = function (entry) { var msg = []; msg.push("Message: " + entry.message); if (typeof entry.data !== "undefined") { msg.push(" Data: " + JSON.stringify(entry.data)); } return msg.join(""); }; return ConsoleListener; }()); /** * Implementation of LogListener which logs to the supplied function * */ var FunctionListener = /** @class */ (function () { /** * Creates a new instance of the FunctionListener class * * @constructor * @param method The method to which any logging data will be passed */ function FunctionListener(method) { this.method = method; } /** * Any associated data that a given logging listener may choose to log or ignore * * @param entry The information to be logged */ FunctionListener.prototype.log = function (entry) { this.method(entry); }; return FunctionListener; }()); //# sourceMappingURL=listeners.js.map /***/ }) /******/ ]); }); //# sourceMappingURL=logging.es5.umd.bundle.js.map
define( //begin v1.x content { "field-quarter-short-relative+0": "ce trim.", "field-quarter-short-relative+1": "le trim. proch.", "field-tue-relative+-1": "mardi dernier", "field-year": "année", "field-wed-relative+0": "ce mercredi", "field-wed-relative+1": "mercredi prochain", "field-minute": "minute", "field-month-narrow-relative+-1": "le mois dernier", "field-tue-narrow-relative+0": "ce mar.", "field-tue-narrow-relative+1": "mar. prochain", "field-thu-short-relative+0": "ce jeu.", "field-day-short-relative+-1": "hier", "field-thu-short-relative+1": "jeu. prochain", "field-day-relative+0": "aujourd’hui", "field-day-short-relative+-2": "avant-hier", "field-day-relative+1": "demain", "field-week-narrow-relative+0": "cette semaine", "field-day-relative+2": "après-demain", "field-week-narrow-relative+1": "la semaine prochaine", "field-wed-narrow-relative+-1": "mer. dernier", "field-year-narrow": "a", "field-era-short": "ère", "field-year-narrow-relative+0": "cette année", "field-tue-relative+0": "ce mardi", "field-year-narrow-relative+1": "l’année prochaine", "field-tue-relative+1": "mardi prochain", "field-weekdayOfMonth": "jour (mois)", "field-second-short": "s", "dateFormatItem-MMMd": "d MMM", "field-weekdayOfMonth-narrow": "jour (mois)", "field-week-relative+0": "cette semaine", "field-month-relative+0": "ce mois-ci", "field-week-relative+1": "la semaine prochaine", "field-month-relative+1": "le mois prochain", "field-sun-narrow-relative+0": "ce dim.", "field-mon-short-relative+0": "ce lun.", "field-sun-narrow-relative+1": "dim. prochain", "field-mon-short-relative+1": "lun. prochain", "field-second-relative+0": "maintenant", "dateFormatItem-yyyyQQQ": "QQQ y G", "months-standAlone-narrow": [ "J", "F", "M", "A", "M", "J", "J", "A", "S", "O", "N", "D" ], "eraNames": [ "ère bouddhique" ], "field-weekOfMonth": "semaine (mois)", "field-month-short": "m.", "dateFormatItem-GyMMMEd": "E d MMM y G", "dateFormatItem-yyyyMd": "d/M/y GGGGG", "field-day": "jour", "field-dayOfYear-short": "j (an)", "field-year-relative+-1": "l’année dernière", "field-sat-short-relative+-1": "sam. dernier", "field-hour-relative+0": "cette heure-ci", "dateFormatItem-yyyyMEd": "E d/M/y GGGGG", "field-wed-relative+-1": "mercredi dernier", "field-sat-narrow-relative+-1": "sam. dernier", "field-second": "seconde", "days-standAlone-narrow": [ "D", "L", "M", "M", "J", "V", "S" ], "dateFormat-long": "d MMMM y G", "dateFormatItem-GyMMMd": "d MMM y G", "field-hour-short-relative+0": "cette h", "field-quarter": "trimestre", "field-week-short": "sem.", "field-day-narrow-relative+0": "aujourd’hui", "field-day-narrow-relative+1": "demain", "field-day-narrow-relative+2": "après-demain", "quarters-standAlone-wide": [ "1er trimestre", "2e trimestre", "3e trimestre", "4e trimestre" ], "days-format-narrow": [ "D", "L", "M", "M", "J", "V", "S" ], "field-tue-short-relative+0": "ce mar.", "field-tue-short-relative+1": "mar. prochain", "field-month-short-relative+-1": "le mois dernier", "field-mon-relative+-1": "lundi dernier", "dateFormatItem-GyMMM": "MMM y G", "field-month": "mois", "field-day-narrow": "j", "dateFormatItem-MMM": "LLL", "field-minute-short": "min", "field-dayperiod": "cadran", "field-sat-short-relative+0": "ce sam.", "field-sat-short-relative+1": "sam. prochain", "dateFormat-medium": "d MMM y G", "dateFormatItem-yyyyMMMM": "MMMM y G", "eraAbbr": [ "E. B." ], "quarters-standAlone-abbr": [ "T1", "T2", "T3", "T4" ], "dateFormatItem-yyyyM": "M/y GGGGG", "field-second-narrow": "s", "field-mon-relative+0": "ce lundi", "field-mon-relative+1": "lundi prochain", "field-day-narrow-relative+-1": "hier", "field-year-short": "an", "field-day-narrow-relative+-2": "avant-hier", "months-format-narrow": [ "J", "F", "M", "A", "M", "J", "J", "A", "S", "O", "N", "D" ], "field-quarter-relative+-1": "le trimestre dernier", "dateFormatItem-yyyyMMMd": "d MMM y G", "field-dayperiod-narrow": "cadran", "field-week-narrow-relative+-1": "la semaine dernière", "days-format-short": [ "di", "lu", "ma", "me", "je", "ve", "sa" ], "field-dayOfYear": "jour (année)", "field-sat-relative+-1": "samedi dernier", "dateTimeFormat-long": "{1} 'à' {0}", "dateFormatItem-Md": "d/M", "field-minute-narrow-relative+0": "cette min", "field-hour": "heure", "months-format-wide": [ "janvier", "février", "mars", "avril", "mai", "juin", "juillet", "août", "septembre", "octobre", "novembre", "décembre" ], "dateFormat-full": "EEEE d MMMM y G", "field-month-relative+-1": "le mois dernier", "field-quarter-short": "trim.", "field-sat-narrow-relative+0": "ce sam.", "field-fri-relative+0": "ce vendredi", "field-sat-narrow-relative+1": "sam. prochain", "field-fri-relative+1": "vendredi prochain", "field-month-narrow-relative+0": "ce mois-ci", "field-month-narrow-relative+1": "le mois prochain", "field-sun-short-relative+0": "ce dim.", "field-sun-short-relative+1": "dim. prochain", "field-week-relative+-1": "la semaine dernière", "field-quarter-short-relative+-1": "le trim. dern.", "field-minute-short-relative+0": "cette min", "months-format-abbr": [ "janv.", "févr.", "mars", "avr.", "mai", "juin", "juil.", "août", "sept.", "oct.", "nov.", "déc." ], "field-quarter-relative+0": "ce trimestre", "field-minute-relative+0": "cette minute-ci", "field-quarter-relative+1": "le trimestre prochain", "field-wed-short-relative+-1": "mer. dernier", "dateFormat-short": "dd/MM/y GGGGG", "field-thu-short-relative+-1": "jeu. dernier", "field-year-narrow-relative+-1": "l’année dernière", "days-standAlone-wide": [ "dimanche", "lundi", "mardi", "mercredi", "jeudi", "vendredi", "samedi" ], "dateFormatItem-yyyyMMMEd": "E d MMM y G", "field-mon-narrow-relative+-1": "lun. dernier", "dateFormatItem-MMMMd": "d MMMM", "field-thu-narrow-relative+-1": "jeu. dernier", "field-tue-narrow-relative+-1": "mar. dernier", "field-weekOfMonth-short": "sem. (m.)", "dateFormatItem-yyyy": "y G", "field-wed-short-relative+0": "ce mer.", "dateFormatItem-M": "L", "months-standAlone-wide": [ "janvier", "février", "mars", "avril", "mai", "juin", "juillet", "août", "septembre", "octobre", "novembre", "décembre" ], "field-wed-short-relative+1": "mer. prochain", "field-sun-relative+-1": "dimanche dernier", "days-standAlone-abbr": [ "dim.", "lun.", "mar.", "mer.", "jeu.", "ven.", "sam." ], "dateTimeFormat-full": "{1} 'à' {0}", "dateFormatItem-d": "d", "field-weekday": "jour de la semaine", "field-day-short-relative+0": "aujourd’hui", "field-quarter-narrow-relative+0": "ce trim.", "field-day-short-relative+1": "demain", "field-sat-relative+0": "ce samedi", "field-quarter-narrow-relative+1": "trim. proch.", "field-day-short-relative+2": "après-demain", "field-sat-relative+1": "samedi prochain", "field-week-short-relative+0": "cette semaine", "field-week-short-relative+1": "la semaine prochaine", "months-standAlone-abbr": [ "janv.", "févr.", "mars", "avr.", "mai", "juin", "juil.", "août", "sept.", "oct.", "nov.", "déc." ], "field-dayOfYear-narrow": "j (an)", "field-month-short-relative+0": "ce mois-ci", "field-month-short-relative+1": "le mois prochain", "field-weekdayOfMonth-short": "jour (mois)", "dateFormatItem-MEd": "E d/M", "field-zone-narrow": "fuseau horaire", "dateFormatItem-y": "y G", "field-thu-narrow-relative+0": "ce jeu.", "field-thu-narrow-relative+1": "jeu. prochain", "field-sun-narrow-relative+-1": "dim. dernier", "field-mon-short-relative+-1": "lun. dernier", "field-thu-relative+0": "ce jeudi", "field-thu-relative+1": "jeudi prochain", "field-fri-short-relative+-1": "ven. dernier", "field-thu-relative+-1": "jeudi dernier", "field-week": "semaine", "quarters-format-wide": [ "1er trimestre", "2e trimestre", "3e trimestre", "4e trimestre" ], "dateFormatItem-Ed": "E d", "field-wed-narrow-relative+0": "ce mer.", "field-wed-narrow-relative+1": "mer. prochain", "field-quarter-narrow-relative+-1": "trim. dern.", "field-year-short-relative+0": "cette année", "field-dayperiod-short": "cadran", "dateFormatItem-yyyyMMM": "MMM y G", "field-year-short-relative+1": "l’année prochaine", "field-fri-short-relative+0": "ce ven.", "field-fri-short-relative+1": "ven. prochain", "days-standAlone-short": [ "di", "lu", "ma", "me", "je", "ve", "sa" ], "field-week-short-relative+-1": "la semaine dernière", "field-hour-narrow-relative+0": "cette h", "dateFormatItem-yyyyQQQQ": "QQQQ y G", "field-hour-short": "h", "field-zone-short": "fuseau horaire", "quarters-format-abbr": [ "T1", "T2", "T3", "T4" ], "field-month-narrow": "m.", "field-hour-narrow": "h", "field-fri-narrow-relative+-1": "ven. dernier", "field-year-relative+0": "cette année", "field-year-relative+1": "l’année prochaine", "field-era-narrow": "ère", "field-fri-relative+-1": "vendredi dernier", "eraNarrow": "EB", "field-tue-short-relative+-1": "mar. dernier", "field-minute-narrow": "min", "days-format-wide": [ "dimanche", "lundi", "mardi", "mercredi", "jeudi", "vendredi", "samedi" ], "field-mon-narrow-relative+0": "ce lun.", "field-mon-narrow-relative+1": "lun. prochain", "field-year-short-relative+-1": "l’année dernière", "field-zone": "fuseau horaire", "dateFormatItem-MMMEd": "E d MMM", "field-weekOfMonth-narrow": "sem. (m.)", "field-weekday-narrow": "j (sem.)", "field-quarter-narrow": "trim.", "field-sun-short-relative+-1": "dim. dernier", "field-day-relative+-1": "hier", "field-day-relative+-2": "avant-hier", "field-weekday-short": "j (sem.)", "days-format-abbr": [ "dim.", "lun.", "mar.", "mer.", "jeu.", "ven.", "sam." ], "field-sun-relative+0": "ce dimanche", "field-sun-relative+1": "dimanche prochain", "dateFormatItem-Gy": "y G", "field-day-short": "j", "field-week-narrow": "sem.", "field-era": "ère", "field-fri-narrow-relative+0": "ce ven.", "field-fri-narrow-relative+1": "ven. prochain" } //end v1.x content );
/**************************************************************************** Copyright (c) 2013-2014 Chukong Technologies Inc. http://www.cocos2d-x.org 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. ****************************************************************************/ // ----------------------------------- LabelTTF WebGL render cmd ---------------------------- (function() { cc.LabelTTF.WebGLRenderCmd = function (renderable) { cc.Sprite.WebGLRenderCmd.call(this, renderable); cc.LabelTTF.RenderCmd.call(this); this.setShaderProgram(cc.shaderCache.programForKey(cc.LabelTTF._SHADER_PROGRAM)); }; var proto = cc.LabelTTF.WebGLRenderCmd.prototype = Object.create(cc.Sprite.WebGLRenderCmd.prototype); cc.inject(cc.LabelTTF.RenderCmd.prototype, proto); //multi-inherit proto.constructor = cc.LabelTTF.WebGLRenderCmd; proto._setColorsString = function () { this.setDirtyFlag(cc.Node._dirtyFlags.textDirty); var node = this._node; var locStrokeColor = node._strokeColor, locFontFillColor = node._textFillColor; this._shadowColorStr = "rgba(128,128,128," + node._shadowOpacity + ")"; this._fillColorStr = "rgba(" + (0 | locFontFillColor.r) + "," + (0 | locFontFillColor.g) + "," + (0 | locFontFillColor.b) + ", 1)"; this._strokeColorStr = "rgba(" + (0 | locStrokeColor.r) + "," + (0 | locStrokeColor.g) + "," + (0 | locStrokeColor.b) + ", 1)"; }; proto._syncStatus = function (parentCmd) { var flags = cc.Node._dirtyFlags, locFlag = this._dirtyFlag; var parentNode = parentCmd ? parentCmd._node : null; if(parentNode && parentNode._cascadeColorEnabled && (parentCmd._dirtyFlag & flags.colorDirty)) locFlag |= flags.colorDirty; if(parentNode && parentNode._cascadeOpacityEnabled && (parentCmd._dirtyFlag & flags.opacityDirty)) locFlag |= flags.opacityDirty; if(parentCmd && (parentCmd._dirtyFlag & flags.transformDirty)) locFlag |= flags.transformDirty; var colorDirty = locFlag & flags.colorDirty, opacityDirty = locFlag & flags.opacityDirty; this._dirtyFlag = locFlag; if (colorDirty) this._syncDisplayColor(); if (opacityDirty) this._syncDisplayOpacity(); if(colorDirty || opacityDirty){ this._setColorsString(); this._updateColor(); this._updateTexture(); }else if(locFlag & flags.textDirty) this._updateTexture(); this.transform(parentCmd); }; })();
yepnope([ // Libs '../lib/bean-min.js', '../lib/underscore-min.js', { test : (navigator.appVersion.indexOf("MSIE") != -1 && parseFloat(navigator.appVersion.split("MSIE")[1]) < 9), // Load for IE < 9 yep : [ '../lib/excanvas.js', '../lib/base64.js', '../lib/canvastext.js' ] }, 'lib/codemirror/lib/codemirror.js', 'lib/codemirror/mode/javascript/javascript.js', 'lib/beautify.js', 'lib/randomseed.js', 'lib/jquery-1.7.1.min.js', 'lib/jquery.ba-hashchange.min.js', // Flotr '../js/Flotr.js', '../js/DefaultOptions.js', '../js/Color.js', '../js/Date.js', '../js/DOM.js', '../js/EventAdapter.js', '../js/Text.js', '../js/Graph.js', '../js/Axis.js', '../js/Series.js', '../js/types/lines.js', '../js/types/bars.js', '../js/types/points.js', '../js/types/pie.js', '../js/types/candles.js', '../js/types/markers.js', '../js/types/radar.js', '../js/types/bubbles.js', '../js/types/gantt.js', '../js/types/timeline.js', '../js/plugins/download.js', '../js/plugins/selection.js', '../js/plugins/spreadsheet.js', '../js/plugins/grid.js', '../js/plugins/hit.js', '../js/plugins/crosshair.js', '../js/plugins/labels.js', '../js/plugins/legend.js', '../js/plugins/titles.js', // Examples 'js/Examples.js', 'js/ExampleList.js', 'js/Example.js', 'js/Editor.js', 'js/Profile.js', 'js/examples/basic.js', 'js/examples/basic-axis.js', 'js/examples/basic-bars.js', 'js/examples/basic-bars-stacked.js', 'js/examples/basic-pie.js', 'js/examples/basic-radar.js', 'js/examples/basic-bubble.js', 'js/examples/basic-candle.js', 'js/examples/basic-candle-barchart.js', 'js/examples/basic-legend.js', 'js/examples/mouse-tracking.js', 'js/examples/mouse-zoom.js', 'js/examples/mouse-drag.js', 'js/examples/basic-time.js', 'js/examples/negative-values.js', 'js/examples/click-example.js', 'js/examples/download-image.js', 'js/examples/download-data.js', 'js/examples/advanced-titles.js', 'js/examples/color-gradients.js', 'js/examples/profile-bars.js', 'js/examples/basic-timeline.js', 'js/examples/advanced-markers.js', { complete : function () { if (Flotr.ExamplesCallback) { Flotr.ExamplesCallback(); } else { Examples = new Flotr.Examples({ node : document.getElementById('examples') }); } } } ]);
!function(){if(jQuery&&jQuery.fn&&jQuery.fn.select2&&jQuery.fn.select2.amd)var n=jQuery.fn.select2.amd;n.define("select2/i18n/ko",[],function(){return{errorLoading:function(){return"결과를 불러올 수 없습니다."},inputTooLong:function(n){return"너무 깁니다. "+(n.input.length-n.maximum)+" 글자 지워주세요."},inputTooShort:function(n){return"너무 짧습니다. "+(n.minimum-n.input.length)+" 글자 더 입력해주세요."},loadingMore:function(){return"불러오는 중…"},maximumSelected:function(n){return"최대 "+n.maximum+"개까지만 선택 가능합니다."},noResults:function(){return"결과가 없습니다."},searching:function(){return"검색 중…"}}}),n.define,n.require}();
function excluded() { return null; }
/** * @author Mat Groves http://matgroves.com/ @Doormat23 */ PIXI.blendModes = {}; PIXI.blendModes.NORMAL = 0; PIXI.blendModes.SCREEN = 1; /** @class Sprite @extends DisplayObjectContainer @constructor @param texture {Texture} @type String */ PIXI.Sprite = function(texture) { PIXI.DisplayObjectContainer.call( this ); /** * The anchor sets the origin point of the texture. * The default is 0,0 this means the textures origin is the top left * Setting than anchor to 0.5,0.5 means the textures origin is centered * Setting the anchor to 1,1 would mean the textures origin points will be the bottom right * @property anchor * @type Point */ this.anchor = new PIXI.Point(); /** * The texture that the sprite is using * @property texture * @type Texture */ this.texture = texture; /** * The blend mode of sprite. * currently supports PIXI.blendModes.NORMAL and PIXI.blendModes.SCREEN * @property blendMode * @type uint */ this.blendMode = PIXI.blendModes.NORMAL; /** * The width of the sprite (this is initially set by the texture) * @property width * @type #Number */ this.width = 0; /** * The height of the sprite (this is initially set by the texture) * @property height * @type #Number */ this.height = 0; if(texture.baseTexture.hasLoaded) { this.width = this.texture.frame.width; this.height = this.texture.frame.height; this.updateFrame = true; } else { this.onTextureUpdateBind = this.onTextureUpdate.bind(this); this.texture.addEventListener( 'update', this.onTextureUpdateBind ); } this.renderable = true; // thi next bit is here for the docs... } // constructor PIXI.Sprite.constructor = PIXI.Sprite; PIXI.Sprite.prototype = Object.create( PIXI.DisplayObjectContainer.prototype ); /** @method setTexture @param texture {Texture} The PIXI texture that is displayed by the sprite */ PIXI.Sprite.prototype.setTexture = function(texture) { // stop current texture; if(this.texture.baseTexture != texture.baseTexture) { this.textureChange = true; } this.texture = texture; this.width = texture.frame.width; this.height = texture.frame.height; this.updateFrame = true; } /** * @private */ PIXI.Sprite.prototype.onTextureUpdate = function(event) { this.width = this.width || this.texture.frame.width; this.height = this.height || this.texture.frame.height; this.updateFrame = true; } // some helper functions.. /** * * Helper function that creates a sprite that will contain a texture from the TextureCache based on the frameId * The frame ids are created when a Texture packer file has been loaded * @method fromFrame * @static * @param frameId {String} The frame Id of the texture in the cache * @return {Sprite} A new Sprite using a texture from the texture cache matching the frameId */ PIXI.Sprite.fromFrame = function(frameId) { var texture = PIXI.TextureCache[frameId]; if(!texture)throw new Error("The frameId '"+ frameId +"' does not exist in the texture cache" + this); return new PIXI.Sprite(texture); } /** * * Helper function that creates a sprite that will contain a texture based on an image url * If the image is not in the texture cache it will be loaded * @method fromImage * @static * @param The image url of the texture * @return {Sprite} A new Sprite using a texture from the texture cache matching the image id */ PIXI.Sprite.fromImage = function(imageId) { var texture = PIXI.Texture.fromImage(imageId); return new PIXI.Sprite(texture); }
/*! * grunt-jslint * https://github.com/stephenmathieson/grunt-jslint * * Copyright (c) 2013 Stephen Mathieson * Licensed under the WTFPL license. */ 'use strict'; var jslint = require('..'); var pkg = require('../package.json'); /** * Register the `jslint` task * * @api private * @param {Object} grunt */ var gruntJSLint = module.exports = function (grunt) { grunt.registerMultiTask('jslint', 'Validate JavaScript files with JSLint', function () { var next = this.async(); if (grunt.config('jslint.files') || grunt.config('jslint.options')) { // single-task is deprecated return (function deprecation() { var err = new Error([ 'grunt-jslint\'s interface has changed', 'since 0.2.x;', 'see ' + pkg.homepage + ' for update instructions.' ].join(' ')); next(err); }()); } var conf = { files: this.filesSrc, exclude: this.data.exclude || [], options: this.data.options || {}, directives: this.data.directives || {} }; gruntJSLint.task(grunt, conf, next); }); }; /** * The actual jslint `task` * * * @api private * @param {Object} grunt * @param {Object} config * @param {Function} next */ gruntJSLint.task = function (grunt, config, next) { var files = config.files; var excludedFiles = config.exclude; var options = config.options; if (!files || !files.length) { grunt.log.error('NO FILES?!?'); return false; } if (options.failOnError === undefined) { options.failOnError = true; } excludedFiles = grunt.file.expand(excludedFiles); files = grunt.file .expand(files) .filter(function (file) { return excludedFiles.indexOf(file) === -1; }); options.directives = config.directives; jslint.runner(files, options, function (err, report) { var template; if (err) { grunt.log.error(err); return next(false); } if (options.errorsOnly) { template = jslint.reporters.errorsOnly(report); } else { template = jslint.reporters.standard(report); } if (options.log) { grunt.file.write(options.log, grunt.log.uncolor(template)); } if (options.junit) { grunt.file.write(options.junit, jslint.reporters.junit(report)); } if (options.jslintXml) { grunt.file.write(options.jslintXml, jslint.reporters.jslint(report)); } if (options.checkstyle) { grunt.file.write(options.checkstyle, jslint.reporters.checkstyle(report)); } if (grunt.option('no-color')) { template = grunt.log.uncolor(template); } grunt.log.write(template); if (report.failures && options.failOnError) { next(false); } else { next(true); } }); };
(function webpackUniversalModuleDefinition(root, factory) { if(typeof exports === 'object' && typeof module === 'object') module.exports = factory(require("react"), require("react-dom")); else if(typeof define === 'function' && define.amd) define(["react", "react-dom"], factory); else if(typeof exports === 'object') exports["SortableHOC"] = factory(require("react"), require("react-dom")); else root["SortableHOC"] = factory(root["React"], root["ReactDOM"]); })(this, function(__WEBPACK_EXTERNAL_MODULE_112__, __WEBPACK_EXTERNAL_MODULE_113__) { return /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) /******/ return installedModules[moduleId].exports; /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ exports: {}, /******/ id: moduleId, /******/ loaded: false /******/ }; /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ // Flag the module as loaded /******/ module.loaded = true; /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ // Load entry module and return exports /******/ return __webpack_require__(0); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ function(module, exports, __webpack_require__) { module.exports = __webpack_require__(1); /***/ }, /* 1 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.arrayMove = exports.SortableHandle = exports.SortableElement = exports.SortableContainer = undefined; var _utils = __webpack_require__(2); Object.defineProperty(exports, 'arrayMove', { enumerable: true, get: function get() { return _utils.arrayMove; } }); var _SortableContainer2 = __webpack_require__(3); var _SortableContainer3 = _interopRequireDefault(_SortableContainer2); var _SortableElement2 = __webpack_require__(248); var _SortableElement3 = _interopRequireDefault(_SortableElement2); var _SortableHandle2 = __webpack_require__(249); var _SortableHandle3 = _interopRequireDefault(_SortableHandle2); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } exports.SortableContainer = _SortableContainer3.default; exports.SortableElement = _SortableElement3.default; exports.SortableHandle = _SortableHandle3.default; /***/ }, /* 2 */ /***/ function(module, exports) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.arrayMove = arrayMove; exports.closest = closest; exports.limit = limit; exports.getElementMargin = getElementMargin; function arrayMove(arr, previousIndex, newIndex) { var array = arr.slice(0); if (newIndex >= array.length) { var k = newIndex - array.length; while (k-- + 1) { array.push(undefined); } } array.splice(newIndex, 0, array.splice(previousIndex, 1)[0]); return array; } var events = exports.events = { start: ['touchstart', 'mousedown'], move: ['touchmove', 'mousemove'], end: ['touchend', 'mouseup'] }; var vendorPrefix = exports.vendorPrefix = function () { if (typeof window === 'undefined' || typeof document === 'undefined') return ''; // server environment var styles = window.getComputedStyle(document.documentElement, ''); var pre = (Array.prototype.slice.call(styles).join('').match(/-(moz|webkit|ms)-/) || styles.OLink === '' && ['', 'o'])[1]; switch (pre) { case 'ms': return 'ms'; default: return pre && pre.length ? pre[0].toUpperCase() + pre.substr(1) : ''; } }(); function closest(el, fn) { while (el) { if (fn(el)) return el; el = el.parentNode; } } function limit(min, max, value) { if (value < min) { return min; } if (value > max) { return max; } return value; } function getCSSPixelValue(stringValue) { if (stringValue.substr(-2) === 'px') { return parseFloat(stringValue); } return 0; } function getElementMargin(element) { var style = window.getComputedStyle(element); return { top: getCSSPixelValue(style.marginTop), right: getCSSPixelValue(style.marginRight), bottom: getCSSPixelValue(style.marginBottom), left: getCSSPixelValue(style.marginLeft) }; } /***/ }, /* 3 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _extends2 = __webpack_require__(4); var _extends3 = _interopRequireDefault(_extends2); var _slicedToArray2 = __webpack_require__(42); var _slicedToArray3 = _interopRequireDefault(_slicedToArray2); var _toConsumableArray2 = __webpack_require__(68); var _toConsumableArray3 = _interopRequireDefault(_toConsumableArray2); var _getPrototypeOf = __webpack_require__(76); var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf); var _classCallCheck2 = __webpack_require__(80); var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); var _createClass2 = __webpack_require__(81); var _createClass3 = _interopRequireDefault(_createClass2); var _possibleConstructorReturn2 = __webpack_require__(85); var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2); var _inherits2 = __webpack_require__(104); var _inherits3 = _interopRequireDefault(_inherits2); exports.default = SortableContainer; var _react = __webpack_require__(112); var _react2 = _interopRequireDefault(_react); var _reactDom = __webpack_require__(113); var _reactDom2 = _interopRequireDefault(_reactDom); var _Manager = __webpack_require__(114); var _Manager2 = _interopRequireDefault(_Manager); var _utils = __webpack_require__(2); var _invariant = __webpack_require__(246); var _invariant2 = _interopRequireDefault(_invariant); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } // Export Higher Order Sortable Container Component function SortableContainer(WrappedComponent) { var _class, _temp; var config = arguments.length <= 1 || arguments[1] === undefined ? { withRef: false } : arguments[1]; return _temp = _class = function (_Component) { (0, _inherits3.default)(_class, _Component); function _class(props) { (0, _classCallCheck3.default)(this, _class); var _this = (0, _possibleConstructorReturn3.default)(this, (0, _getPrototypeOf2.default)(_class).call(this)); _this.state = {}; _this.handleStart = function (e) { var _this$props = _this.props; var distance = _this$props.distance; var shouldCancelStart = _this$props.shouldCancelStart; if (e.button === 2 || shouldCancelStart(e)) { return false; } _this._touched = true; _this._pos = { x: e.clientX, y: e.clientY }; var node = (0, _utils.closest)(e.target, function (el) { return el.sortableInfo != null; }); if (node && !_this.state.sorting && node.sortableInfo) { var useDragHandle = _this.props.useDragHandle; var _node$sortableInfo = node.sortableInfo; var index = _node$sortableInfo.index; var collection = _node$sortableInfo.collection; if (useDragHandle && !(0, _utils.closest)(e.target, function (el) { return el.sortableHandle != null; })) return; _this.manager.active = { index: index, collection: collection }; if (!distance) { _this.pressTimer = setTimeout(function () { return _this.handlePress(e); }, _this.props.pressDelay); } } }; _this.handleMove = function (e) { var distance = _this.props.distance; if (!_this.state.sorting && _this._touched) { _this._delta = { x: _this._pos.x - e.clientX, y: _this._pos.y - e.clientY }; var delta = Math.abs(_this._delta.x) + Math.abs(_this._delta.y); if (!distance) { _this.cancel(); } else if (delta >= distance) { _this.handlePress(e); } } }; _this.handleEnd = function () { var distance = _this.props.distance; _this._touched = false; if (!distance) { _this.cancel(); } }; _this.cancel = function () { if (!_this.state.sorting) { clearTimeout(_this.pressTimer); _this.manager.active = null; } }; _this.handlePress = function (e) { var active = _this.manager.getActive(); if (active) { var _this$props2 = _this.props; var axis = _this$props2.axis; var onSortStart = _this$props2.onSortStart; var helperClass = _this$props2.helperClass; var hideSortableGhost = _this$props2.hideSortableGhost; var useWindowAsScrollContainer = _this$props2.useWindowAsScrollContainer; var node = active.node; var collection = active.collection; var index = node.sortableInfo.index; var margin = (0, _utils.getElementMargin)(node); var containerBoundingRect = _this.container.getBoundingClientRect(); _this.node = node; _this.margin = margin; _this.width = node.offsetWidth; _this.height = node.offsetHeight; _this.dimension = axis == 'x' ? _this.width : _this.height; _this.marginOffset = { x: _this.margin.left + _this.margin.right, y: Math.max(_this.margin.top, _this.margin.bottom) }; _this.boundingClientRect = node.getBoundingClientRect(); _this.index = index; _this.newIndex = index; var edge = _this.edge = axis == 'x' ? 'Left' : 'Top'; _this.offsetEdge = _this.getEdgeOffset(edge, node); _this.initialOffset = _this.getOffset(e); _this.initialScroll = _this.scrollContainer['scroll' + edge]; _this.helper = _this.document.body.appendChild(node.cloneNode(true)); _this.helper.style.position = 'fixed'; _this.helper.style.top = _this.boundingClientRect.top - margin.top + 'px'; _this.helper.style.left = _this.boundingClientRect.left - margin.left + 'px'; _this.helper.style.width = _this.width + 'px'; _this.helper.style.boxSizing = 'border-box'; if (hideSortableGhost) { _this.sortableGhost = node; node.style.visibility = 'hidden'; } if (axis == 'x') { _this.minTranslate = (useWindowAsScrollContainer ? 0 : containerBoundingRect.left) - _this.boundingClientRect.left - _this.width / 2; _this.maxTranslate = (useWindowAsScrollContainer ? _this.contentWindow.innerWidth : containerBoundingRect.left + containerBoundingRect.width) - _this.boundingClientRect.left - _this.width / 2; } else { _this.minTranslate = (useWindowAsScrollContainer ? 0 : containerBoundingRect.top) - _this.boundingClientRect.top - _this.height / 2; _this.maxTranslate = (useWindowAsScrollContainer ? _this.contentWindow.innerHeight : containerBoundingRect.top + containerBoundingRect.height) - _this.boundingClientRect.top - _this.height / 2; } if (helperClass) { var _this$helper$classLis; (_this$helper$classLis = _this.helper.classList).add.apply(_this$helper$classLis, (0, _toConsumableArray3.default)(helperClass.split(' '))); } _this.listenerNode = e.touches ? node : _this.contentWindow; _utils.events.move.forEach(function (eventName) { return _this.listenerNode.addEventListener(eventName, _this.handleSortMove, false); }); _utils.events.end.forEach(function (eventName) { return _this.listenerNode.addEventListener(eventName, _this.handleSortEnd, false); }); _this.setState({ sorting: true, sortingIndex: index }); if (onSortStart) onSortStart({ node: node, index: index, collection: collection }, e); } }; _this.handleSortMove = function (e) { var onSortMove = _this.props.onSortMove; e.preventDefault(); // Prevent scrolling on mobile _this.updatePosition(e); _this.animateNodes(); _this.autoscroll(); if (onSortMove) onSortMove(e); }; _this.handleSortEnd = function (e) { var _this$props3 = _this.props; var hideSortableGhost = _this$props3.hideSortableGhost; var onSortEnd = _this$props3.onSortEnd; var collection = _this.manager.active.collection; // Remove the event listeners if the node is still in the DOM if (_this.listenerNode) { _utils.events.move.forEach(function (eventName) { return _this.listenerNode.removeEventListener(eventName, _this.handleSortMove); }); _utils.events.end.forEach(function (eventName) { return _this.listenerNode.removeEventListener(eventName, _this.handleSortEnd); }); } // Remove the helper from the DOM _this.helper.parentNode.removeChild(_this.helper); if (hideSortableGhost && _this.sortableGhost) { _this.sortableGhost.style.visibility = ''; } var nodes = _this.manager.refs[collection]; for (var i = 0, len = nodes.length; i < len; i++) { var node = nodes[i]; var el = node.node; // Clear the cached offsetTop / offsetLeft value node.edgeOffset = null; // Remove the transforms / transitions el.style[_utils.vendorPrefix + 'Transform'] = ''; el.style[_utils.vendorPrefix + 'TransitionDuration'] = ''; } if (typeof onSortEnd == 'function') { onSortEnd({ oldIndex: _this.index, newIndex: _this.newIndex, collection: collection }, e); } // Stop autoscroll clearInterval(_this.autoscrollInterval); _this.autoscrollInterval = null; // Update state _this.manager.active = null; _this.setState({ sorting: false, sortingIndex: null }); _this._touched = false; }; _this.autoscroll = function () { var translate = _this.translate; var direction = void 0; var speed = 1; var acceleration = 10; if (translate >= _this.maxTranslate - _this.dimension / 2) { direction = 1; // Scroll Down speed = acceleration * Math.abs((_this.maxTranslate - _this.dimension / 2 - translate) / _this.dimension); } else if (translate <= _this.minTranslate + _this.dimension / 2) { direction = -1; // Scroll Up speed = acceleration * Math.abs((translate - _this.dimension / 2 - _this.minTranslate) / _this.dimension); } if (_this.autoscrollInterval) { clearTimeout(_this.autoscrollInterval); _this.autoscrollInterval = null; _this.isAutoScrolling = false; } if (direction) { _this.autoscrollInterval = setInterval(function () { _this.isAutoScrolling = true; var offset = 1 * speed * direction; _this.scrollContainer['scroll' + _this.edge] += offset; _this.translate += offset; _this.animateNodes(); }, 5); } }; _this.manager = new _Manager2.default(); _this.events = { start: _this.handleStart, move: _this.handleMove, end: _this.handleEnd }; (0, _invariant2.default)(!(props.distance && props.pressDelay), 'Attempted to set both `pressDelay` and `distance` on SortableContainer, you may only use one or the other, not both at the same time.'); return _this; } (0, _createClass3.default)(_class, [{ key: 'getChildContext', value: function getChildContext() { return { manager: this.manager }; } }, { key: 'componentDidMount', value: function componentDidMount() { var _this2 = this; var _props = this.props; var contentWindow = _props.contentWindow; var getContainer = _props.getContainer; this.container = typeof getContainer == 'function' ? getContainer(this.getWrappedInstance()) : _reactDom2.default.findDOMNode(this); this.document = this.container.ownerDocument || document; this.scrollContainer = this.props.useWindowAsScrollContainer ? this.document.body : this.container; this.contentWindow = typeof contentWindow == 'function' ? contentWindow() : contentWindow; var _loop = function _loop(key) { _utils.events[key].forEach(function (eventName) { return _this2.container.addEventListener(eventName, _this2.events[key], false); }); }; for (var key in this.events) { _loop(key); } } }, { key: 'componentWillUnmount', value: function componentWillUnmount() { var _this3 = this; var _loop2 = function _loop2(key) { _utils.events[key].forEach(function (eventName) { return _this3.container.removeEventListener(eventName, _this3.events[key]); }); }; for (var key in this.events) { _loop2(key); } } }, { key: 'getEdgeOffset', value: function getEdgeOffset(edge, node) { var offset = arguments.length <= 2 || arguments[2] === undefined ? 0 : arguments[2]; // Get the actual offsetTop / offsetLeft value, no matter how deep the node is nested if (node) { if (node.parentNode !== this.container) { return this.getEdgeOffset(edge, node.parentNode, offset + node['offset' + edge]); } else { return node['offset' + edge] + offset; } } } }, { key: 'getOffset', value: function getOffset(e) { return { x: e.touches ? e.touches[0].clientX : e.clientX, y: e.touches ? e.touches[0].clientY : e.clientY }; } }, { key: 'getLockPixelOffsets', value: function getLockPixelOffsets() { var lockOffset = this.props.lockOffset; if (!Array.isArray(lockOffset)) { lockOffset = [lockOffset, lockOffset]; } (0, _invariant2.default)(lockOffset.length === 2, 'lockOffset prop of SortableContainer should be a single ' + 'value or an array of exactly two values. Given %s', lockOffset); var _lockOffset = lockOffset; var _lockOffset2 = (0, _slicedToArray3.default)(_lockOffset, 2); var minLockOffset = _lockOffset2[0]; var maxLockOffset = _lockOffset2[1]; return [this.getLockPixelOffset(minLockOffset), this.getLockPixelOffset(maxLockOffset)]; } }, { key: 'getLockPixelOffset', value: function getLockPixelOffset(lockOffset) { var offset = lockOffset; var unit = 'px'; if (typeof lockOffset === 'string') { var match = /^[+-]?\d*(?:\.\d*)?(px|%)$/.exec(lockOffset); (0, _invariant2.default)(match !== null, 'lockOffset value should be a number or a string of a ' + 'number followed by "px" or "%". Given %s', lockOffset); offset = parseFloat(lockOffset); unit = match[1]; } (0, _invariant2.default)(isFinite(offset), 'lockOffset value should be a finite. Given %s', lockOffset); if (unit === '%') { offset = offset * this.dimension / 100; } return offset; } }, { key: 'updatePosition', value: function updatePosition(e) { var _props2 = this.props; var axis = _props2.axis; var lockAxis = _props2.lockAxis; var lockToContainerEdges = _props2.lockToContainerEdges; var offset = this.getOffset(e); var translate = { x: offset.x - this.initialOffset.x, y: offset.y - this.initialOffset.y }; this.translate = translate[axis]; if (lockToContainerEdges) { var _getLockPixelOffsets = this.getLockPixelOffsets(); var _getLockPixelOffsets2 = (0, _slicedToArray3.default)(_getLockPixelOffsets, 2); var minLockOffset = _getLockPixelOffsets2[0]; var maxLockOffset = _getLockPixelOffsets2[1]; var minOffset = this.dimension / 2 - minLockOffset; var maxOffset = this.dimension / 2 - maxLockOffset; translate[axis] = (0, _utils.limit)(this.minTranslate + minOffset, this.maxTranslate - maxOffset, translate[axis]); } switch (lockAxis) { case 'x': translate.y = 0; break; case 'y': translate.x = 0; break; } this.helper.style[_utils.vendorPrefix + 'Transform'] = 'translate3d(' + translate.x + 'px,' + translate.y + 'px, 0)'; } }, { key: 'animateNodes', value: function animateNodes() { var _props3 = this.props; var axis = _props3.axis; var transitionDuration = _props3.transitionDuration; var hideSortableGhost = _props3.hideSortableGhost; var nodes = this.manager.getOrderedRefs(); var deltaScroll = this.scrollContainer['scroll' + this.edge] - this.initialScroll; var sortingOffset = this.offsetEdge + this.translate + deltaScroll; this.newIndex = null; for (var i = 0, len = nodes.length; i < len; i++) { var _nodes$i = nodes[i]; var node = _nodes$i.node; var edgeOffset = _nodes$i.edgeOffset; var index = node.sortableInfo.index; var dimension = axis == 'x' ? node.offsetWidth : node.offsetHeight; var offset = this.dimension > dimension ? dimension / 2 : this.dimension / 2; var translate = 0; var translateX = 0; var translateY = 0; // If we haven't cached the node's offsetTop / offsetLeft value if (edgeOffset == null) { nodes[i].edgeOffset = edgeOffset = this.getEdgeOffset(this.edge, node); } // If the node is the one we're currently animating, skip it if (index === this.index) { if (hideSortableGhost) { /* * With windowing libraries such as `react-virtualized`, the sortableGhost * node may change while scrolling down and then back up (or vice-versa), * so we need to update the reference to the new node just to be safe. */ this.sortableGhost = node; node.style.visibility = 'hidden'; } continue; } if (transitionDuration) { node.style[_utils.vendorPrefix + 'TransitionDuration'] = transitionDuration + 'ms'; } if (index > this.index && sortingOffset + offset >= edgeOffset) { translate = -(this.dimension + this.marginOffset[axis]); this.newIndex = index; } else if (index < this.index && sortingOffset <= edgeOffset + offset) { translate = this.dimension + this.marginOffset[axis]; if (this.newIndex == null) { this.newIndex = index; } } if (axis == 'x') { translateX = translate; } else { translateY = translate; } node.style[_utils.vendorPrefix + 'Transform'] = 'translate3d(' + translateX + 'px,' + translateY + 'px,0)'; } if (this.newIndex == null) { this.newIndex = this.index; } } }, { key: 'getWrappedInstance', value: function getWrappedInstance() { (0, _invariant2.default)(config.withRef, 'To access the wrapped instance, you need to pass in {withRef: true} as the second argument of the SortableContainer() call'); return this.refs.wrappedInstance; } }, { key: 'render', value: function render() { var ref = config.withRef ? 'wrappedInstance' : null; return _react2.default.createElement(WrappedComponent, (0, _extends3.default)({ ref: ref }, this.props, this.state)); } }]); return _class; }(_react.Component), _class.displayName = WrappedComponent.displayName ? 'SortableList(' + WrappedComponent.displayName + ')' : 'SortableList', _class.WrappedComponent = WrappedComponent, _class.defaultProps = { axis: 'y', transitionDuration: 300, pressDelay: 0, distance: 0, useWindowAsScrollContainer: false, hideSortableGhost: true, contentWindow: typeof window !== 'undefined' ? window : null, shouldCancelStart: function shouldCancelStart(e) { // Cancel sorting if the event target is an `input`, `textarea`, `select` or `option` if (['input', 'textarea', 'select', 'option'].indexOf(e.target.tagName.toLowerCase()) !== -1) { return true; // Return true to cancel sorting } }, lockToContainerEdges: false, lockOffset: '50%' }, _class.propTypes = { axis: _react.PropTypes.oneOf(['x', 'y']), distance: _react.PropTypes.number, lockAxis: _react.PropTypes.string, helperClass: _react.PropTypes.string, transitionDuration: _react.PropTypes.number, contentWindow: _react.PropTypes.any, onSortStart: _react.PropTypes.func, onSortMove: _react.PropTypes.func, onSortEnd: _react.PropTypes.func, shouldCancelStart: _react.PropTypes.func, pressDelay: _react.PropTypes.number, useDragHandle: _react.PropTypes.bool, useWindowAsScrollContainer: _react.PropTypes.bool, hideSortableGhost: _react.PropTypes.bool, lockToContainerEdges: _react.PropTypes.bool, lockOffset: _react.PropTypes.oneOfType([_react.PropTypes.number, _react.PropTypes.string, _react.PropTypes.arrayOf(_react.PropTypes.oneOfType([_react.PropTypes.number, _react.PropTypes.string]))]), getContainer: _react.PropTypes.func }, _class.childContextTypes = { manager: _react.PropTypes.object.isRequired }, _temp; } /***/ }, /* 4 */ /***/ function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; var _assign = __webpack_require__(5); var _assign2 = _interopRequireDefault(_assign); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } exports.default = _assign2.default || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; /***/ }, /* 5 */ /***/ function(module, exports, __webpack_require__) { module.exports = { "default": __webpack_require__(6), __esModule: true }; /***/ }, /* 6 */ /***/ function(module, exports, __webpack_require__) { __webpack_require__(7); module.exports = __webpack_require__(10).Object.assign; /***/ }, /* 7 */ /***/ function(module, exports, __webpack_require__) { // 19.1.3.1 Object.assign(target, source) var $export = __webpack_require__(8); $export($export.S + $export.F, 'Object', {assign: __webpack_require__(23)}); /***/ }, /* 8 */ /***/ function(module, exports, __webpack_require__) { var global = __webpack_require__(9) , core = __webpack_require__(10) , ctx = __webpack_require__(11) , hide = __webpack_require__(13) , PROTOTYPE = 'prototype'; var $export = function(type, name, source){ var IS_FORCED = type & $export.F , IS_GLOBAL = type & $export.G , IS_STATIC = type & $export.S , IS_PROTO = type & $export.P , IS_BIND = type & $export.B , IS_WRAP = type & $export.W , exports = IS_GLOBAL ? core : core[name] || (core[name] = {}) , expProto = exports[PROTOTYPE] , target = IS_GLOBAL ? global : IS_STATIC ? global[name] : (global[name] || {})[PROTOTYPE] , key, own, out; if(IS_GLOBAL)source = name; for(key in source){ // contains in native own = !IS_FORCED && target && target[key] !== undefined; if(own && key in exports)continue; // export native or passed out = own ? target[key] : source[key]; // prevent global pollution for namespaces exports[key] = IS_GLOBAL && typeof target[key] != 'function' ? source[key] // bind timers to global for call from export context : IS_BIND && own ? ctx(out, global) // wrap global constructors for prevent change them in library : IS_WRAP && target[key] == out ? (function(C){ var F = function(a, b, c){ if(this instanceof C){ switch(arguments.length){ case 0: return new C; case 1: return new C(a); case 2: return new C(a, b); } return new C(a, b, c); } return C.apply(this, arguments); }; F[PROTOTYPE] = C[PROTOTYPE]; return F; // make static versions for prototype methods })(out) : IS_PROTO && typeof out == 'function' ? ctx(Function.call, out) : out; // export proto methods to core.%CONSTRUCTOR%.methods.%NAME% if(IS_PROTO){ (exports.virtual || (exports.virtual = {}))[key] = out; // export proto methods to core.%CONSTRUCTOR%.prototype.%NAME% if(type & $export.R && expProto && !expProto[key])hide(expProto, key, out); } } }; // type bitmap $export.F = 1; // forced $export.G = 2; // global $export.S = 4; // static $export.P = 8; // proto $export.B = 16; // bind $export.W = 32; // wrap $export.U = 64; // safe $export.R = 128; // real proto method for `library` module.exports = $export; /***/ }, /* 9 */ /***/ function(module, exports) { // https://github.com/zloirock/core-js/issues/86#issuecomment-115759028 var global = module.exports = typeof window != 'undefined' && window.Math == Math ? window : typeof self != 'undefined' && self.Math == Math ? self : Function('return this')(); if(typeof __g == 'number')__g = global; // eslint-disable-line no-undef /***/ }, /* 10 */ /***/ function(module, exports) { var core = module.exports = {version: '2.4.0'}; if(typeof __e == 'number')__e = core; // eslint-disable-line no-undef /***/ }, /* 11 */ /***/ function(module, exports, __webpack_require__) { // optional / simple context binding var aFunction = __webpack_require__(12); module.exports = function(fn, that, length){ aFunction(fn); if(that === undefined)return fn; switch(length){ case 1: return function(a){ return fn.call(that, a); }; case 2: return function(a, b){ return fn.call(that, a, b); }; case 3: return function(a, b, c){ return fn.call(that, a, b, c); }; } return function(/* ...args */){ return fn.apply(that, arguments); }; }; /***/ }, /* 12 */ /***/ function(module, exports) { module.exports = function(it){ if(typeof it != 'function')throw TypeError(it + ' is not a function!'); return it; }; /***/ }, /* 13 */ /***/ function(module, exports, __webpack_require__) { var dP = __webpack_require__(14) , createDesc = __webpack_require__(22); module.exports = __webpack_require__(18) ? function(object, key, value){ return dP.f(object, key, createDesc(1, value)); } : function(object, key, value){ object[key] = value; return object; }; /***/ }, /* 14 */ /***/ function(module, exports, __webpack_require__) { var anObject = __webpack_require__(15) , IE8_DOM_DEFINE = __webpack_require__(17) , toPrimitive = __webpack_require__(21) , dP = Object.defineProperty; exports.f = __webpack_require__(18) ? Object.defineProperty : function defineProperty(O, P, Attributes){ anObject(O); P = toPrimitive(P, true); anObject(Attributes); if(IE8_DOM_DEFINE)try { return dP(O, P, Attributes); } catch(e){ /* empty */ } if('get' in Attributes || 'set' in Attributes)throw TypeError('Accessors not supported!'); if('value' in Attributes)O[P] = Attributes.value; return O; }; /***/ }, /* 15 */ /***/ function(module, exports, __webpack_require__) { var isObject = __webpack_require__(16); module.exports = function(it){ if(!isObject(it))throw TypeError(it + ' is not an object!'); return it; }; /***/ }, /* 16 */ /***/ function(module, exports) { module.exports = function(it){ return typeof it === 'object' ? it !== null : typeof it === 'function'; }; /***/ }, /* 17 */ /***/ function(module, exports, __webpack_require__) { module.exports = !__webpack_require__(18) && !__webpack_require__(19)(function(){ return Object.defineProperty(__webpack_require__(20)('div'), 'a', {get: function(){ return 7; }}).a != 7; }); /***/ }, /* 18 */ /***/ function(module, exports, __webpack_require__) { // Thank's IE8 for his funny defineProperty module.exports = !__webpack_require__(19)(function(){ return Object.defineProperty({}, 'a', {get: function(){ return 7; }}).a != 7; }); /***/ }, /* 19 */ /***/ function(module, exports) { module.exports = function(exec){ try { return !!exec(); } catch(e){ return true; } }; /***/ }, /* 20 */ /***/ function(module, exports, __webpack_require__) { var isObject = __webpack_require__(16) , document = __webpack_require__(9).document // in old IE typeof document.createElement is 'object' , is = isObject(document) && isObject(document.createElement); module.exports = function(it){ return is ? document.createElement(it) : {}; }; /***/ }, /* 21 */ /***/ function(module, exports, __webpack_require__) { // 7.1.1 ToPrimitive(input [, PreferredType]) var isObject = __webpack_require__(16); // instead of the ES6 spec version, we didn't implement @@toPrimitive case // and the second argument - flag - preferred type is a string module.exports = function(it, S){ if(!isObject(it))return it; var fn, val; if(S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it)))return val; if(typeof (fn = it.valueOf) == 'function' && !isObject(val = fn.call(it)))return val; if(!S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it)))return val; throw TypeError("Can't convert object to primitive value"); }; /***/ }, /* 22 */ /***/ function(module, exports) { module.exports = function(bitmap, value){ return { enumerable : !(bitmap & 1), configurable: !(bitmap & 2), writable : !(bitmap & 4), value : value }; }; /***/ }, /* 23 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; // 19.1.2.1 Object.assign(target, source, ...) var getKeys = __webpack_require__(24) , gOPS = __webpack_require__(39) , pIE = __webpack_require__(40) , toObject = __webpack_require__(41) , IObject = __webpack_require__(28) , $assign = Object.assign; // should work with symbols and should have deterministic property order (V8 bug) module.exports = !$assign || __webpack_require__(19)(function(){ var A = {} , B = {} , S = Symbol() , K = 'abcdefghijklmnopqrst'; A[S] = 7; K.split('').forEach(function(k){ B[k] = k; }); return $assign({}, A)[S] != 7 || Object.keys($assign({}, B)).join('') != K; }) ? function assign(target, source){ // eslint-disable-line no-unused-vars var T = toObject(target) , aLen = arguments.length , index = 1 , getSymbols = gOPS.f , isEnum = pIE.f; while(aLen > index){ var S = IObject(arguments[index++]) , keys = getSymbols ? getKeys(S).concat(getSymbols(S)) : getKeys(S) , length = keys.length , j = 0 , key; while(length > j)if(isEnum.call(S, key = keys[j++]))T[key] = S[key]; } return T; } : $assign; /***/ }, /* 24 */ /***/ function(module, exports, __webpack_require__) { // 19.1.2.14 / 15.2.3.14 Object.keys(O) var $keys = __webpack_require__(25) , enumBugKeys = __webpack_require__(38); module.exports = Object.keys || function keys(O){ return $keys(O, enumBugKeys); }; /***/ }, /* 25 */ /***/ function(module, exports, __webpack_require__) { var has = __webpack_require__(26) , toIObject = __webpack_require__(27) , arrayIndexOf = __webpack_require__(31)(false) , IE_PROTO = __webpack_require__(35)('IE_PROTO'); module.exports = function(object, names){ var O = toIObject(object) , i = 0 , result = [] , key; for(key in O)if(key != IE_PROTO)has(O, key) && result.push(key); // Don't enum bug & hidden keys while(names.length > i)if(has(O, key = names[i++])){ ~arrayIndexOf(result, key) || result.push(key); } return result; }; /***/ }, /* 26 */ /***/ function(module, exports) { var hasOwnProperty = {}.hasOwnProperty; module.exports = function(it, key){ return hasOwnProperty.call(it, key); }; /***/ }, /* 27 */ /***/ function(module, exports, __webpack_require__) { // to indexed object, toObject with fallback for non-array-like ES3 strings var IObject = __webpack_require__(28) , defined = __webpack_require__(30); module.exports = function(it){ return IObject(defined(it)); }; /***/ }, /* 28 */ /***/ function(module, exports, __webpack_require__) { // fallback for non-array-like ES3 and non-enumerable old V8 strings var cof = __webpack_require__(29); module.exports = Object('z').propertyIsEnumerable(0) ? Object : function(it){ return cof(it) == 'String' ? it.split('') : Object(it); }; /***/ }, /* 29 */ /***/ function(module, exports) { var toString = {}.toString; module.exports = function(it){ return toString.call(it).slice(8, -1); }; /***/ }, /* 30 */ /***/ function(module, exports) { // 7.2.1 RequireObjectCoercible(argument) module.exports = function(it){ if(it == undefined)throw TypeError("Can't call method on " + it); return it; }; /***/ }, /* 31 */ /***/ function(module, exports, __webpack_require__) { // false -> Array#indexOf // true -> Array#includes var toIObject = __webpack_require__(27) , toLength = __webpack_require__(32) , toIndex = __webpack_require__(34); module.exports = function(IS_INCLUDES){ return function($this, el, fromIndex){ var O = toIObject($this) , length = toLength(O.length) , index = toIndex(fromIndex, length) , value; // Array#includes uses SameValueZero equality algorithm if(IS_INCLUDES && el != el)while(length > index){ value = O[index++]; if(value != value)return true; // Array#toIndex ignores holes, Array#includes - not } else for(;length > index; index++)if(IS_INCLUDES || index in O){ if(O[index] === el)return IS_INCLUDES || index || 0; } return !IS_INCLUDES && -1; }; }; /***/ }, /* 32 */ /***/ function(module, exports, __webpack_require__) { // 7.1.15 ToLength var toInteger = __webpack_require__(33) , min = Math.min; module.exports = function(it){ return it > 0 ? min(toInteger(it), 0x1fffffffffffff) : 0; // pow(2, 53) - 1 == 9007199254740991 }; /***/ }, /* 33 */ /***/ function(module, exports) { // 7.1.4 ToInteger var ceil = Math.ceil , floor = Math.floor; module.exports = function(it){ return isNaN(it = +it) ? 0 : (it > 0 ? floor : ceil)(it); }; /***/ }, /* 34 */ /***/ function(module, exports, __webpack_require__) { var toInteger = __webpack_require__(33) , max = Math.max , min = Math.min; module.exports = function(index, length){ index = toInteger(index); return index < 0 ? max(index + length, 0) : min(index, length); }; /***/ }, /* 35 */ /***/ function(module, exports, __webpack_require__) { var shared = __webpack_require__(36)('keys') , uid = __webpack_require__(37); module.exports = function(key){ return shared[key] || (shared[key] = uid(key)); }; /***/ }, /* 36 */ /***/ function(module, exports, __webpack_require__) { var global = __webpack_require__(9) , SHARED = '__core-js_shared__' , store = global[SHARED] || (global[SHARED] = {}); module.exports = function(key){ return store[key] || (store[key] = {}); }; /***/ }, /* 37 */ /***/ function(module, exports) { var id = 0 , px = Math.random(); module.exports = function(key){ return 'Symbol('.concat(key === undefined ? '' : key, ')_', (++id + px).toString(36)); }; /***/ }, /* 38 */ /***/ function(module, exports) { // IE 8- don't enum bug keys module.exports = ( 'constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf' ).split(','); /***/ }, /* 39 */ /***/ function(module, exports) { exports.f = Object.getOwnPropertySymbols; /***/ }, /* 40 */ /***/ function(module, exports) { exports.f = {}.propertyIsEnumerable; /***/ }, /* 41 */ /***/ function(module, exports, __webpack_require__) { // 7.1.13 ToObject(argument) var defined = __webpack_require__(30); module.exports = function(it){ return Object(defined(it)); }; /***/ }, /* 42 */ /***/ function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; var _isIterable2 = __webpack_require__(43); var _isIterable3 = _interopRequireDefault(_isIterable2); var _getIterator2 = __webpack_require__(64); var _getIterator3 = _interopRequireDefault(_getIterator2); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } exports.default = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = (0, _getIterator3.default)(arr), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if ((0, _isIterable3.default)(Object(arr))) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }(); /***/ }, /* 43 */ /***/ function(module, exports, __webpack_require__) { module.exports = { "default": __webpack_require__(44), __esModule: true }; /***/ }, /* 44 */ /***/ function(module, exports, __webpack_require__) { __webpack_require__(45); __webpack_require__(60); module.exports = __webpack_require__(62); /***/ }, /* 45 */ /***/ function(module, exports, __webpack_require__) { __webpack_require__(46); var global = __webpack_require__(9) , hide = __webpack_require__(13) , Iterators = __webpack_require__(49) , TO_STRING_TAG = __webpack_require__(58)('toStringTag'); for(var collections = ['NodeList', 'DOMTokenList', 'MediaList', 'StyleSheetList', 'CSSRuleList'], i = 0; i < 5; i++){ var NAME = collections[i] , Collection = global[NAME] , proto = Collection && Collection.prototype; if(proto && !proto[TO_STRING_TAG])hide(proto, TO_STRING_TAG, NAME); Iterators[NAME] = Iterators.Array; } /***/ }, /* 46 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var addToUnscopables = __webpack_require__(47) , step = __webpack_require__(48) , Iterators = __webpack_require__(49) , toIObject = __webpack_require__(27); // 22.1.3.4 Array.prototype.entries() // 22.1.3.13 Array.prototype.keys() // 22.1.3.29 Array.prototype.values() // 22.1.3.30 Array.prototype[@@iterator]() module.exports = __webpack_require__(50)(Array, 'Array', function(iterated, kind){ this._t = toIObject(iterated); // target this._i = 0; // next index this._k = kind; // kind // 22.1.5.2.1 %ArrayIteratorPrototype%.next() }, function(){ var O = this._t , kind = this._k , index = this._i++; if(!O || index >= O.length){ this._t = undefined; return step(1); } if(kind == 'keys' )return step(0, index); if(kind == 'values')return step(0, O[index]); return step(0, [index, O[index]]); }, 'values'); // argumentsList[@@iterator] is %ArrayProto_values% (9.4.4.6, 9.4.4.7) Iterators.Arguments = Iterators.Array; addToUnscopables('keys'); addToUnscopables('values'); addToUnscopables('entries'); /***/ }, /* 47 */ /***/ function(module, exports) { module.exports = function(){ /* empty */ }; /***/ }, /* 48 */ /***/ function(module, exports) { module.exports = function(done, value){ return {value: value, done: !!done}; }; /***/ }, /* 49 */ /***/ function(module, exports) { module.exports = {}; /***/ }, /* 50 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var LIBRARY = __webpack_require__(51) , $export = __webpack_require__(8) , redefine = __webpack_require__(52) , hide = __webpack_require__(13) , has = __webpack_require__(26) , Iterators = __webpack_require__(49) , $iterCreate = __webpack_require__(53) , setToStringTag = __webpack_require__(57) , getPrototypeOf = __webpack_require__(59) , ITERATOR = __webpack_require__(58)('iterator') , BUGGY = !([].keys && 'next' in [].keys()) // Safari has buggy iterators w/o `next` , FF_ITERATOR = '@@iterator' , KEYS = 'keys' , VALUES = 'values'; var returnThis = function(){ return this; }; module.exports = function(Base, NAME, Constructor, next, DEFAULT, IS_SET, FORCED){ $iterCreate(Constructor, NAME, next); var getMethod = function(kind){ if(!BUGGY && kind in proto)return proto[kind]; switch(kind){ case KEYS: return function keys(){ return new Constructor(this, kind); }; case VALUES: return function values(){ return new Constructor(this, kind); }; } return function entries(){ return new Constructor(this, kind); }; }; var TAG = NAME + ' Iterator' , DEF_VALUES = DEFAULT == VALUES , VALUES_BUG = false , proto = Base.prototype , $native = proto[ITERATOR] || proto[FF_ITERATOR] || DEFAULT && proto[DEFAULT] , $default = $native || getMethod(DEFAULT) , $entries = DEFAULT ? !DEF_VALUES ? $default : getMethod('entries') : undefined , $anyNative = NAME == 'Array' ? proto.entries || $native : $native , methods, key, IteratorPrototype; // Fix native if($anyNative){ IteratorPrototype = getPrototypeOf($anyNative.call(new Base)); if(IteratorPrototype !== Object.prototype){ // Set @@toStringTag to native iterators setToStringTag(IteratorPrototype, TAG, true); // fix for some old engines if(!LIBRARY && !has(IteratorPrototype, ITERATOR))hide(IteratorPrototype, ITERATOR, returnThis); } } // fix Array#{values, @@iterator}.name in V8 / FF if(DEF_VALUES && $native && $native.name !== VALUES){ VALUES_BUG = true; $default = function values(){ return $native.call(this); }; } // Define iterator if((!LIBRARY || FORCED) && (BUGGY || VALUES_BUG || !proto[ITERATOR])){ hide(proto, ITERATOR, $default); } // Plug for library Iterators[NAME] = $default; Iterators[TAG] = returnThis; if(DEFAULT){ methods = { values: DEF_VALUES ? $default : getMethod(VALUES), keys: IS_SET ? $default : getMethod(KEYS), entries: $entries }; if(FORCED)for(key in methods){ if(!(key in proto))redefine(proto, key, methods[key]); } else $export($export.P + $export.F * (BUGGY || VALUES_BUG), NAME, methods); } return methods; }; /***/ }, /* 51 */ /***/ function(module, exports) { module.exports = true; /***/ }, /* 52 */ /***/ function(module, exports, __webpack_require__) { module.exports = __webpack_require__(13); /***/ }, /* 53 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var create = __webpack_require__(54) , descriptor = __webpack_require__(22) , setToStringTag = __webpack_require__(57) , IteratorPrototype = {}; // 25.1.2.1.1 %IteratorPrototype%[@@iterator]() __webpack_require__(13)(IteratorPrototype, __webpack_require__(58)('iterator'), function(){ return this; }); module.exports = function(Constructor, NAME, next){ Constructor.prototype = create(IteratorPrototype, {next: descriptor(1, next)}); setToStringTag(Constructor, NAME + ' Iterator'); }; /***/ }, /* 54 */ /***/ function(module, exports, __webpack_require__) { // 19.1.2.2 / 15.2.3.5 Object.create(O [, Properties]) var anObject = __webpack_require__(15) , dPs = __webpack_require__(55) , enumBugKeys = __webpack_require__(38) , IE_PROTO = __webpack_require__(35)('IE_PROTO') , Empty = function(){ /* empty */ } , PROTOTYPE = 'prototype'; // Create object with fake `null` prototype: use iframe Object with cleared prototype var createDict = function(){ // Thrash, waste and sodomy: IE GC bug var iframe = __webpack_require__(20)('iframe') , i = enumBugKeys.length , gt = '>' , iframeDocument; iframe.style.display = 'none'; __webpack_require__(56).appendChild(iframe); iframe.src = 'javascript:'; // eslint-disable-line no-script-url // createDict = iframe.contentWindow.Object; // html.removeChild(iframe); iframeDocument = iframe.contentWindow.document; iframeDocument.open(); iframeDocument.write('<script>document.F=Object</script' + gt); iframeDocument.close(); createDict = iframeDocument.F; while(i--)delete createDict[PROTOTYPE][enumBugKeys[i]]; return createDict(); }; module.exports = Object.create || function create(O, Properties){ var result; if(O !== null){ Empty[PROTOTYPE] = anObject(O); result = new Empty; Empty[PROTOTYPE] = null; // add "__proto__" for Object.getPrototypeOf polyfill result[IE_PROTO] = O; } else result = createDict(); return Properties === undefined ? result : dPs(result, Properties); }; /***/ }, /* 55 */ /***/ function(module, exports, __webpack_require__) { var dP = __webpack_require__(14) , anObject = __webpack_require__(15) , getKeys = __webpack_require__(24); module.exports = __webpack_require__(18) ? Object.defineProperties : function defineProperties(O, Properties){ anObject(O); var keys = getKeys(Properties) , length = keys.length , i = 0 , P; while(length > i)dP.f(O, P = keys[i++], Properties[P]); return O; }; /***/ }, /* 56 */ /***/ function(module, exports, __webpack_require__) { module.exports = __webpack_require__(9).document && document.documentElement; /***/ }, /* 57 */ /***/ function(module, exports, __webpack_require__) { var def = __webpack_require__(14).f , has = __webpack_require__(26) , TAG = __webpack_require__(58)('toStringTag'); module.exports = function(it, tag, stat){ if(it && !has(it = stat ? it : it.prototype, TAG))def(it, TAG, {configurable: true, value: tag}); }; /***/ }, /* 58 */ /***/ function(module, exports, __webpack_require__) { var store = __webpack_require__(36)('wks') , uid = __webpack_require__(37) , Symbol = __webpack_require__(9).Symbol , USE_SYMBOL = typeof Symbol == 'function'; var $exports = module.exports = function(name){ return store[name] || (store[name] = USE_SYMBOL && Symbol[name] || (USE_SYMBOL ? Symbol : uid)('Symbol.' + name)); }; $exports.store = store; /***/ }, /* 59 */ /***/ function(module, exports, __webpack_require__) { // 19.1.2.9 / 15.2.3.2 Object.getPrototypeOf(O) var has = __webpack_require__(26) , toObject = __webpack_require__(41) , IE_PROTO = __webpack_require__(35)('IE_PROTO') , ObjectProto = Object.prototype; module.exports = Object.getPrototypeOf || function(O){ O = toObject(O); if(has(O, IE_PROTO))return O[IE_PROTO]; if(typeof O.constructor == 'function' && O instanceof O.constructor){ return O.constructor.prototype; } return O instanceof Object ? ObjectProto : null; }; /***/ }, /* 60 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var $at = __webpack_require__(61)(true); // 21.1.3.27 String.prototype[@@iterator]() __webpack_require__(50)(String, 'String', function(iterated){ this._t = String(iterated); // target this._i = 0; // next index // 21.1.5.2.1 %StringIteratorPrototype%.next() }, function(){ var O = this._t , index = this._i , point; if(index >= O.length)return {value: undefined, done: true}; point = $at(O, index); this._i += point.length; return {value: point, done: false}; }); /***/ }, /* 61 */ /***/ function(module, exports, __webpack_require__) { var toInteger = __webpack_require__(33) , defined = __webpack_require__(30); // true -> String#at // false -> String#codePointAt module.exports = function(TO_STRING){ return function(that, pos){ var s = String(defined(that)) , i = toInteger(pos) , l = s.length , a, b; if(i < 0 || i >= l)return TO_STRING ? '' : undefined; a = s.charCodeAt(i); return a < 0xd800 || a > 0xdbff || i + 1 === l || (b = s.charCodeAt(i + 1)) < 0xdc00 || b > 0xdfff ? TO_STRING ? s.charAt(i) : a : TO_STRING ? s.slice(i, i + 2) : (a - 0xd800 << 10) + (b - 0xdc00) + 0x10000; }; }; /***/ }, /* 62 */ /***/ function(module, exports, __webpack_require__) { var classof = __webpack_require__(63) , ITERATOR = __webpack_require__(58)('iterator') , Iterators = __webpack_require__(49); module.exports = __webpack_require__(10).isIterable = function(it){ var O = Object(it); return O[ITERATOR] !== undefined || '@@iterator' in O || Iterators.hasOwnProperty(classof(O)); }; /***/ }, /* 63 */ /***/ function(module, exports, __webpack_require__) { // getting tag from 19.1.3.6 Object.prototype.toString() var cof = __webpack_require__(29) , TAG = __webpack_require__(58)('toStringTag') // ES3 wrong here , ARG = cof(function(){ return arguments; }()) == 'Arguments'; // fallback for IE11 Script Access Denied error var tryGet = function(it, key){ try { return it[key]; } catch(e){ /* empty */ } }; module.exports = function(it){ var O, T, B; return it === undefined ? 'Undefined' : it === null ? 'Null' // @@toStringTag case : typeof (T = tryGet(O = Object(it), TAG)) == 'string' ? T // builtinTag case : ARG ? cof(O) // ES3 arguments fallback : (B = cof(O)) == 'Object' && typeof O.callee == 'function' ? 'Arguments' : B; }; /***/ }, /* 64 */ /***/ function(module, exports, __webpack_require__) { module.exports = { "default": __webpack_require__(65), __esModule: true }; /***/ }, /* 65 */ /***/ function(module, exports, __webpack_require__) { __webpack_require__(45); __webpack_require__(60); module.exports = __webpack_require__(66); /***/ }, /* 66 */ /***/ function(module, exports, __webpack_require__) { var anObject = __webpack_require__(15) , get = __webpack_require__(67); module.exports = __webpack_require__(10).getIterator = function(it){ var iterFn = get(it); if(typeof iterFn != 'function')throw TypeError(it + ' is not iterable!'); return anObject(iterFn.call(it)); }; /***/ }, /* 67 */ /***/ function(module, exports, __webpack_require__) { var classof = __webpack_require__(63) , ITERATOR = __webpack_require__(58)('iterator') , Iterators = __webpack_require__(49); module.exports = __webpack_require__(10).getIteratorMethod = function(it){ if(it != undefined)return it[ITERATOR] || it['@@iterator'] || Iterators[classof(it)]; }; /***/ }, /* 68 */ /***/ function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; var _from = __webpack_require__(69); var _from2 = _interopRequireDefault(_from); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } exports.default = function (arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return (0, _from2.default)(arr); } }; /***/ }, /* 69 */ /***/ function(module, exports, __webpack_require__) { module.exports = { "default": __webpack_require__(70), __esModule: true }; /***/ }, /* 70 */ /***/ function(module, exports, __webpack_require__) { __webpack_require__(60); __webpack_require__(71); module.exports = __webpack_require__(10).Array.from; /***/ }, /* 71 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var ctx = __webpack_require__(11) , $export = __webpack_require__(8) , toObject = __webpack_require__(41) , call = __webpack_require__(72) , isArrayIter = __webpack_require__(73) , toLength = __webpack_require__(32) , createProperty = __webpack_require__(74) , getIterFn = __webpack_require__(67); $export($export.S + $export.F * !__webpack_require__(75)(function(iter){ Array.from(iter); }), 'Array', { // 22.1.2.1 Array.from(arrayLike, mapfn = undefined, thisArg = undefined) from: function from(arrayLike/*, mapfn = undefined, thisArg = undefined*/){ var O = toObject(arrayLike) , C = typeof this == 'function' ? this : Array , aLen = arguments.length , mapfn = aLen > 1 ? arguments[1] : undefined , mapping = mapfn !== undefined , index = 0 , iterFn = getIterFn(O) , length, result, step, iterator; if(mapping)mapfn = ctx(mapfn, aLen > 2 ? arguments[2] : undefined, 2); // if object isn't iterable or it's array with default iterator - use simple case if(iterFn != undefined && !(C == Array && isArrayIter(iterFn))){ for(iterator = iterFn.call(O), result = new C; !(step = iterator.next()).done; index++){ createProperty(result, index, mapping ? call(iterator, mapfn, [step.value, index], true) : step.value); } } else { length = toLength(O.length); for(result = new C(length); length > index; index++){ createProperty(result, index, mapping ? mapfn(O[index], index) : O[index]); } } result.length = index; return result; } }); /***/ }, /* 72 */ /***/ function(module, exports, __webpack_require__) { // call something on iterator step with safe closing on error var anObject = __webpack_require__(15); module.exports = function(iterator, fn, value, entries){ try { return entries ? fn(anObject(value)[0], value[1]) : fn(value); // 7.4.6 IteratorClose(iterator, completion) } catch(e){ var ret = iterator['return']; if(ret !== undefined)anObject(ret.call(iterator)); throw e; } }; /***/ }, /* 73 */ /***/ function(module, exports, __webpack_require__) { // check on default Array iterator var Iterators = __webpack_require__(49) , ITERATOR = __webpack_require__(58)('iterator') , ArrayProto = Array.prototype; module.exports = function(it){ return it !== undefined && (Iterators.Array === it || ArrayProto[ITERATOR] === it); }; /***/ }, /* 74 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var $defineProperty = __webpack_require__(14) , createDesc = __webpack_require__(22); module.exports = function(object, index, value){ if(index in object)$defineProperty.f(object, index, createDesc(0, value)); else object[index] = value; }; /***/ }, /* 75 */ /***/ function(module, exports, __webpack_require__) { var ITERATOR = __webpack_require__(58)('iterator') , SAFE_CLOSING = false; try { var riter = [7][ITERATOR](); riter['return'] = function(){ SAFE_CLOSING = true; }; Array.from(riter, function(){ throw 2; }); } catch(e){ /* empty */ } module.exports = function(exec, skipClosing){ if(!skipClosing && !SAFE_CLOSING)return false; var safe = false; try { var arr = [7] , iter = arr[ITERATOR](); iter.next = function(){ return {done: safe = true}; }; arr[ITERATOR] = function(){ return iter; }; exec(arr); } catch(e){ /* empty */ } return safe; }; /***/ }, /* 76 */ /***/ function(module, exports, __webpack_require__) { module.exports = { "default": __webpack_require__(77), __esModule: true }; /***/ }, /* 77 */ /***/ function(module, exports, __webpack_require__) { __webpack_require__(78); module.exports = __webpack_require__(10).Object.getPrototypeOf; /***/ }, /* 78 */ /***/ function(module, exports, __webpack_require__) { // 19.1.2.9 Object.getPrototypeOf(O) var toObject = __webpack_require__(41) , $getPrototypeOf = __webpack_require__(59); __webpack_require__(79)('getPrototypeOf', function(){ return function getPrototypeOf(it){ return $getPrototypeOf(toObject(it)); }; }); /***/ }, /* 79 */ /***/ function(module, exports, __webpack_require__) { // most Object methods by ES6 should accept primitives var $export = __webpack_require__(8) , core = __webpack_require__(10) , fails = __webpack_require__(19); module.exports = function(KEY, exec){ var fn = (core.Object || {})[KEY] || Object[KEY] , exp = {}; exp[KEY] = exec(fn); $export($export.S + $export.F * fails(function(){ fn(1); }), 'Object', exp); }; /***/ }, /* 80 */ /***/ function(module, exports) { "use strict"; exports.__esModule = true; exports.default = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }; /***/ }, /* 81 */ /***/ function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; var _defineProperty = __webpack_require__(82); var _defineProperty2 = _interopRequireDefault(_defineProperty); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } exports.default = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; (0, _defineProperty2.default)(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); /***/ }, /* 82 */ /***/ function(module, exports, __webpack_require__) { module.exports = { "default": __webpack_require__(83), __esModule: true }; /***/ }, /* 83 */ /***/ function(module, exports, __webpack_require__) { __webpack_require__(84); var $Object = __webpack_require__(10).Object; module.exports = function defineProperty(it, key, desc){ return $Object.defineProperty(it, key, desc); }; /***/ }, /* 84 */ /***/ function(module, exports, __webpack_require__) { var $export = __webpack_require__(8); // 19.1.2.4 / 15.2.3.6 Object.defineProperty(O, P, Attributes) $export($export.S + $export.F * !__webpack_require__(18), 'Object', {defineProperty: __webpack_require__(14).f}); /***/ }, /* 85 */ /***/ function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; var _typeof2 = __webpack_require__(86); var _typeof3 = _interopRequireDefault(_typeof2); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } exports.default = function (self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && ((typeof call === "undefined" ? "undefined" : (0, _typeof3.default)(call)) === "object" || typeof call === "function") ? call : self; }; /***/ }, /* 86 */ /***/ function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; var _iterator = __webpack_require__(87); var _iterator2 = _interopRequireDefault(_iterator); var _symbol = __webpack_require__(90); var _symbol2 = _interopRequireDefault(_symbol); var _typeof = typeof _symbol2.default === "function" && typeof _iterator2.default === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof _symbol2.default === "function" && obj.constructor === _symbol2.default ? "symbol" : typeof obj; }; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } exports.default = typeof _symbol2.default === "function" && _typeof(_iterator2.default) === "symbol" ? function (obj) { return typeof obj === "undefined" ? "undefined" : _typeof(obj); } : function (obj) { return obj && typeof _symbol2.default === "function" && obj.constructor === _symbol2.default ? "symbol" : typeof obj === "undefined" ? "undefined" : _typeof(obj); }; /***/ }, /* 87 */ /***/ function(module, exports, __webpack_require__) { module.exports = { "default": __webpack_require__(88), __esModule: true }; /***/ }, /* 88 */ /***/ function(module, exports, __webpack_require__) { __webpack_require__(60); __webpack_require__(45); module.exports = __webpack_require__(89).f('iterator'); /***/ }, /* 89 */ /***/ function(module, exports, __webpack_require__) { exports.f = __webpack_require__(58); /***/ }, /* 90 */ /***/ function(module, exports, __webpack_require__) { module.exports = { "default": __webpack_require__(91), __esModule: true }; /***/ }, /* 91 */ /***/ function(module, exports, __webpack_require__) { __webpack_require__(92); __webpack_require__(101); __webpack_require__(102); __webpack_require__(103); module.exports = __webpack_require__(10).Symbol; /***/ }, /* 92 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; // ECMAScript 6 symbols shim var global = __webpack_require__(9) , has = __webpack_require__(26) , DESCRIPTORS = __webpack_require__(18) , $export = __webpack_require__(8) , redefine = __webpack_require__(52) , META = __webpack_require__(93).KEY , $fails = __webpack_require__(19) , shared = __webpack_require__(36) , setToStringTag = __webpack_require__(57) , uid = __webpack_require__(37) , wks = __webpack_require__(58) , wksExt = __webpack_require__(89) , wksDefine = __webpack_require__(94) , keyOf = __webpack_require__(95) , enumKeys = __webpack_require__(96) , isArray = __webpack_require__(97) , anObject = __webpack_require__(15) , toIObject = __webpack_require__(27) , toPrimitive = __webpack_require__(21) , createDesc = __webpack_require__(22) , _create = __webpack_require__(54) , gOPNExt = __webpack_require__(98) , $GOPD = __webpack_require__(100) , $DP = __webpack_require__(14) , $keys = __webpack_require__(24) , gOPD = $GOPD.f , dP = $DP.f , gOPN = gOPNExt.f , $Symbol = global.Symbol , $JSON = global.JSON , _stringify = $JSON && $JSON.stringify , PROTOTYPE = 'prototype' , HIDDEN = wks('_hidden') , TO_PRIMITIVE = wks('toPrimitive') , isEnum = {}.propertyIsEnumerable , SymbolRegistry = shared('symbol-registry') , AllSymbols = shared('symbols') , OPSymbols = shared('op-symbols') , ObjectProto = Object[PROTOTYPE] , USE_NATIVE = typeof $Symbol == 'function' , QObject = global.QObject; // Don't use setters in Qt Script, https://github.com/zloirock/core-js/issues/173 var setter = !QObject || !QObject[PROTOTYPE] || !QObject[PROTOTYPE].findChild; // fallback for old Android, https://code.google.com/p/v8/issues/detail?id=687 var setSymbolDesc = DESCRIPTORS && $fails(function(){ return _create(dP({}, 'a', { get: function(){ return dP(this, 'a', {value: 7}).a; } })).a != 7; }) ? function(it, key, D){ var protoDesc = gOPD(ObjectProto, key); if(protoDesc)delete ObjectProto[key]; dP(it, key, D); if(protoDesc && it !== ObjectProto)dP(ObjectProto, key, protoDesc); } : dP; var wrap = function(tag){ var sym = AllSymbols[tag] = _create($Symbol[PROTOTYPE]); sym._k = tag; return sym; }; var isSymbol = USE_NATIVE && typeof $Symbol.iterator == 'symbol' ? function(it){ return typeof it == 'symbol'; } : function(it){ return it instanceof $Symbol; }; var $defineProperty = function defineProperty(it, key, D){ if(it === ObjectProto)$defineProperty(OPSymbols, key, D); anObject(it); key = toPrimitive(key, true); anObject(D); if(has(AllSymbols, key)){ if(!D.enumerable){ if(!has(it, HIDDEN))dP(it, HIDDEN, createDesc(1, {})); it[HIDDEN][key] = true; } else { if(has(it, HIDDEN) && it[HIDDEN][key])it[HIDDEN][key] = false; D = _create(D, {enumerable: createDesc(0, false)}); } return setSymbolDesc(it, key, D); } return dP(it, key, D); }; var $defineProperties = function defineProperties(it, P){ anObject(it); var keys = enumKeys(P = toIObject(P)) , i = 0 , l = keys.length , key; while(l > i)$defineProperty(it, key = keys[i++], P[key]); return it; }; var $create = function create(it, P){ return P === undefined ? _create(it) : $defineProperties(_create(it), P); }; var $propertyIsEnumerable = function propertyIsEnumerable(key){ var E = isEnum.call(this, key = toPrimitive(key, true)); if(this === ObjectProto && has(AllSymbols, key) && !has(OPSymbols, key))return false; return E || !has(this, key) || !has(AllSymbols, key) || has(this, HIDDEN) && this[HIDDEN][key] ? E : true; }; var $getOwnPropertyDescriptor = function getOwnPropertyDescriptor(it, key){ it = toIObject(it); key = toPrimitive(key, true); if(it === ObjectProto && has(AllSymbols, key) && !has(OPSymbols, key))return; var D = gOPD(it, key); if(D && has(AllSymbols, key) && !(has(it, HIDDEN) && it[HIDDEN][key]))D.enumerable = true; return D; }; var $getOwnPropertyNames = function getOwnPropertyNames(it){ var names = gOPN(toIObject(it)) , result = [] , i = 0 , key; while(names.length > i){ if(!has(AllSymbols, key = names[i++]) && key != HIDDEN && key != META)result.push(key); } return result; }; var $getOwnPropertySymbols = function getOwnPropertySymbols(it){ var IS_OP = it === ObjectProto , names = gOPN(IS_OP ? OPSymbols : toIObject(it)) , result = [] , i = 0 , key; while(names.length > i){ if(has(AllSymbols, key = names[i++]) && (IS_OP ? has(ObjectProto, key) : true))result.push(AllSymbols[key]); } return result; }; // 19.4.1.1 Symbol([description]) if(!USE_NATIVE){ $Symbol = function Symbol(){ if(this instanceof $Symbol)throw TypeError('Symbol is not a constructor!'); var tag = uid(arguments.length > 0 ? arguments[0] : undefined); var $set = function(value){ if(this === ObjectProto)$set.call(OPSymbols, value); if(has(this, HIDDEN) && has(this[HIDDEN], tag))this[HIDDEN][tag] = false; setSymbolDesc(this, tag, createDesc(1, value)); }; if(DESCRIPTORS && setter)setSymbolDesc(ObjectProto, tag, {configurable: true, set: $set}); return wrap(tag); }; redefine($Symbol[PROTOTYPE], 'toString', function toString(){ return this._k; }); $GOPD.f = $getOwnPropertyDescriptor; $DP.f = $defineProperty; __webpack_require__(99).f = gOPNExt.f = $getOwnPropertyNames; __webpack_require__(40).f = $propertyIsEnumerable; __webpack_require__(39).f = $getOwnPropertySymbols; if(DESCRIPTORS && !__webpack_require__(51)){ redefine(ObjectProto, 'propertyIsEnumerable', $propertyIsEnumerable, true); } wksExt.f = function(name){ return wrap(wks(name)); } } $export($export.G + $export.W + $export.F * !USE_NATIVE, {Symbol: $Symbol}); for(var symbols = ( // 19.4.2.2, 19.4.2.3, 19.4.2.4, 19.4.2.6, 19.4.2.8, 19.4.2.9, 19.4.2.10, 19.4.2.11, 19.4.2.12, 19.4.2.13, 19.4.2.14 'hasInstance,isConcatSpreadable,iterator,match,replace,search,species,split,toPrimitive,toStringTag,unscopables' ).split(','), i = 0; symbols.length > i; )wks(symbols[i++]); for(var symbols = $keys(wks.store), i = 0; symbols.length > i; )wksDefine(symbols[i++]); $export($export.S + $export.F * !USE_NATIVE, 'Symbol', { // 19.4.2.1 Symbol.for(key) 'for': function(key){ return has(SymbolRegistry, key += '') ? SymbolRegistry[key] : SymbolRegistry[key] = $Symbol(key); }, // 19.4.2.5 Symbol.keyFor(sym) keyFor: function keyFor(key){ if(isSymbol(key))return keyOf(SymbolRegistry, key); throw TypeError(key + ' is not a symbol!'); }, useSetter: function(){ setter = true; }, useSimple: function(){ setter = false; } }); $export($export.S + $export.F * !USE_NATIVE, 'Object', { // 19.1.2.2 Object.create(O [, Properties]) create: $create, // 19.1.2.4 Object.defineProperty(O, P, Attributes) defineProperty: $defineProperty, // 19.1.2.3 Object.defineProperties(O, Properties) defineProperties: $defineProperties, // 19.1.2.6 Object.getOwnPropertyDescriptor(O, P) getOwnPropertyDescriptor: $getOwnPropertyDescriptor, // 19.1.2.7 Object.getOwnPropertyNames(O) getOwnPropertyNames: $getOwnPropertyNames, // 19.1.2.8 Object.getOwnPropertySymbols(O) getOwnPropertySymbols: $getOwnPropertySymbols }); // 24.3.2 JSON.stringify(value [, replacer [, space]]) $JSON && $export($export.S + $export.F * (!USE_NATIVE || $fails(function(){ var S = $Symbol(); // MS Edge converts symbol values to JSON as {} // WebKit converts symbol values to JSON as null // V8 throws on boxed symbols return _stringify([S]) != '[null]' || _stringify({a: S}) != '{}' || _stringify(Object(S)) != '{}'; })), 'JSON', { stringify: function stringify(it){ if(it === undefined || isSymbol(it))return; // IE8 returns string on undefined var args = [it] , i = 1 , replacer, $replacer; while(arguments.length > i)args.push(arguments[i++]); replacer = args[1]; if(typeof replacer == 'function')$replacer = replacer; if($replacer || !isArray(replacer))replacer = function(key, value){ if($replacer)value = $replacer.call(this, key, value); if(!isSymbol(value))return value; }; args[1] = replacer; return _stringify.apply($JSON, args); } }); // 19.4.3.4 Symbol.prototype[@@toPrimitive](hint) $Symbol[PROTOTYPE][TO_PRIMITIVE] || __webpack_require__(13)($Symbol[PROTOTYPE], TO_PRIMITIVE, $Symbol[PROTOTYPE].valueOf); // 19.4.3.5 Symbol.prototype[@@toStringTag] setToStringTag($Symbol, 'Symbol'); // 20.2.1.9 Math[@@toStringTag] setToStringTag(Math, 'Math', true); // 24.3.3 JSON[@@toStringTag] setToStringTag(global.JSON, 'JSON', true); /***/ }, /* 93 */ /***/ function(module, exports, __webpack_require__) { var META = __webpack_require__(37)('meta') , isObject = __webpack_require__(16) , has = __webpack_require__(26) , setDesc = __webpack_require__(14).f , id = 0; var isExtensible = Object.isExtensible || function(){ return true; }; var FREEZE = !__webpack_require__(19)(function(){ return isExtensible(Object.preventExtensions({})); }); var setMeta = function(it){ setDesc(it, META, {value: { i: 'O' + ++id, // object ID w: {} // weak collections IDs }}); }; var fastKey = function(it, create){ // return primitive with prefix if(!isObject(it))return typeof it == 'symbol' ? it : (typeof it == 'string' ? 'S' : 'P') + it; if(!has(it, META)){ // can't set metadata to uncaught frozen object if(!isExtensible(it))return 'F'; // not necessary to add metadata if(!create)return 'E'; // add missing metadata setMeta(it); // return object ID } return it[META].i; }; var getWeak = function(it, create){ if(!has(it, META)){ // can't set metadata to uncaught frozen object if(!isExtensible(it))return true; // not necessary to add metadata if(!create)return false; // add missing metadata setMeta(it); // return hash weak collections IDs } return it[META].w; }; // add metadata on freeze-family methods calling var onFreeze = function(it){ if(FREEZE && meta.NEED && isExtensible(it) && !has(it, META))setMeta(it); return it; }; var meta = module.exports = { KEY: META, NEED: false, fastKey: fastKey, getWeak: getWeak, onFreeze: onFreeze }; /***/ }, /* 94 */ /***/ function(module, exports, __webpack_require__) { var global = __webpack_require__(9) , core = __webpack_require__(10) , LIBRARY = __webpack_require__(51) , wksExt = __webpack_require__(89) , defineProperty = __webpack_require__(14).f; module.exports = function(name){ var $Symbol = core.Symbol || (core.Symbol = LIBRARY ? {} : global.Symbol || {}); if(name.charAt(0) != '_' && !(name in $Symbol))defineProperty($Symbol, name, {value: wksExt.f(name)}); }; /***/ }, /* 95 */ /***/ function(module, exports, __webpack_require__) { var getKeys = __webpack_require__(24) , toIObject = __webpack_require__(27); module.exports = function(object, el){ var O = toIObject(object) , keys = getKeys(O) , length = keys.length , index = 0 , key; while(length > index)if(O[key = keys[index++]] === el)return key; }; /***/ }, /* 96 */ /***/ function(module, exports, __webpack_require__) { // all enumerable object keys, includes symbols var getKeys = __webpack_require__(24) , gOPS = __webpack_require__(39) , pIE = __webpack_require__(40); module.exports = function(it){ var result = getKeys(it) , getSymbols = gOPS.f; if(getSymbols){ var symbols = getSymbols(it) , isEnum = pIE.f , i = 0 , key; while(symbols.length > i)if(isEnum.call(it, key = symbols[i++]))result.push(key); } return result; }; /***/ }, /* 97 */ /***/ function(module, exports, __webpack_require__) { // 7.2.2 IsArray(argument) var cof = __webpack_require__(29); module.exports = Array.isArray || function isArray(arg){ return cof(arg) == 'Array'; }; /***/ }, /* 98 */ /***/ function(module, exports, __webpack_require__) { // fallback for IE11 buggy Object.getOwnPropertyNames with iframe and window var toIObject = __webpack_require__(27) , gOPN = __webpack_require__(99).f , toString = {}.toString; var windowNames = typeof window == 'object' && window && Object.getOwnPropertyNames ? Object.getOwnPropertyNames(window) : []; var getWindowNames = function(it){ try { return gOPN(it); } catch(e){ return windowNames.slice(); } }; module.exports.f = function getOwnPropertyNames(it){ return windowNames && toString.call(it) == '[object Window]' ? getWindowNames(it) : gOPN(toIObject(it)); }; /***/ }, /* 99 */ /***/ function(module, exports, __webpack_require__) { // 19.1.2.7 / 15.2.3.4 Object.getOwnPropertyNames(O) var $keys = __webpack_require__(25) , hiddenKeys = __webpack_require__(38).concat('length', 'prototype'); exports.f = Object.getOwnPropertyNames || function getOwnPropertyNames(O){ return $keys(O, hiddenKeys); }; /***/ }, /* 100 */ /***/ function(module, exports, __webpack_require__) { var pIE = __webpack_require__(40) , createDesc = __webpack_require__(22) , toIObject = __webpack_require__(27) , toPrimitive = __webpack_require__(21) , has = __webpack_require__(26) , IE8_DOM_DEFINE = __webpack_require__(17) , gOPD = Object.getOwnPropertyDescriptor; exports.f = __webpack_require__(18) ? gOPD : function getOwnPropertyDescriptor(O, P){ O = toIObject(O); P = toPrimitive(P, true); if(IE8_DOM_DEFINE)try { return gOPD(O, P); } catch(e){ /* empty */ } if(has(O, P))return createDesc(!pIE.f.call(O, P), O[P]); }; /***/ }, /* 101 */ /***/ function(module, exports) { /***/ }, /* 102 */ /***/ function(module, exports, __webpack_require__) { __webpack_require__(94)('asyncIterator'); /***/ }, /* 103 */ /***/ function(module, exports, __webpack_require__) { __webpack_require__(94)('observable'); /***/ }, /* 104 */ /***/ function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; var _setPrototypeOf = __webpack_require__(105); var _setPrototypeOf2 = _interopRequireDefault(_setPrototypeOf); var _create = __webpack_require__(109); var _create2 = _interopRequireDefault(_create); var _typeof2 = __webpack_require__(86); var _typeof3 = _interopRequireDefault(_typeof2); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } exports.default = function (subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + (typeof superClass === "undefined" ? "undefined" : (0, _typeof3.default)(superClass))); } subClass.prototype = (0, _create2.default)(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) _setPrototypeOf2.default ? (0, _setPrototypeOf2.default)(subClass, superClass) : subClass.__proto__ = superClass; }; /***/ }, /* 105 */ /***/ function(module, exports, __webpack_require__) { module.exports = { "default": __webpack_require__(106), __esModule: true }; /***/ }, /* 106 */ /***/ function(module, exports, __webpack_require__) { __webpack_require__(107); module.exports = __webpack_require__(10).Object.setPrototypeOf; /***/ }, /* 107 */ /***/ function(module, exports, __webpack_require__) { // 19.1.3.19 Object.setPrototypeOf(O, proto) var $export = __webpack_require__(8); $export($export.S, 'Object', {setPrototypeOf: __webpack_require__(108).set}); /***/ }, /* 108 */ /***/ function(module, exports, __webpack_require__) { // Works with __proto__ only. Old v8 can't work with null proto objects. /* eslint-disable no-proto */ var isObject = __webpack_require__(16) , anObject = __webpack_require__(15); var check = function(O, proto){ anObject(O); if(!isObject(proto) && proto !== null)throw TypeError(proto + ": can't set as prototype!"); }; module.exports = { set: Object.setPrototypeOf || ('__proto__' in {} ? // eslint-disable-line function(test, buggy, set){ try { set = __webpack_require__(11)(Function.call, __webpack_require__(100).f(Object.prototype, '__proto__').set, 2); set(test, []); buggy = !(test instanceof Array); } catch(e){ buggy = true; } return function setPrototypeOf(O, proto){ check(O, proto); if(buggy)O.__proto__ = proto; else set(O, proto); return O; }; }({}, false) : undefined), check: check }; /***/ }, /* 109 */ /***/ function(module, exports, __webpack_require__) { module.exports = { "default": __webpack_require__(110), __esModule: true }; /***/ }, /* 110 */ /***/ function(module, exports, __webpack_require__) { __webpack_require__(111); var $Object = __webpack_require__(10).Object; module.exports = function create(P, D){ return $Object.create(P, D); }; /***/ }, /* 111 */ /***/ function(module, exports, __webpack_require__) { var $export = __webpack_require__(8) // 19.1.2.2 / 15.2.3.5 Object.create(O [, Properties]) $export($export.S, 'Object', {create: __webpack_require__(54)}); /***/ }, /* 112 */ /***/ function(module, exports) { module.exports = __WEBPACK_EXTERNAL_MODULE_112__; /***/ }, /* 113 */ /***/ function(module, exports) { module.exports = __WEBPACK_EXTERNAL_MODULE_113__; /***/ }, /* 114 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _classCallCheck2 = __webpack_require__(80); var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); var _createClass2 = __webpack_require__(81); var _createClass3 = _interopRequireDefault(_createClass2); var _find = __webpack_require__(115); var _find2 = _interopRequireDefault(_find); var _sortBy = __webpack_require__(228); var _sortBy2 = _interopRequireDefault(_sortBy); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var Manager = function () { function Manager() { (0, _classCallCheck3.default)(this, Manager); this.refs = {}; } (0, _createClass3.default)(Manager, [{ key: 'add', value: function add(collection, ref) { if (!this.refs[collection]) this.refs[collection] = []; this.refs[collection].push(ref); } }, { key: 'remove', value: function remove(collection, ref) { var index = this.getIndex(collection, ref); if (index !== -1) { this.refs[collection].splice(index, 1); } } }, { key: 'getActive', value: function getActive() { var _this = this; return (0, _find2.default)(this.refs[this.active.collection], function (_ref) { var node = _ref.node; return node.sortableInfo.index == _this.active.index; }); } }, { key: 'getIndex', value: function getIndex(collection, ref) { return this.refs[collection].indexOf(ref); } }, { key: 'getOrderedRefs', value: function getOrderedRefs() { var collection = arguments.length <= 0 || arguments[0] === undefined ? this.active.collection : arguments[0]; return (0, _sortBy2.default)(this.refs[collection], function (_ref2) { var node = _ref2.node; return node.sortableInfo.index; }); } }]); return Manager; }(); exports.default = Manager; /***/ }, /* 115 */ /***/ function(module, exports, __webpack_require__) { var createFind = __webpack_require__(116), findIndex = __webpack_require__(223); /** * Iterates over elements of `collection`, returning the first element * `predicate` returns truthy for. The predicate is invoked with three * arguments: (value, index|key, collection). * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to search. * @param {Function} [predicate=_.identity] * The function invoked per iteration. * @param {number} [fromIndex=0] The index to search from. * @returns {*} Returns the matched element, else `undefined`. * @example * * var users = [ * { 'user': 'barney', 'age': 36, 'active': true }, * { 'user': 'fred', 'age': 40, 'active': false }, * { 'user': 'pebbles', 'age': 1, 'active': true } * ]; * * _.find(users, function(o) { return o.age < 40; }); * // => object for 'barney' * * // The `_.matches` iteratee shorthand. * _.find(users, { 'age': 1, 'active': true }); * // => object for 'pebbles' * * // The `_.matchesProperty` iteratee shorthand. * _.find(users, ['active', false]); * // => object for 'fred' * * // The `_.property` iteratee shorthand. * _.find(users, 'active'); * // => object for 'barney' */ var find = createFind(findIndex); module.exports = find; /***/ }, /* 116 */ /***/ function(module, exports, __webpack_require__) { var baseIteratee = __webpack_require__(117), isArrayLike = __webpack_require__(183), keys = __webpack_require__(177); /** * Creates a `_.find` or `_.findLast` function. * * @private * @param {Function} findIndexFunc The function to find the collection index. * @returns {Function} Returns the new find function. */ function createFind(findIndexFunc) { return function(collection, predicate, fromIndex) { var iterable = Object(collection); if (!isArrayLike(collection)) { var iteratee = baseIteratee(predicate, 3); collection = keys(collection); predicate = function(key) { return iteratee(iterable[key], key, iterable); }; } var index = findIndexFunc(collection, predicate, fromIndex); return index > -1 ? iterable[iteratee ? collection[index] : index] : undefined; }; } module.exports = createFind; /***/ }, /* 117 */ /***/ function(module, exports, __webpack_require__) { var baseMatches = __webpack_require__(118), baseMatchesProperty = __webpack_require__(206), identity = __webpack_require__(220), isArray = __webpack_require__(188), property = __webpack_require__(221); /** * The base implementation of `_.iteratee`. * * @private * @param {*} [value=_.identity] The value to convert to an iteratee. * @returns {Function} Returns the iteratee. */ function baseIteratee(value) { // Don't store the `typeof` result in a variable to avoid a JIT bug in Safari 9. // See https://bugs.webkit.org/show_bug.cgi?id=156034 for more details. if (typeof value == 'function') { return value; } if (value == null) { return identity; } if (typeof value == 'object') { return isArray(value) ? baseMatchesProperty(value[0], value[1]) : baseMatches(value); } return property(value); } module.exports = baseIteratee; /***/ }, /* 118 */ /***/ function(module, exports, __webpack_require__) { var baseIsMatch = __webpack_require__(119), getMatchData = __webpack_require__(203), matchesStrictComparable = __webpack_require__(205); /** * The base implementation of `_.matches` which doesn't clone `source`. * * @private * @param {Object} source The object of property values to match. * @returns {Function} Returns the new spec function. */ function baseMatches(source) { var matchData = getMatchData(source); if (matchData.length == 1 && matchData[0][2]) { return matchesStrictComparable(matchData[0][0], matchData[0][1]); } return function(object) { return object === source || baseIsMatch(object, source, matchData); }; } module.exports = baseMatches; /***/ }, /* 119 */ /***/ function(module, exports, __webpack_require__) { var Stack = __webpack_require__(120), baseIsEqual = __webpack_require__(161); /** Used to compose bitmasks for comparison styles. */ var UNORDERED_COMPARE_FLAG = 1, PARTIAL_COMPARE_FLAG = 2; /** * The base implementation of `_.isMatch` without support for iteratee shorthands. * * @private * @param {Object} object The object to inspect. * @param {Object} source The object of property values to match. * @param {Array} matchData The property names, values, and compare flags to match. * @param {Function} [customizer] The function to customize comparisons. * @returns {boolean} Returns `true` if `object` is a match, else `false`. */ function baseIsMatch(object, source, matchData, customizer) { var index = matchData.length, length = index, noCustomizer = !customizer; if (object == null) { return !length; } object = Object(object); while (index--) { var data = matchData[index]; if ((noCustomizer && data[2]) ? data[1] !== object[data[0]] : !(data[0] in object) ) { return false; } } while (++index < length) { data = matchData[index]; var key = data[0], objValue = object[key], srcValue = data[1]; if (noCustomizer && data[2]) { if (objValue === undefined && !(key in object)) { return false; } } else { var stack = new Stack; if (customizer) { var result = customizer(objValue, srcValue, key, object, source, stack); } if (!(result === undefined ? baseIsEqual(srcValue, objValue, customizer, UNORDERED_COMPARE_FLAG | PARTIAL_COMPARE_FLAG, stack) : result )) { return false; } } } return true; } module.exports = baseIsMatch; /***/ }, /* 120 */ /***/ function(module, exports, __webpack_require__) { var ListCache = __webpack_require__(121), stackClear = __webpack_require__(129), stackDelete = __webpack_require__(130), stackGet = __webpack_require__(131), stackHas = __webpack_require__(132), stackSet = __webpack_require__(133); /** * Creates a stack cache object to store key-value pairs. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function Stack(entries) { this.__data__ = new ListCache(entries); } // Add methods to `Stack`. Stack.prototype.clear = stackClear; Stack.prototype['delete'] = stackDelete; Stack.prototype.get = stackGet; Stack.prototype.has = stackHas; Stack.prototype.set = stackSet; module.exports = Stack; /***/ }, /* 121 */ /***/ function(module, exports, __webpack_require__) { var listCacheClear = __webpack_require__(122), listCacheDelete = __webpack_require__(123), listCacheGet = __webpack_require__(126), listCacheHas = __webpack_require__(127), listCacheSet = __webpack_require__(128); /** * Creates an list cache object. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function ListCache(entries) { var index = -1, length = entries ? entries.length : 0; this.clear(); while (++index < length) { var entry = entries[index]; this.set(entry[0], entry[1]); } } // Add methods to `ListCache`. ListCache.prototype.clear = listCacheClear; ListCache.prototype['delete'] = listCacheDelete; ListCache.prototype.get = listCacheGet; ListCache.prototype.has = listCacheHas; ListCache.prototype.set = listCacheSet; module.exports = ListCache; /***/ }, /* 122 */ /***/ function(module, exports) { /** * Removes all key-value entries from the list cache. * * @private * @name clear * @memberOf ListCache */ function listCacheClear() { this.__data__ = []; } module.exports = listCacheClear; /***/ }, /* 123 */ /***/ function(module, exports, __webpack_require__) { var assocIndexOf = __webpack_require__(124); /** Used for built-in method references. */ var arrayProto = Array.prototype; /** Built-in value references. */ var splice = arrayProto.splice; /** * Removes `key` and its value from the list cache. * * @private * @name delete * @memberOf ListCache * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ function listCacheDelete(key) { var data = this.__data__, index = assocIndexOf(data, key); if (index < 0) { return false; } var lastIndex = data.length - 1; if (index == lastIndex) { data.pop(); } else { splice.call(data, index, 1); } return true; } module.exports = listCacheDelete; /***/ }, /* 124 */ /***/ function(module, exports, __webpack_require__) { var eq = __webpack_require__(125); /** * Gets the index at which the `key` is found in `array` of key-value pairs. * * @private * @param {Array} array The array to search. * @param {*} key The key to search for. * @returns {number} Returns the index of the matched value, else `-1`. */ function assocIndexOf(array, key) { var length = array.length; while (length--) { if (eq(array[length][0], key)) { return length; } } return -1; } module.exports = assocIndexOf; /***/ }, /* 125 */ /***/ function(module, exports) { /** * Performs a * [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero) * comparison between two values to determine if they are equivalent. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {boolean} Returns `true` if the values are equivalent, else `false`. * @example * * var object = { 'a': 1 }; * var other = { 'a': 1 }; * * _.eq(object, object); * // => true * * _.eq(object, other); * // => false * * _.eq('a', 'a'); * // => true * * _.eq('a', Object('a')); * // => false * * _.eq(NaN, NaN); * // => true */ function eq(value, other) { return value === other || (value !== value && other !== other); } module.exports = eq; /***/ }, /* 126 */ /***/ function(module, exports, __webpack_require__) { var assocIndexOf = __webpack_require__(124); /** * Gets the list cache value for `key`. * * @private * @name get * @memberOf ListCache * @param {string} key The key of the value to get. * @returns {*} Returns the entry value. */ function listCacheGet(key) { var data = this.__data__, index = assocIndexOf(data, key); return index < 0 ? undefined : data[index][1]; } module.exports = listCacheGet; /***/ }, /* 127 */ /***/ function(module, exports, __webpack_require__) { var assocIndexOf = __webpack_require__(124); /** * Checks if a list cache value for `key` exists. * * @private * @name has * @memberOf ListCache * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function listCacheHas(key) { return assocIndexOf(this.__data__, key) > -1; } module.exports = listCacheHas; /***/ }, /* 128 */ /***/ function(module, exports, __webpack_require__) { var assocIndexOf = __webpack_require__(124); /** * Sets the list cache `key` to `value`. * * @private * @name set * @memberOf ListCache * @param {string} key The key of the value to set. * @param {*} value The value to set. * @returns {Object} Returns the list cache instance. */ function listCacheSet(key, value) { var data = this.__data__, index = assocIndexOf(data, key); if (index < 0) { data.push([key, value]); } else { data[index][1] = value; } return this; } module.exports = listCacheSet; /***/ }, /* 129 */ /***/ function(module, exports, __webpack_require__) { var ListCache = __webpack_require__(121); /** * Removes all key-value entries from the stack. * * @private * @name clear * @memberOf Stack */ function stackClear() { this.__data__ = new ListCache; } module.exports = stackClear; /***/ }, /* 130 */ /***/ function(module, exports) { /** * Removes `key` and its value from the stack. * * @private * @name delete * @memberOf Stack * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ function stackDelete(key) { return this.__data__['delete'](key); } module.exports = stackDelete; /***/ }, /* 131 */ /***/ function(module, exports) { /** * Gets the stack value for `key`. * * @private * @name get * @memberOf Stack * @param {string} key The key of the value to get. * @returns {*} Returns the entry value. */ function stackGet(key) { return this.__data__.get(key); } module.exports = stackGet; /***/ }, /* 132 */ /***/ function(module, exports) { /** * Checks if a stack value for `key` exists. * * @private * @name has * @memberOf Stack * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function stackHas(key) { return this.__data__.has(key); } module.exports = stackHas; /***/ }, /* 133 */ /***/ function(module, exports, __webpack_require__) { var ListCache = __webpack_require__(121), Map = __webpack_require__(134), MapCache = __webpack_require__(146); /** Used as the size to enable large array optimizations. */ var LARGE_ARRAY_SIZE = 200; /** * Sets the stack `key` to `value`. * * @private * @name set * @memberOf Stack * @param {string} key The key of the value to set. * @param {*} value The value to set. * @returns {Object} Returns the stack cache instance. */ function stackSet(key, value) { var cache = this.__data__; if (cache instanceof ListCache) { var pairs = cache.__data__; if (!Map || (pairs.length < LARGE_ARRAY_SIZE - 1)) { pairs.push([key, value]); return this; } cache = this.__data__ = new MapCache(pairs); } cache.set(key, value); return this; } module.exports = stackSet; /***/ }, /* 134 */ /***/ function(module, exports, __webpack_require__) { var getNative = __webpack_require__(135), root = __webpack_require__(142); /* Built-in method references that are verified to be native. */ var Map = getNative(root, 'Map'); module.exports = Map; /***/ }, /* 135 */ /***/ function(module, exports, __webpack_require__) { var baseIsNative = __webpack_require__(136), getValue = __webpack_require__(145); /** * Gets the native function at `key` of `object`. * * @private * @param {Object} object The object to query. * @param {string} key The key of the method to get. * @returns {*} Returns the function if it's native, else `undefined`. */ function getNative(object, key) { var value = getValue(object, key); return baseIsNative(value) ? value : undefined; } module.exports = getNative; /***/ }, /* 136 */ /***/ function(module, exports, __webpack_require__) { var isFunction = __webpack_require__(137), isHostObject = __webpack_require__(139), isMasked = __webpack_require__(140), isObject = __webpack_require__(138), toSource = __webpack_require__(144); /** * Used to match `RegExp` * [syntax characters](http://ecma-international.org/ecma-262/6.0/#sec-patterns). */ var reRegExpChar = /[\\^$.*+?()[\]{}|]/g; /** Used to detect host constructors (Safari). */ var reIsHostCtor = /^\[object .+?Constructor\]$/; /** Used for built-in method references. */ var objectProto = Object.prototype; /** Used to resolve the decompiled source of functions. */ var funcToString = Function.prototype.toString; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** Used to detect if a method is native. */ var reIsNative = RegExp('^' + funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\$&') .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$' ); /** * The base implementation of `_.isNative` without bad shim checks. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a native function, * else `false`. */ function baseIsNative(value) { if (!isObject(value) || isMasked(value)) { return false; } var pattern = (isFunction(value) || isHostObject(value)) ? reIsNative : reIsHostCtor; return pattern.test(toSource(value)); } module.exports = baseIsNative; /***/ }, /* 137 */ /***/ function(module, exports, __webpack_require__) { var isObject = __webpack_require__(138); /** `Object#toString` result references. */ var funcTag = '[object Function]', genTag = '[object GeneratorFunction]'; /** Used for built-in method references. */ var objectProto = Object.prototype; /** * Used to resolve the * [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring) * of values. */ var objectToString = objectProto.toString; /** * Checks if `value` is classified as a `Function` object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a function, else `false`. * @example * * _.isFunction(_); * // => true * * _.isFunction(/abc/); * // => false */ function isFunction(value) { // The use of `Object#toString` avoids issues with the `typeof` operator // in Safari 8 which returns 'object' for typed array and weak map constructors, // and PhantomJS 1.9 which returns 'function' for `NodeList` instances. var tag = isObject(value) ? objectToString.call(value) : ''; return tag == funcTag || tag == genTag; } module.exports = isFunction; /***/ }, /* 138 */ /***/ function(module, exports) { /** * Checks if `value` is the * [language type](http://www.ecma-international.org/ecma-262/6.0/#sec-ecmascript-language-types) * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an object, else `false`. * @example * * _.isObject({}); * // => true * * _.isObject([1, 2, 3]); * // => true * * _.isObject(_.noop); * // => true * * _.isObject(null); * // => false */ function isObject(value) { var type = typeof value; return !!value && (type == 'object' || type == 'function'); } module.exports = isObject; /***/ }, /* 139 */ /***/ function(module, exports) { /** * Checks if `value` is a host object in IE < 9. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a host object, else `false`. */ function isHostObject(value) { // Many host objects are `Object` objects that can coerce to strings // despite having improperly defined `toString` methods. var result = false; if (value != null && typeof value.toString != 'function') { try { result = !!(value + ''); } catch (e) {} } return result; } module.exports = isHostObject; /***/ }, /* 140 */ /***/ function(module, exports, __webpack_require__) { var coreJsData = __webpack_require__(141); /** Used to detect methods masquerading as native. */ var maskSrcKey = (function() { var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || ''); return uid ? ('Symbol(src)_1.' + uid) : ''; }()); /** * Checks if `func` has its source masked. * * @private * @param {Function} func The function to check. * @returns {boolean} Returns `true` if `func` is masked, else `false`. */ function isMasked(func) { return !!maskSrcKey && (maskSrcKey in func); } module.exports = isMasked; /***/ }, /* 141 */ /***/ function(module, exports, __webpack_require__) { var root = __webpack_require__(142); /** Used to detect overreaching core-js shims. */ var coreJsData = root['__core-js_shared__']; module.exports = coreJsData; /***/ }, /* 142 */ /***/ function(module, exports, __webpack_require__) { var freeGlobal = __webpack_require__(143); /** Detect free variable `self`. */ var freeSelf = typeof self == 'object' && self && self.Object === Object && self; /** Used as a reference to the global object. */ var root = freeGlobal || freeSelf || Function('return this')(); module.exports = root; /***/ }, /* 143 */ /***/ function(module, exports) { /* WEBPACK VAR INJECTION */(function(global) {/** Detect free variable `global` from Node.js. */ var freeGlobal = typeof global == 'object' && global && global.Object === Object && global; module.exports = freeGlobal; /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()))) /***/ }, /* 144 */ /***/ function(module, exports) { /** Used to resolve the decompiled source of functions. */ var funcToString = Function.prototype.toString; /** * Converts `func` to its source code. * * @private * @param {Function} func The function to process. * @returns {string} Returns the source code. */ function toSource(func) { if (func != null) { try { return funcToString.call(func); } catch (e) {} try { return (func + ''); } catch (e) {} } return ''; } module.exports = toSource; /***/ }, /* 145 */ /***/ function(module, exports) { /** * Gets the value at `key` of `object`. * * @private * @param {Object} [object] The object to query. * @param {string} key The key of the property to get. * @returns {*} Returns the property value. */ function getValue(object, key) { return object == null ? undefined : object[key]; } module.exports = getValue; /***/ }, /* 146 */ /***/ function(module, exports, __webpack_require__) { var mapCacheClear = __webpack_require__(147), mapCacheDelete = __webpack_require__(155), mapCacheGet = __webpack_require__(158), mapCacheHas = __webpack_require__(159), mapCacheSet = __webpack_require__(160); /** * Creates a map cache object to store key-value pairs. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function MapCache(entries) { var index = -1, length = entries ? entries.length : 0; this.clear(); while (++index < length) { var entry = entries[index]; this.set(entry[0], entry[1]); } } // Add methods to `MapCache`. MapCache.prototype.clear = mapCacheClear; MapCache.prototype['delete'] = mapCacheDelete; MapCache.prototype.get = mapCacheGet; MapCache.prototype.has = mapCacheHas; MapCache.prototype.set = mapCacheSet; module.exports = MapCache; /***/ }, /* 147 */ /***/ function(module, exports, __webpack_require__) { var Hash = __webpack_require__(148), ListCache = __webpack_require__(121), Map = __webpack_require__(134); /** * Removes all key-value entries from the map. * * @private * @name clear * @memberOf MapCache */ function mapCacheClear() { this.__data__ = { 'hash': new Hash, 'map': new (Map || ListCache), 'string': new Hash }; } module.exports = mapCacheClear; /***/ }, /* 148 */ /***/ function(module, exports, __webpack_require__) { var hashClear = __webpack_require__(149), hashDelete = __webpack_require__(151), hashGet = __webpack_require__(152), hashHas = __webpack_require__(153), hashSet = __webpack_require__(154); /** * Creates a hash object. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function Hash(entries) { var index = -1, length = entries ? entries.length : 0; this.clear(); while (++index < length) { var entry = entries[index]; this.set(entry[0], entry[1]); } } // Add methods to `Hash`. Hash.prototype.clear = hashClear; Hash.prototype['delete'] = hashDelete; Hash.prototype.get = hashGet; Hash.prototype.has = hashHas; Hash.prototype.set = hashSet; module.exports = Hash; /***/ }, /* 149 */ /***/ function(module, exports, __webpack_require__) { var nativeCreate = __webpack_require__(150); /** * Removes all key-value entries from the hash. * * @private * @name clear * @memberOf Hash */ function hashClear() { this.__data__ = nativeCreate ? nativeCreate(null) : {}; } module.exports = hashClear; /***/ }, /* 150 */ /***/ function(module, exports, __webpack_require__) { var getNative = __webpack_require__(135); /* Built-in method references that are verified to be native. */ var nativeCreate = getNative(Object, 'create'); module.exports = nativeCreate; /***/ }, /* 151 */ /***/ function(module, exports) { /** * Removes `key` and its value from the hash. * * @private * @name delete * @memberOf Hash * @param {Object} hash The hash to modify. * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ function hashDelete(key) { return this.has(key) && delete this.__data__[key]; } module.exports = hashDelete; /***/ }, /* 152 */ /***/ function(module, exports, __webpack_require__) { var nativeCreate = __webpack_require__(150); /** Used to stand-in for `undefined` hash values. */ var HASH_UNDEFINED = '__lodash_hash_undefined__'; /** Used for built-in method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * Gets the hash value for `key`. * * @private * @name get * @memberOf Hash * @param {string} key The key of the value to get. * @returns {*} Returns the entry value. */ function hashGet(key) { var data = this.__data__; if (nativeCreate) { var result = data[key]; return result === HASH_UNDEFINED ? undefined : result; } return hasOwnProperty.call(data, key) ? data[key] : undefined; } module.exports = hashGet; /***/ }, /* 153 */ /***/ function(module, exports, __webpack_require__) { var nativeCreate = __webpack_require__(150); /** Used for built-in method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * Checks if a hash value for `key` exists. * * @private * @name has * @memberOf Hash * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function hashHas(key) { var data = this.__data__; return nativeCreate ? data[key] !== undefined : hasOwnProperty.call(data, key); } module.exports = hashHas; /***/ }, /* 154 */ /***/ function(module, exports, __webpack_require__) { var nativeCreate = __webpack_require__(150); /** Used to stand-in for `undefined` hash values. */ var HASH_UNDEFINED = '__lodash_hash_undefined__'; /** * Sets the hash `key` to `value`. * * @private * @name set * @memberOf Hash * @param {string} key The key of the value to set. * @param {*} value The value to set. * @returns {Object} Returns the hash instance. */ function hashSet(key, value) { var data = this.__data__; data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value; return this; } module.exports = hashSet; /***/ }, /* 155 */ /***/ function(module, exports, __webpack_require__) { var getMapData = __webpack_require__(156); /** * Removes `key` and its value from the map. * * @private * @name delete * @memberOf MapCache * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ function mapCacheDelete(key) { return getMapData(this, key)['delete'](key); } module.exports = mapCacheDelete; /***/ }, /* 156 */ /***/ function(module, exports, __webpack_require__) { var isKeyable = __webpack_require__(157); /** * Gets the data for `map`. * * @private * @param {Object} map The map to query. * @param {string} key The reference key. * @returns {*} Returns the map data. */ function getMapData(map, key) { var data = map.__data__; return isKeyable(key) ? data[typeof key == 'string' ? 'string' : 'hash'] : data.map; } module.exports = getMapData; /***/ }, /* 157 */ /***/ function(module, exports) { /** * Checks if `value` is suitable for use as unique object key. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is suitable, else `false`. */ function isKeyable(value) { var type = typeof value; return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean') ? (value !== '__proto__') : (value === null); } module.exports = isKeyable; /***/ }, /* 158 */ /***/ function(module, exports, __webpack_require__) { var getMapData = __webpack_require__(156); /** * Gets the map value for `key`. * * @private * @name get * @memberOf MapCache * @param {string} key The key of the value to get. * @returns {*} Returns the entry value. */ function mapCacheGet(key) { return getMapData(this, key).get(key); } module.exports = mapCacheGet; /***/ }, /* 159 */ /***/ function(module, exports, __webpack_require__) { var getMapData = __webpack_require__(156); /** * Checks if a map value for `key` exists. * * @private * @name has * @memberOf MapCache * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function mapCacheHas(key) { return getMapData(this, key).has(key); } module.exports = mapCacheHas; /***/ }, /* 160 */ /***/ function(module, exports, __webpack_require__) { var getMapData = __webpack_require__(156); /** * Sets the map `key` to `value`. * * @private * @name set * @memberOf MapCache * @param {string} key The key of the value to set. * @param {*} value The value to set. * @returns {Object} Returns the map cache instance. */ function mapCacheSet(key, value) { getMapData(this, key).set(key, value); return this; } module.exports = mapCacheSet; /***/ }, /* 161 */ /***/ function(module, exports, __webpack_require__) { var baseIsEqualDeep = __webpack_require__(162), isObject = __webpack_require__(138), isObjectLike = __webpack_require__(187); /** * The base implementation of `_.isEqual` which supports partial comparisons * and tracks traversed objects. * * @private * @param {*} value The value to compare. * @param {*} other The other value to compare. * @param {Function} [customizer] The function to customize comparisons. * @param {boolean} [bitmask] The bitmask of comparison flags. * The bitmask may be composed of the following flags: * 1 - Unordered comparison * 2 - Partial comparison * @param {Object} [stack] Tracks traversed `value` and `other` objects. * @returns {boolean} Returns `true` if the values are equivalent, else `false`. */ function baseIsEqual(value, other, customizer, bitmask, stack) { if (value === other) { return true; } if (value == null || other == null || (!isObject(value) && !isObjectLike(other))) { return value !== value && other !== other; } return baseIsEqualDeep(value, other, baseIsEqual, customizer, bitmask, stack); } module.exports = baseIsEqual; /***/ }, /* 162 */ /***/ function(module, exports, __webpack_require__) { var Stack = __webpack_require__(120), equalArrays = __webpack_require__(163), equalByTag = __webpack_require__(168), equalObjects = __webpack_require__(173), getTag = __webpack_require__(192), isArray = __webpack_require__(188), isHostObject = __webpack_require__(139), isTypedArray = __webpack_require__(198); /** Used to compose bitmasks for comparison styles. */ var PARTIAL_COMPARE_FLAG = 2; /** `Object#toString` result references. */ var argsTag = '[object Arguments]', arrayTag = '[object Array]', objectTag = '[object Object]'; /** Used for built-in method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * A specialized version of `baseIsEqual` for arrays and objects which performs * deep comparisons and tracks traversed objects enabling objects with circular * references to be compared. * * @private * @param {Object} object The object to compare. * @param {Object} other The other object to compare. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Function} [customizer] The function to customize comparisons. * @param {number} [bitmask] The bitmask of comparison flags. See `baseIsEqual` * for more details. * @param {Object} [stack] Tracks traversed `object` and `other` objects. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. */ function baseIsEqualDeep(object, other, equalFunc, customizer, bitmask, stack) { var objIsArr = isArray(object), othIsArr = isArray(other), objTag = arrayTag, othTag = arrayTag; if (!objIsArr) { objTag = getTag(object); objTag = objTag == argsTag ? objectTag : objTag; } if (!othIsArr) { othTag = getTag(other); othTag = othTag == argsTag ? objectTag : othTag; } var objIsObj = objTag == objectTag && !isHostObject(object), othIsObj = othTag == objectTag && !isHostObject(other), isSameTag = objTag == othTag; if (isSameTag && !objIsObj) { stack || (stack = new Stack); return (objIsArr || isTypedArray(object)) ? equalArrays(object, other, equalFunc, customizer, bitmask, stack) : equalByTag(object, other, objTag, equalFunc, customizer, bitmask, stack); } if (!(bitmask & PARTIAL_COMPARE_FLAG)) { var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'), othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__'); if (objIsWrapped || othIsWrapped) { var objUnwrapped = objIsWrapped ? object.value() : object, othUnwrapped = othIsWrapped ? other.value() : other; stack || (stack = new Stack); return equalFunc(objUnwrapped, othUnwrapped, customizer, bitmask, stack); } } if (!isSameTag) { return false; } stack || (stack = new Stack); return equalObjects(object, other, equalFunc, customizer, bitmask, stack); } module.exports = baseIsEqualDeep; /***/ }, /* 163 */ /***/ function(module, exports, __webpack_require__) { var SetCache = __webpack_require__(164), arraySome = __webpack_require__(167); /** Used to compose bitmasks for comparison styles. */ var UNORDERED_COMPARE_FLAG = 1, PARTIAL_COMPARE_FLAG = 2; /** * A specialized version of `baseIsEqualDeep` for arrays with support for * partial deep comparisons. * * @private * @param {Array} array The array to compare. * @param {Array} other The other array to compare. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Function} customizer The function to customize comparisons. * @param {number} bitmask The bitmask of comparison flags. See `baseIsEqual` * for more details. * @param {Object} stack Tracks traversed `array` and `other` objects. * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`. */ function equalArrays(array, other, equalFunc, customizer, bitmask, stack) { var isPartial = bitmask & PARTIAL_COMPARE_FLAG, arrLength = array.length, othLength = other.length; if (arrLength != othLength && !(isPartial && othLength > arrLength)) { return false; } // Assume cyclic values are equal. var stacked = stack.get(array); if (stacked && stack.get(other)) { return stacked == other; } var index = -1, result = true, seen = (bitmask & UNORDERED_COMPARE_FLAG) ? new SetCache : undefined; stack.set(array, other); stack.set(other, array); // Ignore non-index properties. while (++index < arrLength) { var arrValue = array[index], othValue = other[index]; if (customizer) { var compared = isPartial ? customizer(othValue, arrValue, index, other, array, stack) : customizer(arrValue, othValue, index, array, other, stack); } if (compared !== undefined) { if (compared) { continue; } result = false; break; } // Recursively compare arrays (susceptible to call stack limits). if (seen) { if (!arraySome(other, function(othValue, othIndex) { if (!seen.has(othIndex) && (arrValue === othValue || equalFunc(arrValue, othValue, customizer, bitmask, stack))) { return seen.add(othIndex); } })) { result = false; break; } } else if (!( arrValue === othValue || equalFunc(arrValue, othValue, customizer, bitmask, stack) )) { result = false; break; } } stack['delete'](array); return result; } module.exports = equalArrays; /***/ }, /* 164 */ /***/ function(module, exports, __webpack_require__) { var MapCache = __webpack_require__(146), setCacheAdd = __webpack_require__(165), setCacheHas = __webpack_require__(166); /** * * Creates an array cache object to store unique values. * * @private * @constructor * @param {Array} [values] The values to cache. */ function SetCache(values) { var index = -1, length = values ? values.length : 0; this.__data__ = new MapCache; while (++index < length) { this.add(values[index]); } } // Add methods to `SetCache`. SetCache.prototype.add = SetCache.prototype.push = setCacheAdd; SetCache.prototype.has = setCacheHas; module.exports = SetCache; /***/ }, /* 165 */ /***/ function(module, exports) { /** Used to stand-in for `undefined` hash values. */ var HASH_UNDEFINED = '__lodash_hash_undefined__'; /** * Adds `value` to the array cache. * * @private * @name add * @memberOf SetCache * @alias push * @param {*} value The value to cache. * @returns {Object} Returns the cache instance. */ function setCacheAdd(value) { this.__data__.set(value, HASH_UNDEFINED); return this; } module.exports = setCacheAdd; /***/ }, /* 166 */ /***/ function(module, exports) { /** * Checks if `value` is in the array cache. * * @private * @name has * @memberOf SetCache * @param {*} value The value to search for. * @returns {number} Returns `true` if `value` is found, else `false`. */ function setCacheHas(value) { return this.__data__.has(value); } module.exports = setCacheHas; /***/ }, /* 167 */ /***/ function(module, exports) { /** * A specialized version of `_.some` for arrays without support for iteratee * shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} predicate The function invoked per iteration. * @returns {boolean} Returns `true` if any element passes the predicate check, * else `false`. */ function arraySome(array, predicate) { var index = -1, length = array ? array.length : 0; while (++index < length) { if (predicate(array[index], index, array)) { return true; } } return false; } module.exports = arraySome; /***/ }, /* 168 */ /***/ function(module, exports, __webpack_require__) { var Symbol = __webpack_require__(169), Uint8Array = __webpack_require__(170), eq = __webpack_require__(125), equalArrays = __webpack_require__(163), mapToArray = __webpack_require__(171), setToArray = __webpack_require__(172); /** Used to compose bitmasks for comparison styles. */ var UNORDERED_COMPARE_FLAG = 1, PARTIAL_COMPARE_FLAG = 2; /** `Object#toString` result references. */ var boolTag = '[object Boolean]', dateTag = '[object Date]', errorTag = '[object Error]', mapTag = '[object Map]', numberTag = '[object Number]', regexpTag = '[object RegExp]', setTag = '[object Set]', stringTag = '[object String]', symbolTag = '[object Symbol]'; var arrayBufferTag = '[object ArrayBuffer]', dataViewTag = '[object DataView]'; /** Used to convert symbols to primitives and strings. */ var symbolProto = Symbol ? Symbol.prototype : undefined, symbolValueOf = symbolProto ? symbolProto.valueOf : undefined; /** * A specialized version of `baseIsEqualDeep` for comparing objects of * the same `toStringTag`. * * **Note:** This function only supports comparing values with tags of * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`. * * @private * @param {Object} object The object to compare. * @param {Object} other The other object to compare. * @param {string} tag The `toStringTag` of the objects to compare. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Function} customizer The function to customize comparisons. * @param {number} bitmask The bitmask of comparison flags. See `baseIsEqual` * for more details. * @param {Object} stack Tracks traversed `object` and `other` objects. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. */ function equalByTag(object, other, tag, equalFunc, customizer, bitmask, stack) { switch (tag) { case dataViewTag: if ((object.byteLength != other.byteLength) || (object.byteOffset != other.byteOffset)) { return false; } object = object.buffer; other = other.buffer; case arrayBufferTag: if ((object.byteLength != other.byteLength) || !equalFunc(new Uint8Array(object), new Uint8Array(other))) { return false; } return true; case boolTag: case dateTag: case numberTag: // Coerce booleans to `1` or `0` and dates to milliseconds. // Invalid dates are coerced to `NaN`. return eq(+object, +other); case errorTag: return object.name == other.name && object.message == other.message; case regexpTag: case stringTag: // Coerce regexes to strings and treat strings, primitives and objects, // as equal. See http://www.ecma-international.org/ecma-262/6.0/#sec-regexp.prototype.tostring // for more details. return object == (other + ''); case mapTag: var convert = mapToArray; case setTag: var isPartial = bitmask & PARTIAL_COMPARE_FLAG; convert || (convert = setToArray); if (object.size != other.size && !isPartial) { return false; } // Assume cyclic values are equal. var stacked = stack.get(object); if (stacked) { return stacked == other; } bitmask |= UNORDERED_COMPARE_FLAG; // Recursively compare objects (susceptible to call stack limits). stack.set(object, other); var result = equalArrays(convert(object), convert(other), equalFunc, customizer, bitmask, stack); stack['delete'](object); return result; case symbolTag: if (symbolValueOf) { return symbolValueOf.call(object) == symbolValueOf.call(other); } } return false; } module.exports = equalByTag; /***/ }, /* 169 */ /***/ function(module, exports, __webpack_require__) { var root = __webpack_require__(142); /** Built-in value references. */ var Symbol = root.Symbol; module.exports = Symbol; /***/ }, /* 170 */ /***/ function(module, exports, __webpack_require__) { var root = __webpack_require__(142); /** Built-in value references. */ var Uint8Array = root.Uint8Array; module.exports = Uint8Array; /***/ }, /* 171 */ /***/ function(module, exports) { /** * Converts `map` to its key-value pairs. * * @private * @param {Object} map The map to convert. * @returns {Array} Returns the key-value pairs. */ function mapToArray(map) { var index = -1, result = Array(map.size); map.forEach(function(value, key) { result[++index] = [key, value]; }); return result; } module.exports = mapToArray; /***/ }, /* 172 */ /***/ function(module, exports) { /** * Converts `set` to an array of its values. * * @private * @param {Object} set The set to convert. * @returns {Array} Returns the values. */ function setToArray(set) { var index = -1, result = Array(set.size); set.forEach(function(value) { result[++index] = value; }); return result; } module.exports = setToArray; /***/ }, /* 173 */ /***/ function(module, exports, __webpack_require__) { var baseHas = __webpack_require__(174), keys = __webpack_require__(177); /** Used to compose bitmasks for comparison styles. */ var PARTIAL_COMPARE_FLAG = 2; /** * A specialized version of `baseIsEqualDeep` for objects with support for * partial deep comparisons. * * @private * @param {Object} object The object to compare. * @param {Object} other The other object to compare. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Function} customizer The function to customize comparisons. * @param {number} bitmask The bitmask of comparison flags. See `baseIsEqual` * for more details. * @param {Object} stack Tracks traversed `object` and `other` objects. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. */ function equalObjects(object, other, equalFunc, customizer, bitmask, stack) { var isPartial = bitmask & PARTIAL_COMPARE_FLAG, objProps = keys(object), objLength = objProps.length, othProps = keys(other), othLength = othProps.length; if (objLength != othLength && !isPartial) { return false; } var index = objLength; while (index--) { var key = objProps[index]; if (!(isPartial ? key in other : baseHas(other, key))) { return false; } } // Assume cyclic values are equal. var stacked = stack.get(object); if (stacked && stack.get(other)) { return stacked == other; } var result = true; stack.set(object, other); stack.set(other, object); var skipCtor = isPartial; while (++index < objLength) { key = objProps[index]; var objValue = object[key], othValue = other[key]; if (customizer) { var compared = isPartial ? customizer(othValue, objValue, key, other, object, stack) : customizer(objValue, othValue, key, object, other, stack); } // Recursively compare objects (susceptible to call stack limits). if (!(compared === undefined ? (objValue === othValue || equalFunc(objValue, othValue, customizer, bitmask, stack)) : compared )) { result = false; break; } skipCtor || (skipCtor = key == 'constructor'); } if (result && !skipCtor) { var objCtor = object.constructor, othCtor = other.constructor; // Non `Object` object instances with different constructors are not equal. if (objCtor != othCtor && ('constructor' in object && 'constructor' in other) && !(typeof objCtor == 'function' && objCtor instanceof objCtor && typeof othCtor == 'function' && othCtor instanceof othCtor)) { result = false; } } stack['delete'](object); return result; } module.exports = equalObjects; /***/ }, /* 174 */ /***/ function(module, exports, __webpack_require__) { var getPrototype = __webpack_require__(175); /** Used for built-in method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * The base implementation of `_.has` without support for deep paths. * * @private * @param {Object} [object] The object to query. * @param {Array|string} key The key to check. * @returns {boolean} Returns `true` if `key` exists, else `false`. */ function baseHas(object, key) { // Avoid a bug in IE 10-11 where objects with a [[Prototype]] of `null`, // that are composed entirely of index properties, return `false` for // `hasOwnProperty` checks of them. return object != null && (hasOwnProperty.call(object, key) || (typeof object == 'object' && key in object && getPrototype(object) === null)); } module.exports = baseHas; /***/ }, /* 175 */ /***/ function(module, exports, __webpack_require__) { var overArg = __webpack_require__(176); /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeGetPrototype = Object.getPrototypeOf; /** * Gets the `[[Prototype]]` of `value`. * * @private * @param {*} value The value to query. * @returns {null|Object} Returns the `[[Prototype]]`. */ var getPrototype = overArg(nativeGetPrototype, Object); module.exports = getPrototype; /***/ }, /* 176 */ /***/ function(module, exports) { /** * Creates a function that invokes `func` with its first argument transformed. * * @private * @param {Function} func The function to wrap. * @param {Function} transform The argument transform. * @returns {Function} Returns the new function. */ function overArg(func, transform) { return function(arg) { return func(transform(arg)); }; } module.exports = overArg; /***/ }, /* 177 */ /***/ function(module, exports, __webpack_require__) { var baseHas = __webpack_require__(174), baseKeys = __webpack_require__(178), indexKeys = __webpack_require__(179), isArrayLike = __webpack_require__(183), isIndex = __webpack_require__(190), isPrototype = __webpack_require__(191); /** * Creates an array of the own enumerable property names of `object`. * * **Note:** Non-object values are coerced to objects. See the * [ES spec](http://ecma-international.org/ecma-262/6.0/#sec-object.keys) * for more details. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.keys(new Foo); * // => ['a', 'b'] (iteration order is not guaranteed) * * _.keys('hi'); * // => ['0', '1'] */ function keys(object) { var isProto = isPrototype(object); if (!(isProto || isArrayLike(object))) { return baseKeys(object); } var indexes = indexKeys(object), skipIndexes = !!indexes, result = indexes || [], length = result.length; for (var key in object) { if (baseHas(object, key) && !(skipIndexes && (key == 'length' || isIndex(key, length))) && !(isProto && key == 'constructor')) { result.push(key); } } return result; } module.exports = keys; /***/ }, /* 178 */ /***/ function(module, exports, __webpack_require__) { var overArg = __webpack_require__(176); /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeKeys = Object.keys; /** * The base implementation of `_.keys` which doesn't skip the constructor * property of prototypes or treat sparse arrays as dense. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. */ var baseKeys = overArg(nativeKeys, Object); module.exports = baseKeys; /***/ }, /* 179 */ /***/ function(module, exports, __webpack_require__) { var baseTimes = __webpack_require__(180), isArguments = __webpack_require__(181), isArray = __webpack_require__(188), isLength = __webpack_require__(186), isString = __webpack_require__(189); /** * Creates an array of index keys for `object` values of arrays, * `arguments` objects, and strings, otherwise `null` is returned. * * @private * @param {Object} object The object to query. * @returns {Array|null} Returns index keys, else `null`. */ function indexKeys(object) { var length = object ? object.length : undefined; if (isLength(length) && (isArray(object) || isString(object) || isArguments(object))) { return baseTimes(length, String); } return null; } module.exports = indexKeys; /***/ }, /* 180 */ /***/ function(module, exports) { /** * The base implementation of `_.times` without support for iteratee shorthands * or max array length checks. * * @private * @param {number} n The number of times to invoke `iteratee`. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns the array of results. */ function baseTimes(n, iteratee) { var index = -1, result = Array(n); while (++index < n) { result[index] = iteratee(index); } return result; } module.exports = baseTimes; /***/ }, /* 181 */ /***/ function(module, exports, __webpack_require__) { var isArrayLikeObject = __webpack_require__(182); /** `Object#toString` result references. */ var argsTag = '[object Arguments]'; /** Used for built-in method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * Used to resolve the * [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring) * of values. */ var objectToString = objectProto.toString; /** Built-in value references. */ var propertyIsEnumerable = objectProto.propertyIsEnumerable; /** * Checks if `value` is likely an `arguments` object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an `arguments` object, * else `false`. * @example * * _.isArguments(function() { return arguments; }()); * // => true * * _.isArguments([1, 2, 3]); * // => false */ function isArguments(value) { // Safari 8.1 incorrectly makes `arguments.callee` enumerable in strict mode. return isArrayLikeObject(value) && hasOwnProperty.call(value, 'callee') && (!propertyIsEnumerable.call(value, 'callee') || objectToString.call(value) == argsTag); } module.exports = isArguments; /***/ }, /* 182 */ /***/ function(module, exports, __webpack_require__) { var isArrayLike = __webpack_require__(183), isObjectLike = __webpack_require__(187); /** * This method is like `_.isArrayLike` except that it also checks if `value` * is an object. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an array-like object, * else `false`. * @example * * _.isArrayLikeObject([1, 2, 3]); * // => true * * _.isArrayLikeObject(document.body.children); * // => true * * _.isArrayLikeObject('abc'); * // => false * * _.isArrayLikeObject(_.noop); * // => false */ function isArrayLikeObject(value) { return isObjectLike(value) && isArrayLike(value); } module.exports = isArrayLikeObject; /***/ }, /* 183 */ /***/ function(module, exports, __webpack_require__) { var getLength = __webpack_require__(184), isFunction = __webpack_require__(137), isLength = __webpack_require__(186); /** * Checks if `value` is array-like. A value is considered array-like if it's * not a function and has a `value.length` that's an integer greater than or * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is array-like, else `false`. * @example * * _.isArrayLike([1, 2, 3]); * // => true * * _.isArrayLike(document.body.children); * // => true * * _.isArrayLike('abc'); * // => true * * _.isArrayLike(_.noop); * // => false */ function isArrayLike(value) { return value != null && isLength(getLength(value)) && !isFunction(value); } module.exports = isArrayLike; /***/ }, /* 184 */ /***/ function(module, exports, __webpack_require__) { var baseProperty = __webpack_require__(185); /** * Gets the "length" property value of `object`. * * **Note:** This function is used to avoid a * [JIT bug](https://bugs.webkit.org/show_bug.cgi?id=142792) that affects * Safari on at least iOS 8.1-8.3 ARM64. * * @private * @param {Object} object The object to query. * @returns {*} Returns the "length" value. */ var getLength = baseProperty('length'); module.exports = getLength; /***/ }, /* 185 */ /***/ function(module, exports) { /** * The base implementation of `_.property` without support for deep paths. * * @private * @param {string} key The key of the property to get. * @returns {Function} Returns the new accessor function. */ function baseProperty(key) { return function(object) { return object == null ? undefined : object[key]; }; } module.exports = baseProperty; /***/ }, /* 186 */ /***/ function(module, exports) { /** Used as references for various `Number` constants. */ var MAX_SAFE_INTEGER = 9007199254740991; /** * Checks if `value` is a valid array-like length. * * **Note:** This function is loosely based on * [`ToLength`](http://ecma-international.org/ecma-262/6.0/#sec-tolength). * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a valid length, * else `false`. * @example * * _.isLength(3); * // => true * * _.isLength(Number.MIN_VALUE); * // => false * * _.isLength(Infinity); * // => false * * _.isLength('3'); * // => false */ function isLength(value) { return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; } module.exports = isLength; /***/ }, /* 187 */ /***/ function(module, exports) { /** * Checks if `value` is object-like. A value is object-like if it's not `null` * and has a `typeof` result of "object". * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is object-like, else `false`. * @example * * _.isObjectLike({}); * // => true * * _.isObjectLike([1, 2, 3]); * // => true * * _.isObjectLike(_.noop); * // => false * * _.isObjectLike(null); * // => false */ function isObjectLike(value) { return !!value && typeof value == 'object'; } module.exports = isObjectLike; /***/ }, /* 188 */ /***/ function(module, exports) { /** * Checks if `value` is classified as an `Array` object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an array, else `false`. * @example * * _.isArray([1, 2, 3]); * // => true * * _.isArray(document.body.children); * // => false * * _.isArray('abc'); * // => false * * _.isArray(_.noop); * // => false */ var isArray = Array.isArray; module.exports = isArray; /***/ }, /* 189 */ /***/ function(module, exports, __webpack_require__) { var isArray = __webpack_require__(188), isObjectLike = __webpack_require__(187); /** `Object#toString` result references. */ var stringTag = '[object String]'; /** Used for built-in method references. */ var objectProto = Object.prototype; /** * Used to resolve the * [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring) * of values. */ var objectToString = objectProto.toString; /** * Checks if `value` is classified as a `String` primitive or object. * * @static * @since 0.1.0 * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a string, else `false`. * @example * * _.isString('abc'); * // => true * * _.isString(1); * // => false */ function isString(value) { return typeof value == 'string' || (!isArray(value) && isObjectLike(value) && objectToString.call(value) == stringTag); } module.exports = isString; /***/ }, /* 190 */ /***/ function(module, exports) { /** Used as references for various `Number` constants. */ var MAX_SAFE_INTEGER = 9007199254740991; /** Used to detect unsigned integer values. */ var reIsUint = /^(?:0|[1-9]\d*)$/; /** * Checks if `value` is a valid array-like index. * * @private * @param {*} value The value to check. * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. */ function isIndex(value, length) { length = length == null ? MAX_SAFE_INTEGER : length; return !!length && (typeof value == 'number' || reIsUint.test(value)) && (value > -1 && value % 1 == 0 && value < length); } module.exports = isIndex; /***/ }, /* 191 */ /***/ function(module, exports) { /** Used for built-in method references. */ var objectProto = Object.prototype; /** * Checks if `value` is likely a prototype object. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a prototype, else `false`. */ function isPrototype(value) { var Ctor = value && value.constructor, proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto; return value === proto; } module.exports = isPrototype; /***/ }, /* 192 */ /***/ function(module, exports, __webpack_require__) { var DataView = __webpack_require__(193), Map = __webpack_require__(134), Promise = __webpack_require__(194), Set = __webpack_require__(195), WeakMap = __webpack_require__(196), baseGetTag = __webpack_require__(197), toSource = __webpack_require__(144); /** `Object#toString` result references. */ var mapTag = '[object Map]', objectTag = '[object Object]', promiseTag = '[object Promise]', setTag = '[object Set]', weakMapTag = '[object WeakMap]'; var dataViewTag = '[object DataView]'; /** Used for built-in method references. */ var objectProto = Object.prototype; /** * Used to resolve the * [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring) * of values. */ var objectToString = objectProto.toString; /** Used to detect maps, sets, and weakmaps. */ var dataViewCtorString = toSource(DataView), mapCtorString = toSource(Map), promiseCtorString = toSource(Promise), setCtorString = toSource(Set), weakMapCtorString = toSource(WeakMap); /** * Gets the `toStringTag` of `value`. * * @private * @param {*} value The value to query. * @returns {string} Returns the `toStringTag`. */ var getTag = baseGetTag; // Fallback for data views, maps, sets, and weak maps in IE 11, // for data views in Edge, and promises in Node.js. if ((DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag) || (Map && getTag(new Map) != mapTag) || (Promise && getTag(Promise.resolve()) != promiseTag) || (Set && getTag(new Set) != setTag) || (WeakMap && getTag(new WeakMap) != weakMapTag)) { getTag = function(value) { var result = objectToString.call(value), Ctor = result == objectTag ? value.constructor : undefined, ctorString = Ctor ? toSource(Ctor) : undefined; if (ctorString) { switch (ctorString) { case dataViewCtorString: return dataViewTag; case mapCtorString: return mapTag; case promiseCtorString: return promiseTag; case setCtorString: return setTag; case weakMapCtorString: return weakMapTag; } } return result; }; } module.exports = getTag; /***/ }, /* 193 */ /***/ function(module, exports, __webpack_require__) { var getNative = __webpack_require__(135), root = __webpack_require__(142); /* Built-in method references that are verified to be native. */ var DataView = getNative(root, 'DataView'); module.exports = DataView; /***/ }, /* 194 */ /***/ function(module, exports, __webpack_require__) { var getNative = __webpack_require__(135), root = __webpack_require__(142); /* Built-in method references that are verified to be native. */ var Promise = getNative(root, 'Promise'); module.exports = Promise; /***/ }, /* 195 */ /***/ function(module, exports, __webpack_require__) { var getNative = __webpack_require__(135), root = __webpack_require__(142); /* Built-in method references that are verified to be native. */ var Set = getNative(root, 'Set'); module.exports = Set; /***/ }, /* 196 */ /***/ function(module, exports, __webpack_require__) { var getNative = __webpack_require__(135), root = __webpack_require__(142); /* Built-in method references that are verified to be native. */ var WeakMap = getNative(root, 'WeakMap'); module.exports = WeakMap; /***/ }, /* 197 */ /***/ function(module, exports) { /** Used for built-in method references. */ var objectProto = Object.prototype; /** * Used to resolve the * [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring) * of values. */ var objectToString = objectProto.toString; /** * The base implementation of `getTag`. * * @private * @param {*} value The value to query. * @returns {string} Returns the `toStringTag`. */ function baseGetTag(value) { return objectToString.call(value); } module.exports = baseGetTag; /***/ }, /* 198 */ /***/ function(module, exports, __webpack_require__) { var baseIsTypedArray = __webpack_require__(199), baseUnary = __webpack_require__(200), nodeUtil = __webpack_require__(201); /* Node.js helper references. */ var nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray; /** * Checks if `value` is classified as a typed array. * * @static * @memberOf _ * @since 3.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. * @example * * _.isTypedArray(new Uint8Array); * // => true * * _.isTypedArray([]); * // => false */ var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray; module.exports = isTypedArray; /***/ }, /* 199 */ /***/ function(module, exports, __webpack_require__) { var isLength = __webpack_require__(186), isObjectLike = __webpack_require__(187); /** `Object#toString` result references. */ var argsTag = '[object Arguments]', arrayTag = '[object Array]', boolTag = '[object Boolean]', dateTag = '[object Date]', errorTag = '[object Error]', funcTag = '[object Function]', mapTag = '[object Map]', numberTag = '[object Number]', objectTag = '[object Object]', regexpTag = '[object RegExp]', setTag = '[object Set]', stringTag = '[object String]', weakMapTag = '[object WeakMap]'; var arrayBufferTag = '[object ArrayBuffer]', dataViewTag = '[object DataView]', float32Tag = '[object Float32Array]', float64Tag = '[object Float64Array]', int8Tag = '[object Int8Array]', int16Tag = '[object Int16Array]', int32Tag = '[object Int32Array]', uint8Tag = '[object Uint8Array]', uint8ClampedTag = '[object Uint8ClampedArray]', uint16Tag = '[object Uint16Array]', uint32Tag = '[object Uint32Array]'; /** Used to identify `toStringTag` values of typed arrays. */ var typedArrayTags = {}; typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = typedArrayTags[uint32Tag] = true; typedArrayTags[argsTag] = typedArrayTags[arrayTag] = typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = typedArrayTags[dataViewTag] = typedArrayTags[dateTag] = typedArrayTags[errorTag] = typedArrayTags[funcTag] = typedArrayTags[mapTag] = typedArrayTags[numberTag] = typedArrayTags[objectTag] = typedArrayTags[regexpTag] = typedArrayTags[setTag] = typedArrayTags[stringTag] = typedArrayTags[weakMapTag] = false; /** Used for built-in method references. */ var objectProto = Object.prototype; /** * Used to resolve the * [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring) * of values. */ var objectToString = objectProto.toString; /** * The base implementation of `_.isTypedArray` without Node.js optimizations. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. */ function baseIsTypedArray(value) { return isObjectLike(value) && isLength(value.length) && !!typedArrayTags[objectToString.call(value)]; } module.exports = baseIsTypedArray; /***/ }, /* 200 */ /***/ function(module, exports) { /** * The base implementation of `_.unary` without support for storing metadata. * * @private * @param {Function} func The function to cap arguments for. * @returns {Function} Returns the new capped function. */ function baseUnary(func) { return function(value) { return func(value); }; } module.exports = baseUnary; /***/ }, /* 201 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(module) {var freeGlobal = __webpack_require__(143); /** Detect free variable `exports`. */ var freeExports = freeGlobal && typeof exports == 'object' && exports; /** Detect free variable `module`. */ var freeModule = freeExports && typeof module == 'object' && module; /** Detect the popular CommonJS extension `module.exports`. */ var moduleExports = freeModule && freeModule.exports === freeExports; /** Detect free variable `process` from Node.js. */ var freeProcess = moduleExports && freeGlobal.process; /** Used to access faster Node.js helpers. */ var nodeUtil = (function() { try { return freeProcess && freeProcess.binding('util'); } catch (e) {} }()); module.exports = nodeUtil; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(202)(module))) /***/ }, /* 202 */ /***/ function(module, exports) { module.exports = function(module) { if(!module.webpackPolyfill) { module.deprecate = function() {}; module.paths = []; // module.parent = undefined by default module.children = []; module.webpackPolyfill = 1; } return module; } /***/ }, /* 203 */ /***/ function(module, exports, __webpack_require__) { var isStrictComparable = __webpack_require__(204), keys = __webpack_require__(177); /** * Gets the property names, values, and compare flags of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the match data of `object`. */ function getMatchData(object) { var result = keys(object), length = result.length; while (length--) { var key = result[length], value = object[key]; result[length] = [key, value, isStrictComparable(value)]; } return result; } module.exports = getMatchData; /***/ }, /* 204 */ /***/ function(module, exports, __webpack_require__) { var isObject = __webpack_require__(138); /** * Checks if `value` is suitable for strict equality comparisons, i.e. `===`. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` if suitable for strict * equality comparisons, else `false`. */ function isStrictComparable(value) { return value === value && !isObject(value); } module.exports = isStrictComparable; /***/ }, /* 205 */ /***/ function(module, exports) { /** * A specialized version of `matchesProperty` for source values suitable * for strict equality comparisons, i.e. `===`. * * @private * @param {string} key The key of the property to get. * @param {*} srcValue The value to match. * @returns {Function} Returns the new spec function. */ function matchesStrictComparable(key, srcValue) { return function(object) { if (object == null) { return false; } return object[key] === srcValue && (srcValue !== undefined || (key in Object(object))); }; } module.exports = matchesStrictComparable; /***/ }, /* 206 */ /***/ function(module, exports, __webpack_require__) { var baseIsEqual = __webpack_require__(161), get = __webpack_require__(207), hasIn = __webpack_require__(217), isKey = __webpack_require__(215), isStrictComparable = __webpack_require__(204), matchesStrictComparable = __webpack_require__(205), toKey = __webpack_require__(216); /** Used to compose bitmasks for comparison styles. */ var UNORDERED_COMPARE_FLAG = 1, PARTIAL_COMPARE_FLAG = 2; /** * The base implementation of `_.matchesProperty` which doesn't clone `srcValue`. * * @private * @param {string} path The path of the property to get. * @param {*} srcValue The value to match. * @returns {Function} Returns the new spec function. */ function baseMatchesProperty(path, srcValue) { if (isKey(path) && isStrictComparable(srcValue)) { return matchesStrictComparable(toKey(path), srcValue); } return function(object) { var objValue = get(object, path); return (objValue === undefined && objValue === srcValue) ? hasIn(object, path) : baseIsEqual(srcValue, objValue, undefined, UNORDERED_COMPARE_FLAG | PARTIAL_COMPARE_FLAG); }; } module.exports = baseMatchesProperty; /***/ }, /* 207 */ /***/ function(module, exports, __webpack_require__) { var baseGet = __webpack_require__(208); /** * Gets the value at `path` of `object`. If the resolved value is * `undefined`, the `defaultValue` is returned in its place. * * @static * @memberOf _ * @since 3.7.0 * @category Object * @param {Object} object The object to query. * @param {Array|string} path The path of the property to get. * @param {*} [defaultValue] The value returned for `undefined` resolved values. * @returns {*} Returns the resolved value. * @example * * var object = { 'a': [{ 'b': { 'c': 3 } }] }; * * _.get(object, 'a[0].b.c'); * // => 3 * * _.get(object, ['a', '0', 'b', 'c']); * // => 3 * * _.get(object, 'a.b.c', 'default'); * // => 'default' */ function get(object, path, defaultValue) { var result = object == null ? undefined : baseGet(object, path); return result === undefined ? defaultValue : result; } module.exports = get; /***/ }, /* 208 */ /***/ function(module, exports, __webpack_require__) { var castPath = __webpack_require__(209), isKey = __webpack_require__(215), toKey = __webpack_require__(216); /** * The base implementation of `_.get` without support for default values. * * @private * @param {Object} object The object to query. * @param {Array|string} path The path of the property to get. * @returns {*} Returns the resolved value. */ function baseGet(object, path) { path = isKey(path, object) ? [path] : castPath(path); var index = 0, length = path.length; while (object != null && index < length) { object = object[toKey(path[index++])]; } return (index && index == length) ? object : undefined; } module.exports = baseGet; /***/ }, /* 209 */ /***/ function(module, exports, __webpack_require__) { var isArray = __webpack_require__(188), stringToPath = __webpack_require__(210); /** * Casts `value` to a path array if it's not one. * * @private * @param {*} value The value to inspect. * @returns {Array} Returns the cast property path array. */ function castPath(value) { return isArray(value) ? value : stringToPath(value); } module.exports = castPath; /***/ }, /* 210 */ /***/ function(module, exports, __webpack_require__) { var memoize = __webpack_require__(211), toString = __webpack_require__(212); /** Used to match property names within property paths. */ var rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(\.|\[\])(?:\4|$))/g; /** Used to match backslashes in property paths. */ var reEscapeChar = /\\(\\)?/g; /** * Converts `string` to a property path array. * * @private * @param {string} string The string to convert. * @returns {Array} Returns the property path array. */ var stringToPath = memoize(function(string) { var result = []; toString(string).replace(rePropName, function(match, number, quote, string) { result.push(quote ? string.replace(reEscapeChar, '$1') : (number || match)); }); return result; }); module.exports = stringToPath; /***/ }, /* 211 */ /***/ function(module, exports, __webpack_require__) { var MapCache = __webpack_require__(146); /** Used as the `TypeError` message for "Functions" methods. */ var FUNC_ERROR_TEXT = 'Expected a function'; /** * Creates a function that memoizes the result of `func`. If `resolver` is * provided, it determines the cache key for storing the result based on the * arguments provided to the memoized function. By default, the first argument * provided to the memoized function is used as the map cache key. The `func` * is invoked with the `this` binding of the memoized function. * * **Note:** The cache is exposed as the `cache` property on the memoized * function. Its creation may be customized by replacing the `_.memoize.Cache` * constructor with one whose instances implement the * [`Map`](http://ecma-international.org/ecma-262/6.0/#sec-properties-of-the-map-prototype-object) * method interface of `delete`, `get`, `has`, and `set`. * * @static * @memberOf _ * @since 0.1.0 * @category Function * @param {Function} func The function to have its output memoized. * @param {Function} [resolver] The function to resolve the cache key. * @returns {Function} Returns the new memoized function. * @example * * var object = { 'a': 1, 'b': 2 }; * var other = { 'c': 3, 'd': 4 }; * * var values = _.memoize(_.values); * values(object); * // => [1, 2] * * values(other); * // => [3, 4] * * object.a = 2; * values(object); * // => [1, 2] * * // Modify the result cache. * values.cache.set(object, ['a', 'b']); * values(object); * // => ['a', 'b'] * * // Replace `_.memoize.Cache`. * _.memoize.Cache = WeakMap; */ function memoize(func, resolver) { if (typeof func != 'function' || (resolver && typeof resolver != 'function')) { throw new TypeError(FUNC_ERROR_TEXT); } var memoized = function() { var args = arguments, key = resolver ? resolver.apply(this, args) : args[0], cache = memoized.cache; if (cache.has(key)) { return cache.get(key); } var result = func.apply(this, args); memoized.cache = cache.set(key, result); return result; }; memoized.cache = new (memoize.Cache || MapCache); return memoized; } // Assign cache to `_.memoize`. memoize.Cache = MapCache; module.exports = memoize; /***/ }, /* 212 */ /***/ function(module, exports, __webpack_require__) { var baseToString = __webpack_require__(213); /** * Converts `value` to a string. An empty string is returned for `null` * and `undefined` values. The sign of `-0` is preserved. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to process. * @returns {string} Returns the string. * @example * * _.toString(null); * // => '' * * _.toString(-0); * // => '-0' * * _.toString([1, 2, 3]); * // => '1,2,3' */ function toString(value) { return value == null ? '' : baseToString(value); } module.exports = toString; /***/ }, /* 213 */ /***/ function(module, exports, __webpack_require__) { var Symbol = __webpack_require__(169), isSymbol = __webpack_require__(214); /** Used as references for various `Number` constants. */ var INFINITY = 1 / 0; /** Used to convert symbols to primitives and strings. */ var symbolProto = Symbol ? Symbol.prototype : undefined, symbolToString = symbolProto ? symbolProto.toString : undefined; /** * The base implementation of `_.toString` which doesn't convert nullish * values to empty strings. * * @private * @param {*} value The value to process. * @returns {string} Returns the string. */ function baseToString(value) { // Exit early for strings to avoid a performance hit in some environments. if (typeof value == 'string') { return value; } if (isSymbol(value)) { return symbolToString ? symbolToString.call(value) : ''; } var result = (value + ''); return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; } module.exports = baseToString; /***/ }, /* 214 */ /***/ function(module, exports, __webpack_require__) { var isObjectLike = __webpack_require__(187); /** `Object#toString` result references. */ var symbolTag = '[object Symbol]'; /** Used for built-in method references. */ var objectProto = Object.prototype; /** * Used to resolve the * [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring) * of values. */ var objectToString = objectProto.toString; /** * Checks if `value` is classified as a `Symbol` primitive or object. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a symbol, else `false`. * @example * * _.isSymbol(Symbol.iterator); * // => true * * _.isSymbol('abc'); * // => false */ function isSymbol(value) { return typeof value == 'symbol' || (isObjectLike(value) && objectToString.call(value) == symbolTag); } module.exports = isSymbol; /***/ }, /* 215 */ /***/ function(module, exports, __webpack_require__) { var isArray = __webpack_require__(188), isSymbol = __webpack_require__(214); /** Used to match property names within property paths. */ var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/, reIsPlainProp = /^\w*$/; /** * Checks if `value` is a property name and not a property path. * * @private * @param {*} value The value to check. * @param {Object} [object] The object to query keys on. * @returns {boolean} Returns `true` if `value` is a property name, else `false`. */ function isKey(value, object) { if (isArray(value)) { return false; } var type = typeof value; if (type == 'number' || type == 'symbol' || type == 'boolean' || value == null || isSymbol(value)) { return true; } return reIsPlainProp.test(value) || !reIsDeepProp.test(value) || (object != null && value in Object(object)); } module.exports = isKey; /***/ }, /* 216 */ /***/ function(module, exports, __webpack_require__) { var isSymbol = __webpack_require__(214); /** Used as references for various `Number` constants. */ var INFINITY = 1 / 0; /** * Converts `value` to a string key if it's not a string or symbol. * * @private * @param {*} value The value to inspect. * @returns {string|symbol} Returns the key. */ function toKey(value) { if (typeof value == 'string' || isSymbol(value)) { return value; } var result = (value + ''); return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; } module.exports = toKey; /***/ }, /* 217 */ /***/ function(module, exports, __webpack_require__) { var baseHasIn = __webpack_require__(218), hasPath = __webpack_require__(219); /** * Checks if `path` is a direct or inherited property of `object`. * * @static * @memberOf _ * @since 4.0.0 * @category Object * @param {Object} object The object to query. * @param {Array|string} path The path to check. * @returns {boolean} Returns `true` if `path` exists, else `false`. * @example * * var object = _.create({ 'a': _.create({ 'b': 2 }) }); * * _.hasIn(object, 'a'); * // => true * * _.hasIn(object, 'a.b'); * // => true * * _.hasIn(object, ['a', 'b']); * // => true * * _.hasIn(object, 'b'); * // => false */ function hasIn(object, path) { return object != null && hasPath(object, path, baseHasIn); } module.exports = hasIn; /***/ }, /* 218 */ /***/ function(module, exports) { /** * The base implementation of `_.hasIn` without support for deep paths. * * @private * @param {Object} [object] The object to query. * @param {Array|string} key The key to check. * @returns {boolean} Returns `true` if `key` exists, else `false`. */ function baseHasIn(object, key) { return object != null && key in Object(object); } module.exports = baseHasIn; /***/ }, /* 219 */ /***/ function(module, exports, __webpack_require__) { var castPath = __webpack_require__(209), isArguments = __webpack_require__(181), isArray = __webpack_require__(188), isIndex = __webpack_require__(190), isKey = __webpack_require__(215), isLength = __webpack_require__(186), isString = __webpack_require__(189), toKey = __webpack_require__(216); /** * Checks if `path` exists on `object`. * * @private * @param {Object} object The object to query. * @param {Array|string} path The path to check. * @param {Function} hasFunc The function to check properties. * @returns {boolean} Returns `true` if `path` exists, else `false`. */ function hasPath(object, path, hasFunc) { path = isKey(path, object) ? [path] : castPath(path); var result, index = -1, length = path.length; while (++index < length) { var key = toKey(path[index]); if (!(result = object != null && hasFunc(object, key))) { break; } object = object[key]; } if (result) { return result; } var length = object ? object.length : 0; return !!length && isLength(length) && isIndex(key, length) && (isArray(object) || isString(object) || isArguments(object)); } module.exports = hasPath; /***/ }, /* 220 */ /***/ function(module, exports) { /** * This method returns the first argument it receives. * * @static * @since 0.1.0 * @memberOf _ * @category Util * @param {*} value Any value. * @returns {*} Returns `value`. * @example * * var object = { 'a': 1 }; * * console.log(_.identity(object) === object); * // => true */ function identity(value) { return value; } module.exports = identity; /***/ }, /* 221 */ /***/ function(module, exports, __webpack_require__) { var baseProperty = __webpack_require__(185), basePropertyDeep = __webpack_require__(222), isKey = __webpack_require__(215), toKey = __webpack_require__(216); /** * Creates a function that returns the value at `path` of a given object. * * @static * @memberOf _ * @since 2.4.0 * @category Util * @param {Array|string} path The path of the property to get. * @returns {Function} Returns the new accessor function. * @example * * var objects = [ * { 'a': { 'b': 2 } }, * { 'a': { 'b': 1 } } * ]; * * _.map(objects, _.property('a.b')); * // => [2, 1] * * _.map(_.sortBy(objects, _.property(['a', 'b'])), 'a.b'); * // => [1, 2] */ function property(path) { return isKey(path) ? baseProperty(toKey(path)) : basePropertyDeep(path); } module.exports = property; /***/ }, /* 222 */ /***/ function(module, exports, __webpack_require__) { var baseGet = __webpack_require__(208); /** * A specialized version of `baseProperty` which supports deep paths. * * @private * @param {Array|string} path The path of the property to get. * @returns {Function} Returns the new accessor function. */ function basePropertyDeep(path) { return function(object) { return baseGet(object, path); }; } module.exports = basePropertyDeep; /***/ }, /* 223 */ /***/ function(module, exports, __webpack_require__) { var baseFindIndex = __webpack_require__(224), baseIteratee = __webpack_require__(117), toInteger = __webpack_require__(225); /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeMax = Math.max; /** * This method is like `_.find` except that it returns the index of the first * element `predicate` returns truthy for instead of the element itself. * * @static * @memberOf _ * @since 1.1.0 * @category Array * @param {Array} array The array to search. * @param {Function} [predicate=_.identity] * The function invoked per iteration. * @param {number} [fromIndex=0] The index to search from. * @returns {number} Returns the index of the found element, else `-1`. * @example * * var users = [ * { 'user': 'barney', 'active': false }, * { 'user': 'fred', 'active': false }, * { 'user': 'pebbles', 'active': true } * ]; * * _.findIndex(users, function(o) { return o.user == 'barney'; }); * // => 0 * * // The `_.matches` iteratee shorthand. * _.findIndex(users, { 'user': 'fred', 'active': false }); * // => 1 * * // The `_.matchesProperty` iteratee shorthand. * _.findIndex(users, ['active', false]); * // => 0 * * // The `_.property` iteratee shorthand. * _.findIndex(users, 'active'); * // => 2 */ function findIndex(array, predicate, fromIndex) { var length = array ? array.length : 0; if (!length) { return -1; } var index = fromIndex == null ? 0 : toInteger(fromIndex); if (index < 0) { index = nativeMax(length + index, 0); } return baseFindIndex(array, baseIteratee(predicate, 3), index); } module.exports = findIndex; /***/ }, /* 224 */ /***/ function(module, exports) { /** * The base implementation of `_.findIndex` and `_.findLastIndex` without * support for iteratee shorthands. * * @private * @param {Array} array The array to search. * @param {Function} predicate The function invoked per iteration. * @param {number} fromIndex The index to search from. * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {number} Returns the index of the matched value, else `-1`. */ function baseFindIndex(array, predicate, fromIndex, fromRight) { var length = array.length, index = fromIndex + (fromRight ? 1 : -1); while ((fromRight ? index-- : ++index < length)) { if (predicate(array[index], index, array)) { return index; } } return -1; } module.exports = baseFindIndex; /***/ }, /* 225 */ /***/ function(module, exports, __webpack_require__) { var toFinite = __webpack_require__(226); /** * Converts `value` to an integer. * * **Note:** This method is loosely based on * [`ToInteger`](http://www.ecma-international.org/ecma-262/6.0/#sec-tointeger). * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to convert. * @returns {number} Returns the converted integer. * @example * * _.toInteger(3.2); * // => 3 * * _.toInteger(Number.MIN_VALUE); * // => 0 * * _.toInteger(Infinity); * // => 1.7976931348623157e+308 * * _.toInteger('3.2'); * // => 3 */ function toInteger(value) { var result = toFinite(value), remainder = result % 1; return result === result ? (remainder ? result - remainder : result) : 0; } module.exports = toInteger; /***/ }, /* 226 */ /***/ function(module, exports, __webpack_require__) { var toNumber = __webpack_require__(227); /** Used as references for various `Number` constants. */ var INFINITY = 1 / 0, MAX_INTEGER = 1.7976931348623157e+308; /** * Converts `value` to a finite number. * * @static * @memberOf _ * @since 4.12.0 * @category Lang * @param {*} value The value to convert. * @returns {number} Returns the converted number. * @example * * _.toFinite(3.2); * // => 3.2 * * _.toFinite(Number.MIN_VALUE); * // => 5e-324 * * _.toFinite(Infinity); * // => 1.7976931348623157e+308 * * _.toFinite('3.2'); * // => 3.2 */ function toFinite(value) { if (!value) { return value === 0 ? value : 0; } value = toNumber(value); if (value === INFINITY || value === -INFINITY) { var sign = (value < 0 ? -1 : 1); return sign * MAX_INTEGER; } return value === value ? value : 0; } module.exports = toFinite; /***/ }, /* 227 */ /***/ function(module, exports, __webpack_require__) { var isFunction = __webpack_require__(137), isObject = __webpack_require__(138), isSymbol = __webpack_require__(214); /** Used as references for various `Number` constants. */ var NAN = 0 / 0; /** Used to match leading and trailing whitespace. */ var reTrim = /^\s+|\s+$/g; /** Used to detect bad signed hexadecimal string values. */ var reIsBadHex = /^[-+]0x[0-9a-f]+$/i; /** Used to detect binary string values. */ var reIsBinary = /^0b[01]+$/i; /** Used to detect octal string values. */ var reIsOctal = /^0o[0-7]+$/i; /** Built-in method references without a dependency on `root`. */ var freeParseInt = parseInt; /** * Converts `value` to a number. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to process. * @returns {number} Returns the number. * @example * * _.toNumber(3.2); * // => 3.2 * * _.toNumber(Number.MIN_VALUE); * // => 5e-324 * * _.toNumber(Infinity); * // => Infinity * * _.toNumber('3.2'); * // => 3.2 */ function toNumber(value) { if (typeof value == 'number') { return value; } if (isSymbol(value)) { return NAN; } if (isObject(value)) { var other = isFunction(value.valueOf) ? value.valueOf() : value; value = isObject(other) ? (other + '') : other; } if (typeof value != 'string') { return value === 0 ? value : +value; } value = value.replace(reTrim, ''); var isBinary = reIsBinary.test(value); return (isBinary || reIsOctal.test(value)) ? freeParseInt(value.slice(2), isBinary ? 2 : 8) : (reIsBadHex.test(value) ? NAN : +value); } module.exports = toNumber; /***/ }, /* 228 */ /***/ function(module, exports, __webpack_require__) { var baseFlatten = __webpack_require__(229), baseOrderBy = __webpack_require__(232), baseRest = __webpack_require__(243), isIterateeCall = __webpack_require__(245); /** * Creates an array of elements, sorted in ascending order by the results of * running each element in a collection thru each iteratee. This method * performs a stable sort, that is, it preserves the original sort order of * equal elements. The iteratees are invoked with one argument: (value). * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {...(Function|Function[])} [iteratees=[_.identity]] * The iteratees to sort by. * @returns {Array} Returns the new sorted array. * @example * * var users = [ * { 'user': 'fred', 'age': 48 }, * { 'user': 'barney', 'age': 36 }, * { 'user': 'fred', 'age': 40 }, * { 'user': 'barney', 'age': 34 } * ]; * * _.sortBy(users, function(o) { return o.user; }); * // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 40]] * * _.sortBy(users, ['user', 'age']); * // => objects for [['barney', 34], ['barney', 36], ['fred', 40], ['fred', 48]] * * _.sortBy(users, 'user', function(o) { * return Math.floor(o.age / 10); * }); * // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 40]] */ var sortBy = baseRest(function(collection, iteratees) { if (collection == null) { return []; } var length = iteratees.length; if (length > 1 && isIterateeCall(collection, iteratees[0], iteratees[1])) { iteratees = []; } else if (length > 2 && isIterateeCall(iteratees[0], iteratees[1], iteratees[2])) { iteratees = [iteratees[0]]; } return baseOrderBy(collection, baseFlatten(iteratees, 1), []); }); module.exports = sortBy; /***/ }, /* 229 */ /***/ function(module, exports, __webpack_require__) { var arrayPush = __webpack_require__(230), isFlattenable = __webpack_require__(231); /** * The base implementation of `_.flatten` with support for restricting flattening. * * @private * @param {Array} array The array to flatten. * @param {number} depth The maximum recursion depth. * @param {boolean} [predicate=isFlattenable] The function invoked per iteration. * @param {boolean} [isStrict] Restrict to values that pass `predicate` checks. * @param {Array} [result=[]] The initial result value. * @returns {Array} Returns the new flattened array. */ function baseFlatten(array, depth, predicate, isStrict, result) { var index = -1, length = array.length; predicate || (predicate = isFlattenable); result || (result = []); while (++index < length) { var value = array[index]; if (depth > 0 && predicate(value)) { if (depth > 1) { // Recursively flatten arrays (susceptible to call stack limits). baseFlatten(value, depth - 1, predicate, isStrict, result); } else { arrayPush(result, value); } } else if (!isStrict) { result[result.length] = value; } } return result; } module.exports = baseFlatten; /***/ }, /* 230 */ /***/ function(module, exports) { /** * Appends the elements of `values` to `array`. * * @private * @param {Array} array The array to modify. * @param {Array} values The values to append. * @returns {Array} Returns `array`. */ function arrayPush(array, values) { var index = -1, length = values.length, offset = array.length; while (++index < length) { array[offset + index] = values[index]; } return array; } module.exports = arrayPush; /***/ }, /* 231 */ /***/ function(module, exports, __webpack_require__) { var Symbol = __webpack_require__(169), isArguments = __webpack_require__(181), isArray = __webpack_require__(188); /** Built-in value references. */ var spreadableSymbol = Symbol ? Symbol.isConcatSpreadable : undefined; /** * Checks if `value` is a flattenable `arguments` object or array. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is flattenable, else `false`. */ function isFlattenable(value) { return isArray(value) || isArguments(value) || !!(spreadableSymbol && value && value[spreadableSymbol]) } module.exports = isFlattenable; /***/ }, /* 232 */ /***/ function(module, exports, __webpack_require__) { var arrayMap = __webpack_require__(233), baseIteratee = __webpack_require__(117), baseMap = __webpack_require__(234), baseSortBy = __webpack_require__(240), baseUnary = __webpack_require__(200), compareMultiple = __webpack_require__(241), identity = __webpack_require__(220); /** * The base implementation of `_.orderBy` without param guards. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function[]|Object[]|string[]} iteratees The iteratees to sort by. * @param {string[]} orders The sort orders of `iteratees`. * @returns {Array} Returns the new sorted array. */ function baseOrderBy(collection, iteratees, orders) { var index = -1; iteratees = arrayMap(iteratees.length ? iteratees : [identity], baseUnary(baseIteratee)); var result = baseMap(collection, function(value, key, collection) { var criteria = arrayMap(iteratees, function(iteratee) { return iteratee(value); }); return { 'criteria': criteria, 'index': ++index, 'value': value }; }); return baseSortBy(result, function(object, other) { return compareMultiple(object, other, orders); }); } module.exports = baseOrderBy; /***/ }, /* 233 */ /***/ function(module, exports) { /** * A specialized version of `_.map` for arrays without support for iteratee * shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns the new mapped array. */ function arrayMap(array, iteratee) { var index = -1, length = array ? array.length : 0, result = Array(length); while (++index < length) { result[index] = iteratee(array[index], index, array); } return result; } module.exports = arrayMap; /***/ }, /* 234 */ /***/ function(module, exports, __webpack_require__) { var baseEach = __webpack_require__(235), isArrayLike = __webpack_require__(183); /** * The base implementation of `_.map` without support for iteratee shorthands. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns the new mapped array. */ function baseMap(collection, iteratee) { var index = -1, result = isArrayLike(collection) ? Array(collection.length) : []; baseEach(collection, function(value, key, collection) { result[++index] = iteratee(value, key, collection); }); return result; } module.exports = baseMap; /***/ }, /* 235 */ /***/ function(module, exports, __webpack_require__) { var baseForOwn = __webpack_require__(236), createBaseEach = __webpack_require__(239); /** * The base implementation of `_.forEach` without support for iteratee shorthands. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array|Object} Returns `collection`. */ var baseEach = createBaseEach(baseForOwn); module.exports = baseEach; /***/ }, /* 236 */ /***/ function(module, exports, __webpack_require__) { var baseFor = __webpack_require__(237), keys = __webpack_require__(177); /** * The base implementation of `_.forOwn` without support for iteratee shorthands. * * @private * @param {Object} object The object to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Object} Returns `object`. */ function baseForOwn(object, iteratee) { return object && baseFor(object, iteratee, keys); } module.exports = baseForOwn; /***/ }, /* 237 */ /***/ function(module, exports, __webpack_require__) { var createBaseFor = __webpack_require__(238); /** * The base implementation of `baseForOwn` which iterates over `object` * properties returned by `keysFunc` and invokes `iteratee` for each property. * Iteratee functions may exit iteration early by explicitly returning `false`. * * @private * @param {Object} object The object to iterate over. * @param {Function} iteratee The function invoked per iteration. * @param {Function} keysFunc The function to get the keys of `object`. * @returns {Object} Returns `object`. */ var baseFor = createBaseFor(); module.exports = baseFor; /***/ }, /* 238 */ /***/ function(module, exports) { /** * Creates a base function for methods like `_.forIn` and `_.forOwn`. * * @private * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {Function} Returns the new base function. */ function createBaseFor(fromRight) { return function(object, iteratee, keysFunc) { var index = -1, iterable = Object(object), props = keysFunc(object), length = props.length; while (length--) { var key = props[fromRight ? length : ++index]; if (iteratee(iterable[key], key, iterable) === false) { break; } } return object; }; } module.exports = createBaseFor; /***/ }, /* 239 */ /***/ function(module, exports, __webpack_require__) { var isArrayLike = __webpack_require__(183); /** * Creates a `baseEach` or `baseEachRight` function. * * @private * @param {Function} eachFunc The function to iterate over a collection. * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {Function} Returns the new base function. */ function createBaseEach(eachFunc, fromRight) { return function(collection, iteratee) { if (collection == null) { return collection; } if (!isArrayLike(collection)) { return eachFunc(collection, iteratee); } var length = collection.length, index = fromRight ? length : -1, iterable = Object(collection); while ((fromRight ? index-- : ++index < length)) { if (iteratee(iterable[index], index, iterable) === false) { break; } } return collection; }; } module.exports = createBaseEach; /***/ }, /* 240 */ /***/ function(module, exports) { /** * The base implementation of `_.sortBy` which uses `comparer` to define the * sort order of `array` and replaces criteria objects with their corresponding * values. * * @private * @param {Array} array The array to sort. * @param {Function} comparer The function to define sort order. * @returns {Array} Returns `array`. */ function baseSortBy(array, comparer) { var length = array.length; array.sort(comparer); while (length--) { array[length] = array[length].value; } return array; } module.exports = baseSortBy; /***/ }, /* 241 */ /***/ function(module, exports, __webpack_require__) { var compareAscending = __webpack_require__(242); /** * Used by `_.orderBy` to compare multiple properties of a value to another * and stable sort them. * * If `orders` is unspecified, all values are sorted in ascending order. Otherwise, * specify an order of "desc" for descending or "asc" for ascending sort order * of corresponding values. * * @private * @param {Object} object The object to compare. * @param {Object} other The other object to compare. * @param {boolean[]|string[]} orders The order to sort by for each property. * @returns {number} Returns the sort order indicator for `object`. */ function compareMultiple(object, other, orders) { var index = -1, objCriteria = object.criteria, othCriteria = other.criteria, length = objCriteria.length, ordersLength = orders.length; while (++index < length) { var result = compareAscending(objCriteria[index], othCriteria[index]); if (result) { if (index >= ordersLength) { return result; } var order = orders[index]; return result * (order == 'desc' ? -1 : 1); } } // Fixes an `Array#sort` bug in the JS engine embedded in Adobe applications // that causes it, under certain circumstances, to provide the same value for // `object` and `other`. See https://github.com/jashkenas/underscore/pull/1247 // for more details. // // This also ensures a stable sort in V8 and other engines. // See https://bugs.chromium.org/p/v8/issues/detail?id=90 for more details. return object.index - other.index; } module.exports = compareMultiple; /***/ }, /* 242 */ /***/ function(module, exports, __webpack_require__) { var isSymbol = __webpack_require__(214); /** * Compares values to sort them in ascending order. * * @private * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {number} Returns the sort order indicator for `value`. */ function compareAscending(value, other) { if (value !== other) { var valIsDefined = value !== undefined, valIsNull = value === null, valIsReflexive = value === value, valIsSymbol = isSymbol(value); var othIsDefined = other !== undefined, othIsNull = other === null, othIsReflexive = other === other, othIsSymbol = isSymbol(other); if ((!othIsNull && !othIsSymbol && !valIsSymbol && value > other) || (valIsSymbol && othIsDefined && othIsReflexive && !othIsNull && !othIsSymbol) || (valIsNull && othIsDefined && othIsReflexive) || (!valIsDefined && othIsReflexive) || !valIsReflexive) { return 1; } if ((!valIsNull && !valIsSymbol && !othIsSymbol && value < other) || (othIsSymbol && valIsDefined && valIsReflexive && !valIsNull && !valIsSymbol) || (othIsNull && valIsDefined && valIsReflexive) || (!othIsDefined && valIsReflexive) || !othIsReflexive) { return -1; } } return 0; } module.exports = compareAscending; /***/ }, /* 243 */ /***/ function(module, exports, __webpack_require__) { var apply = __webpack_require__(244); /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeMax = Math.max; /** * The base implementation of `_.rest` which doesn't validate or coerce arguments. * * @private * @param {Function} func The function to apply a rest parameter to. * @param {number} [start=func.length-1] The start position of the rest parameter. * @returns {Function} Returns the new function. */ function baseRest(func, start) { start = nativeMax(start === undefined ? (func.length - 1) : start, 0); return function() { var args = arguments, index = -1, length = nativeMax(args.length - start, 0), array = Array(length); while (++index < length) { array[index] = args[start + index]; } index = -1; var otherArgs = Array(start + 1); while (++index < start) { otherArgs[index] = args[index]; } otherArgs[start] = array; return apply(func, this, otherArgs); }; } module.exports = baseRest; /***/ }, /* 244 */ /***/ function(module, exports) { /** * A faster alternative to `Function#apply`, this function invokes `func` * with the `this` binding of `thisArg` and the arguments of `args`. * * @private * @param {Function} func The function to invoke. * @param {*} thisArg The `this` binding of `func`. * @param {Array} args The arguments to invoke `func` with. * @returns {*} Returns the result of `func`. */ function apply(func, thisArg, args) { switch (args.length) { case 0: return func.call(thisArg); case 1: return func.call(thisArg, args[0]); case 2: return func.call(thisArg, args[0], args[1]); case 3: return func.call(thisArg, args[0], args[1], args[2]); } return func.apply(thisArg, args); } module.exports = apply; /***/ }, /* 245 */ /***/ function(module, exports, __webpack_require__) { var eq = __webpack_require__(125), isArrayLike = __webpack_require__(183), isIndex = __webpack_require__(190), isObject = __webpack_require__(138); /** * Checks if the given arguments are from an iteratee call. * * @private * @param {*} value The potential iteratee value argument. * @param {*} index The potential iteratee index or key argument. * @param {*} object The potential iteratee object argument. * @returns {boolean} Returns `true` if the arguments are from an iteratee call, * else `false`. */ function isIterateeCall(value, index, object) { if (!isObject(object)) { return false; } var type = typeof index; if (type == 'number' ? (isArrayLike(object) && isIndex(index, object.length)) : (type == 'string' && index in object) ) { return eq(object[index], value); } return false; } module.exports = isIterateeCall; /***/ }, /* 246 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ 'use strict'; /** * Use invariant() to assert state which your program assumes to be true. * * Provide sprintf-style format (only %s is supported) and arguments * to provide information about what broke and what you were * expecting. * * The invariant message will be stripped in production, but the invariant * will remain to ensure logic does not differ in production. */ var invariant = function(condition, format, a, b, c, d, e, f) { if (process.env.NODE_ENV !== 'production') { if (format === undefined) { throw new Error('invariant requires an error message argument'); } } if (!condition) { var error; if (format === undefined) { error = new Error( 'Minified exception occurred; use the non-minified dev environment ' + 'for the full error message and additional helpful warnings.' ); } else { var args = [a, b, c, d, e, f]; var argIndex = 0; error = new Error( format.replace(/%s/g, function() { return args[argIndex++]; }) ); error.name = 'Invariant Violation'; } error.framesToPop = 1; // we don't care about invariant's own frame throw error; } }; module.exports = invariant; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(247))) /***/ }, /* 247 */ /***/ function(module, exports) { // shim for using process in browser var process = module.exports = {}; var queue = []; var draining = false; var currentQueue; var queueIndex = -1; function cleanUpNextTick() { if (!draining || !currentQueue) { return; } draining = false; if (currentQueue.length) { queue = currentQueue.concat(queue); } else { queueIndex = -1; } if (queue.length) { drainQueue(); } } function drainQueue() { if (draining) { return; } var timeout = setTimeout(cleanUpNextTick); draining = true; var len = queue.length; while(len) { currentQueue = queue; queue = []; while (++queueIndex < len) { if (currentQueue) { currentQueue[queueIndex].run(); } } queueIndex = -1; len = queue.length; } currentQueue = null; draining = false; clearTimeout(timeout); } process.nextTick = function (fun) { var args = new Array(arguments.length - 1); if (arguments.length > 1) { for (var i = 1; i < arguments.length; i++) { args[i - 1] = arguments[i]; } } queue.push(new Item(fun, args)); if (queue.length === 1 && !draining) { setTimeout(drainQueue, 0); } }; // v8 likes predictible objects function Item(fun, array) { this.fun = fun; this.array = array; } Item.prototype.run = function () { this.fun.apply(null, this.array); }; process.title = 'browser'; process.browser = true; process.env = {}; process.argv = []; process.version = ''; // empty string to avoid regexp issues process.versions = {}; 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'); }; process.cwd = function () { return '/' }; process.chdir = function (dir) { throw new Error('process.chdir is not supported'); }; process.umask = function() { return 0; }; /***/ }, /* 248 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _extends2 = __webpack_require__(4); var _extends3 = _interopRequireDefault(_extends2); var _getPrototypeOf = __webpack_require__(76); var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf); var _classCallCheck2 = __webpack_require__(80); var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); var _createClass2 = __webpack_require__(81); var _createClass3 = _interopRequireDefault(_createClass2); var _possibleConstructorReturn2 = __webpack_require__(85); var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2); var _inherits2 = __webpack_require__(104); var _inherits3 = _interopRequireDefault(_inherits2); exports.default = SortableElement; var _react = __webpack_require__(112); var _react2 = _interopRequireDefault(_react); var _reactDom = __webpack_require__(113); var _invariant = __webpack_require__(246); var _invariant2 = _interopRequireDefault(_invariant); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } // Export Higher Order Sortable Element Component function SortableElement(WrappedComponent) { var _class, _temp; var config = arguments.length <= 1 || arguments[1] === undefined ? { withRef: false } : arguments[1]; return _temp = _class = function (_Component) { (0, _inherits3.default)(_class, _Component); function _class() { (0, _classCallCheck3.default)(this, _class); return (0, _possibleConstructorReturn3.default)(this, (0, _getPrototypeOf2.default)(_class).apply(this, arguments)); } (0, _createClass3.default)(_class, [{ key: 'componentDidMount', value: function componentDidMount() { var _props = this.props; var collection = _props.collection; var disabled = _props.disabled; var index = _props.index; if (!disabled) { this.setDraggable(collection, index); } } }, { key: 'componentWillReceiveProps', value: function componentWillReceiveProps(nextProps) { var index = this.props.index; if (index !== nextProps.index && this.node) { this.node.sortableInfo.index = nextProps.index; } if (this.props.disabled !== nextProps.disabled) { var collection = nextProps.collection; var disabled = nextProps.disabled; var _index = nextProps.index; if (disabled) { this.removeDraggable(collection); } else { this.setDraggable(collection, _index); } } else if (this.props.collection !== nextProps.collection) { this.removeDraggable(this.props.collection); this.setDraggable(nextProps.collection, nextProps.index); } } }, { key: 'componentWillUnmount', value: function componentWillUnmount() { var _props2 = this.props; var collection = _props2.collection; var disabled = _props2.disabled; if (!disabled) this.removeDraggable(collection); } }, { key: 'setDraggable', value: function setDraggable(collection, index) { var node = this.node = (0, _reactDom.findDOMNode)(this); node.sortableInfo = { index: index, collection: collection }; this.ref = { node: node }; this.context.manager.add(collection, this.ref); } }, { key: 'removeDraggable', value: function removeDraggable(collection) { this.context.manager.remove(collection, this.ref); } }, { key: 'getWrappedInstance', value: function getWrappedInstance() { (0, _invariant2.default)(config.withRef, 'To access the wrapped instance, you need to pass in {withRef: true} as the second argument of the SortableElement() call'); return this.refs.wrappedInstance; } }, { key: 'render', value: function render() { var ref = config.withRef ? 'wrappedInstance' : null; return _react2.default.createElement(WrappedComponent, (0, _extends3.default)({ ref: ref }, this.props)); } }]); return _class; }(_react.Component), _class.displayName = WrappedComponent.displayName ? 'SortableElement(' + WrappedComponent.displayName + ')' : 'SortableElement', _class.WrappedComponent = WrappedComponent, _class.contextTypes = { manager: _react.PropTypes.object.isRequired }, _class.propTypes = { index: _react.PropTypes.number.isRequired, collection: _react.PropTypes.oneOfType([_react.PropTypes.number, _react.PropTypes.string]), disabled: _react.PropTypes.bool }, _class.defaultProps = { collection: 0 }, _temp; } /***/ }, /* 249 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _extends2 = __webpack_require__(4); var _extends3 = _interopRequireDefault(_extends2); var _getPrototypeOf = __webpack_require__(76); var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf); var _classCallCheck2 = __webpack_require__(80); var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); var _createClass2 = __webpack_require__(81); var _createClass3 = _interopRequireDefault(_createClass2); var _possibleConstructorReturn2 = __webpack_require__(85); var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2); var _inherits2 = __webpack_require__(104); var _inherits3 = _interopRequireDefault(_inherits2); exports.default = SortableHandle; var _react = __webpack_require__(112); var _react2 = _interopRequireDefault(_react); var _reactDom = __webpack_require__(113); var _invariant = __webpack_require__(246); var _invariant2 = _interopRequireDefault(_invariant); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } // Export Higher Order Sortable Element Component function SortableHandle(WrappedComponent) { var _class, _temp; var config = arguments.length <= 1 || arguments[1] === undefined ? { withRef: false } : arguments[1]; return _temp = _class = function (_Component) { (0, _inherits3.default)(_class, _Component); function _class() { (0, _classCallCheck3.default)(this, _class); return (0, _possibleConstructorReturn3.default)(this, (0, _getPrototypeOf2.default)(_class).apply(this, arguments)); } (0, _createClass3.default)(_class, [{ key: 'componentDidMount', value: function componentDidMount() { var node = (0, _reactDom.findDOMNode)(this); node.sortableHandle = true; } }, { key: 'getWrappedInstance', value: function getWrappedInstance() { (0, _invariant2.default)(config.withRef, 'To access the wrapped instance, you need to pass in {withRef: true} as the second argument of the SortableHandle() call'); return this.refs.wrappedInstance; } }, { key: 'render', value: function render() { var ref = config.withRef ? 'wrappedInstance' : null; return _react2.default.createElement(WrappedComponent, (0, _extends3.default)({ ref: ref }, this.props)); } }]); return _class; }(_react.Component), _class.displayName = WrappedComponent.displayName ? 'SortableHandle(' + WrappedComponent.displayName + ')' : 'SortableHandle', _class.WrappedComponent = WrappedComponent, _temp; } /***/ } /******/ ]) }); ;
jQuery(function($){$.ui.dialog.wiquery.regional.is={okButton:"Ókei",cancelButton:"Hætta",questionTitle:"Spurning",waitTitle:"BÃddu",errorTitle:"Villa",warningTitle:"Viðvörun"}});
/*! p5.sound.js v0.2.15 2015-10-21 */ (function (root, factory) { if (typeof define === 'function' && define.amd) define('p5.sound', ['p5'], function (p5) { (factory(p5));}); else if (typeof exports === 'object') factory(require('../p5')); else factory(root['p5']); }(this, function (p5) { /** * p5.sound extends p5 with <a href="http://caniuse.com/audio-api" * target="_blank">Web Audio</a> functionality including audio input, * playback, analysis and synthesis. * <br/><br/> * <a href="#/p5.SoundFile"><b>p5.SoundFile</b></a>: Load and play sound files.<br/> * <a href="#/p5.Amplitude"><b>p5.Amplitude</b></a>: Get the current volume of a sound.<br/> * <a href="#/p5.AudioIn"><b>p5.AudioIn</b></a>: Get sound from an input source, typically * a computer microphone.<br/> * <a href="#/p5.FFT"><b>p5.FFT</b></a>: Analyze the frequency of sound. Returns * results from the frequency spectrum or time domain (waveform).<br/> * <a href="#/p5.Oscillator"><b>p5.Oscillator</b></a>: Generate Sine, * Triangle, Square and Sawtooth waveforms. Base class of * <a href="#/p5.Noise">p5.Noise</a> and <a href="#/p5.Pulse">p5.Pulse</a>. * <br/> * <a href="#/p5.Env"><b>p5.Env</b></a>: An Envelope is a series * of fades over time. Often used to control an object's * output gain level as an "ADSR Envelope" (Attack, Decay, * Sustain, Release). Can also modulate other parameters.<br/> * <a href="#/p5.Delay"><b>p5.Delay</b></a>: A delay effect with * parameters for feedback, delayTime, and lowpass filter.<br/> * <a href="#/p5.Filter"><b>p5.Filter</b></a>: Filter the frequency range of a * sound. * <br/> * <a href="#/p5.Reverb"><b>p5.Reverb</b></a>: Add reverb to a sound by specifying * duration and decay. <br/> * <b><a href="#/p5.Convolver">p5.Convolver</a>:</b> Extends * <a href="#/p5.Reverb">p5.Reverb</a> to simulate the sound of real * physical spaces through convolution.<br/> * <b><a href="#/p5.SoundRecorder">p5.SoundRecorder</a></b>: Record sound for playback * / save the .wav file. * <b><a href="#/p5.Phrase">p5.Phrase</a></b>, <b><a href="#/p5.Part">p5.Part</a></b> and * <b><a href="#/p5.Score">p5.Score</a></b>: Compose musical sequences. * <br/><br/> * p5.sound is on <a href="https://github.com/therewasaguy/p5.sound/">GitHub</a>. * Download the latest version * <a href="https://github.com/therewasaguy/p5.sound/blob/master/lib/p5.sound.js">here</a>. * * @module p5.sound * @submodule p5.sound * @for p5.sound * @main */ /** * p5.sound developed by Jason Sigal for the Processing Foundation, Google Summer of Code 2014. The MIT License (MIT). * * http://github.com/therewasaguy/p5.sound * * Some of the many audio libraries & resources that inspire p5.sound: * - TONE.js (c) Yotam Mann, 2014. Licensed under The MIT License (MIT). https://github.com/TONEnoTONE/Tone.js * - buzz.js (c) Jay Salvat, 2013. Licensed under The MIT License (MIT). http://buzz.jaysalvat.com/ * - Boris Smus Web Audio API book, 2013. Licensed under the Apache License http://www.apache.org/licenses/LICENSE-2.0 * - wavesurfer.js https://github.com/katspaugh/wavesurfer.js * - Web Audio Components by Jordan Santell https://github.com/web-audio-components * - Wilm Thoben's Sound library for Processing https://github.com/processing/processing/tree/master/java/libraries/sound * * Web Audio API: http://w3.org/TR/webaudio/ */ var sndcore; sndcore = function () { 'use strict'; /* AudioContext Monkeypatch Copyright 2013 Chris Wilson 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. */ (function (global, exports, perf) { exports = exports || {}; 'use strict'; function fixSetTarget(param) { if (!param) // if NYI, just return return; if (!param.setTargetAtTime) param.setTargetAtTime = param.setTargetValueAtTime; } if (window.hasOwnProperty('webkitAudioContext') && !window.hasOwnProperty('AudioContext')) { window.AudioContext = webkitAudioContext; if (!AudioContext.prototype.hasOwnProperty('createGain')) AudioContext.prototype.createGain = AudioContext.prototype.createGainNode; if (!AudioContext.prototype.hasOwnProperty('createDelay')) AudioContext.prototype.createDelay = AudioContext.prototype.createDelayNode; if (!AudioContext.prototype.hasOwnProperty('createScriptProcessor')) AudioContext.prototype.createScriptProcessor = AudioContext.prototype.createJavaScriptNode; if (!AudioContext.prototype.hasOwnProperty('createPeriodicWave')) AudioContext.prototype.createPeriodicWave = AudioContext.prototype.createWaveTable; AudioContext.prototype.internal_createGain = AudioContext.prototype.createGain; AudioContext.prototype.createGain = function () { var node = this.internal_createGain(); fixSetTarget(node.gain); return node; }; AudioContext.prototype.internal_createDelay = AudioContext.prototype.createDelay; AudioContext.prototype.createDelay = function (maxDelayTime) { var node = maxDelayTime ? this.internal_createDelay(maxDelayTime) : this.internal_createDelay(); fixSetTarget(node.delayTime); return node; }; AudioContext.prototype.internal_createBufferSource = AudioContext.prototype.createBufferSource; AudioContext.prototype.createBufferSource = function () { var node = this.internal_createBufferSource(); if (!node.start) { node.start = function (when, offset, duration) { if (offset || duration) this.noteGrainOn(when || 0, offset, duration); else this.noteOn(when || 0); }; } else { node.internal_start = node.start; node.start = function (when, offset, duration) { if (typeof duration !== 'undefined') node.internal_start(when || 0, offset, duration); else node.internal_start(when || 0, offset || 0); }; } if (!node.stop) { node.stop = function (when) { this.noteOff(when || 0); }; } else { node.internal_stop = node.stop; node.stop = function (when) { node.internal_stop(when || 0); }; } fixSetTarget(node.playbackRate); return node; }; AudioContext.prototype.internal_createDynamicsCompressor = AudioContext.prototype.createDynamicsCompressor; AudioContext.prototype.createDynamicsCompressor = function () { var node = this.internal_createDynamicsCompressor(); fixSetTarget(node.threshold); fixSetTarget(node.knee); fixSetTarget(node.ratio); fixSetTarget(node.reduction); fixSetTarget(node.attack); fixSetTarget(node.release); return node; }; AudioContext.prototype.internal_createBiquadFilter = AudioContext.prototype.createBiquadFilter; AudioContext.prototype.createBiquadFilter = function () { var node = this.internal_createBiquadFilter(); fixSetTarget(node.frequency); fixSetTarget(node.detune); fixSetTarget(node.Q); fixSetTarget(node.gain); return node; }; if (AudioContext.prototype.hasOwnProperty('createOscillator')) { AudioContext.prototype.internal_createOscillator = AudioContext.prototype.createOscillator; AudioContext.prototype.createOscillator = function () { var node = this.internal_createOscillator(); if (!node.start) { node.start = function (when) { this.noteOn(when || 0); }; } else { node.internal_start = node.start; node.start = function (when) { node.internal_start(when || 0); }; } if (!node.stop) { node.stop = function (when) { this.noteOff(when || 0); }; } else { node.internal_stop = node.stop; node.stop = function (when) { node.internal_stop(when || 0); }; } if (!node.setPeriodicWave) node.setPeriodicWave = node.setWaveTable; fixSetTarget(node.frequency); fixSetTarget(node.detune); return node; }; } } if (window.hasOwnProperty('webkitOfflineAudioContext') && !window.hasOwnProperty('OfflineAudioContext')) { window.OfflineAudioContext = webkitOfflineAudioContext; } return exports; }(window)); // <-- end MonkeyPatch. // Create the Audio Context var audiocontext = new window.AudioContext(); /** * <p>Returns the Audio Context for this sketch. Useful for users * who would like to dig deeper into the <a target='_blank' href= * 'http://webaudio.github.io/web-audio-api/'>Web Audio API * </a>.</p> * * @method getAudioContext * @return {Object} AudioContext for this sketch */ p5.prototype.getAudioContext = function () { return audiocontext; }; // Polyfill for AudioIn, also handled by p5.dom createCapture navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia; /** * Determine which filetypes are supported (inspired by buzz.js) * The audio element (el) will only be used to test browser support for various audio formats */ var el = document.createElement('audio'); p5.prototype.isSupported = function () { return !!el.canPlayType; }; var isOGGSupported = function () { return !!el.canPlayType && el.canPlayType('audio/ogg; codecs="vorbis"'); }; var isMP3Supported = function () { return !!el.canPlayType && el.canPlayType('audio/mpeg;'); }; var isWAVSupported = function () { return !!el.canPlayType && el.canPlayType('audio/wav; codecs="1"'); }; var isAACSupported = function () { return !!el.canPlayType && (el.canPlayType('audio/x-m4a;') || el.canPlayType('audio/aac;')); }; var isAIFSupported = function () { return !!el.canPlayType && el.canPlayType('audio/x-aiff;'); }; p5.prototype.isFileSupported = function (extension) { switch (extension.toLowerCase()) { case 'mp3': return isMP3Supported(); case 'wav': return isWAVSupported(); case 'ogg': return isOGGSupported(); case 'aac', 'm4a', 'mp4': return isAACSupported(); case 'aif', 'aiff': return isAIFSupported(); default: return false; } }; // if it is iOS, we have to have a user interaction to start Web Audio // http://paulbakaus.com/tutorials/html5/web-audio-on-ios/ var iOS = navigator.userAgent.match(/(iPad|iPhone|iPod)/g) ? true : false; if (iOS) { var iosStarted = false; var startIOS = function () { if (iosStarted) return; // create empty buffer var buffer = audiocontext.createBuffer(1, 1, 22050); var source = audiocontext.createBufferSource(); source.buffer = buffer; // connect to output (your speakers) source.connect(audiocontext.destination); // play the file source.start(0); console.log('start ios!'); if (audiocontext.state === 'running') { iosStarted = true; } }; document.addEventListener('touchend', startIOS, false); document.addEventListener('touchstart', startIOS, false); } }(); var master; master = function () { 'use strict'; /** * Master contains AudioContext and the master sound output. */ var Master = function () { var audiocontext = p5.prototype.getAudioContext(); this.input = audiocontext.createGain(); this.output = audiocontext.createGain(); //put a hard limiter on the output this.limiter = audiocontext.createDynamicsCompressor(); this.limiter.threshold.value = 0; this.limiter.ratio.value = 100; this.audiocontext = audiocontext; this.output.disconnect(); // an array of input sources this.inputSources = []; // connect input to limiter this.input.connect(this.limiter); // connect limiter to output this.limiter.connect(this.output); // meter is just for global Amplitude / FFT analysis this.meter = audiocontext.createGain(); this.fftMeter = audiocontext.createGain(); this.output.connect(this.meter); this.output.connect(this.fftMeter); // connect output to destination this.output.connect(this.audiocontext.destination); // an array of all sounds in the sketch this.soundArray = []; // an array of all musical parts in the sketch this.parts = []; // file extensions to search for this.extensions = []; }; // create a single instance of the p5Sound / master output for use within this sketch var p5sound = new Master(); /** * Returns a number representing the master amplitude (volume) for sound * in this sketch. * * @method getMasterVolume * @return {Number} Master amplitude (volume) for sound in this sketch. * Should be between 0.0 (silence) and 1.0. */ p5.prototype.getMasterVolume = function () { return p5sound.output.gain.value; }; /** * <p>Scale the output of all sound in this sketch</p> * Scaled between 0.0 (silence) and 1.0 (full volume). * 1.0 is the maximum amplitude of a digital sound, so multiplying * by greater than 1.0 may cause digital distortion. To * fade, provide a <code>rampTime</code> parameter. For more * complex fades, see the Env class. * * Alternately, you can pass in a signal source such as an * oscillator to modulate the amplitude with an audio signal. * * <p><b>How This Works</b>: When you load the p5.sound module, it * creates a single instance of p5sound. All sound objects in this * module output to p5sound before reaching your computer's output. * So if you change the amplitude of p5sound, it impacts all of the * sound in this module.</p> * * <p>If no value is provided, returns a Web Audio API Gain Node</p> * * @method masterVolume * @param {Number|Object} volume Volume (amplitude) between 0.0 * and 1.0 or modulating signal/oscillator * @param {Number} [rampTime] Fade for t seconds * @param {Number} [timeFromNow] Schedule this event to happen at * t seconds in the future */ p5.prototype.masterVolume = function (vol, rampTime, tFromNow) { if (typeof vol === 'number') { var rampTime = rampTime || 0; var tFromNow = tFromNow || 0; var now = p5sound.audiocontext.currentTime; var currentVol = p5sound.output.gain.value; p5sound.output.gain.cancelScheduledValues(now + tFromNow); p5sound.output.gain.linearRampToValueAtTime(currentVol, now + tFromNow); p5sound.output.gain.linearRampToValueAtTime(vol, now + tFromNow + rampTime); } else if (vol) { vol.connect(p5sound.output.gain); } else { // return the Gain Node return p5sound.output.gain; } }; /** * p5.soundOut is the p5.sound master output. It sends output to * the destination of this window's web audio context. It contains * Web Audio API nodes including a dyanmicsCompressor (<code>.limiter</code>), * and Gain Nodes for <code>.input</code> and <code>.output</code>. * * @property p5.soundOut * @type {Object} */ p5.soundOut = p5sound; /** * a silent connection to the DesinationNode * which will ensure that anything connected to it * will not be garbage collected * * @private */ p5.soundOut._silentNode = p5sound.audiocontext.createGain(); p5.soundOut._silentNode.gain.value = 0; p5.soundOut._silentNode.connect(p5sound.audiocontext.destination); return p5sound; }(sndcore); var helpers; helpers = function () { 'use strict'; var p5sound = master; /** * Returns a number representing the sample rate, in samples per second, * of all sound objects in this audio context. It is determined by the * sampling rate of your operating system's sound card, and it is not * currently possile to change. * It is often 44100, or twice the range of human hearing. * * @method sampleRate * @return {Number} samplerate samples per second */ p5.prototype.sampleRate = function () { return p5sound.audiocontext.sampleRate; }; /** * Returns the closest MIDI note value for * a given frequency. * * @param {Number} frequency A freqeuncy, for example, the "A" * above Middle C is 440Hz * @return {Number} MIDI note value */ p5.prototype.freqToMidi = function (f) { var mathlog2 = Math.log(f / 440) / Math.log(2); var m = Math.round(12 * mathlog2) + 57; return m; }; /** * Returns the frequency value of a MIDI note value. * General MIDI treats notes as integers where middle C * is 60, C# is 61, D is 62 etc. Useful for generating * musical frequencies with oscillators. * * @method midiToFreq * @param {Number} midiNote The number of a MIDI note * @return {Number} Frequency value of the given MIDI note * @example * <div><code> * var notes = [60, 64, 67, 72]; * var i = 0; * * function setup() { * osc = new p5.Oscillator('Triangle'); * osc.start(); * frameRate(1); * } * * function draw() { * var freq = midiToFreq(notes[i]); * osc.freq(freq); * i++; * if (i >= notes.length){ * i = 0; * } * } * </code></div> */ p5.prototype.midiToFreq = function (m) { return 440 * Math.pow(2, (m - 69) / 12); }; /** * List the SoundFile formats that you will include. LoadSound * will search your directory for these extensions, and will pick * a format that is compatable with the client's web browser. * <a href="http://media.io/">Here</a> is a free online file * converter. * * @method soundFormats * @param {String|Strings} formats i.e. 'mp3', 'wav', 'ogg' * @example * <div><code> * function preload() { * // set the global sound formats * soundFormats('mp3', 'ogg'); * * // load either beatbox.mp3, or .ogg, depending on browser * mySound = loadSound('../sounds/beatbox.mp3'); * } * * function setup() { * mySound.play(); * } * </code></div> */ p5.prototype.soundFormats = function () { // reset extensions array p5sound.extensions = []; // add extensions for (var i = 0; i < arguments.length; i++) { arguments[i] = arguments[i].toLowerCase(); if ([ 'mp3', 'wav', 'ogg', 'm4a', 'aac' ].indexOf(arguments[i]) > -1) { p5sound.extensions.push(arguments[i]); } else { throw arguments[i] + ' is not a valid sound format!'; } } }; p5.prototype.disposeSound = function () { for (var i = 0; i < p5sound.soundArray.length; i++) { p5sound.soundArray[i].dispose(); } }; // register removeSound to dispose of p5sound SoundFiles, Convolvers, // Oscillators etc when sketch ends p5.prototype.registerMethod('remove', p5.prototype.disposeSound); p5.prototype._checkFileFormats = function (paths) { var path; // if path is a single string, check to see if extension is provided if (typeof paths === 'string') { path = paths; // see if extension is provided var extTest = path.split('.').pop(); // if an extension is provided... if ([ 'mp3', 'wav', 'ogg', 'm4a', 'aac' ].indexOf(extTest) > -1) { var supported = p5.prototype.isFileSupported(extTest); if (supported) { path = path; } else { var pathSplit = path.split('.'); var pathCore = pathSplit[pathSplit.length - 1]; for (var i = 0; i < p5sound.extensions.length; i++) { var extension = p5sound.extensions[i]; var supported = p5.prototype.isFileSupported(extension); if (supported) { pathCore = ''; if (pathSplit.length === 2) { pathCore += pathSplit[0]; } for (var i = 1; i <= pathSplit.length - 2; i++) { var p = pathSplit[i]; pathCore += '.' + p; } path = pathCore += '.'; path = path += extension; break; } } } } else { for (var i = 0; i < p5sound.extensions.length; i++) { var extension = p5sound.extensions[i]; var supported = p5.prototype.isFileSupported(extension); if (supported) { path = path + '.' + extension; break; } } } } else if (typeof paths === 'object') { for (var i = 0; i < paths.length; i++) { var extension = paths[i].split('.').pop(); var supported = p5.prototype.isFileSupported(extension); if (supported) { // console.log('.'+extension + ' is ' + supported + // ' supported by your browser.'); path = paths[i]; break; } } } return path; }; /** * Used by Osc and Env to chain signal math */ p5.prototype._mathChain = function (o, math, thisChain, nextChain, type) { // if this type of math already exists in the chain, replace it for (var i in o.mathOps) { if (o.mathOps[i] instanceof type) { o.mathOps[i].dispose(); thisChain = i; if (thisChain < o.mathOps.length - 1) { nextChain = o.mathOps[i + 1]; } } } o.mathOps[thisChain - 1].disconnect(); o.mathOps[thisChain - 1].connect(math); math.connect(nextChain); o.mathOps[thisChain] = math; return o; }; }(master); var panner; panner = function () { 'use strict'; var p5sound = master; var ac = p5sound.audiocontext; // Stereo panner // if there is a stereo panner node use it if (typeof ac.createStereoPanner !== 'undefined') { p5.Panner = function (input, output, numInputChannels) { this.stereoPanner = this.input = ac.createStereoPanner(); input.connect(this.stereoPanner); this.stereoPanner.connect(output); }; p5.Panner.prototype.pan = function (val, tFromNow) { var time = tFromNow || 0; var t = ac.currentTime + time; this.stereoPanner.pan.linearRampToValueAtTime(val, t); }; p5.Panner.prototype.inputChannels = function (numChannels) { }; p5.Panner.prototype.connect = function (obj) { this.stereoPanner.connect(obj); }; p5.Panner.prototype.disconnect = function (obj) { this.stereoPanner.disconnect(); }; } else { // if there is no createStereoPanner object // such as in safari 7.1.7 at the time of writing this // use this method to create the effect p5.Panner = function (input, output, numInputChannels) { this.input = ac.createGain(); input.connect(this.input); this.left = ac.createGain(); this.right = ac.createGain(); this.left.channelInterpretation = 'discrete'; this.right.channelInterpretation = 'discrete'; // if input is stereo if (numInputChannels > 1) { this.splitter = ac.createChannelSplitter(2); this.input.connect(this.splitter); this.splitter.connect(this.left, 1); this.splitter.connect(this.right, 0); } else { this.input.connect(this.left); this.input.connect(this.right); } this.output = ac.createChannelMerger(2); this.left.connect(this.output, 0, 1); this.right.connect(this.output, 0, 0); this.output.connect(output); }; // -1 is left, +1 is right p5.Panner.prototype.pan = function (val, tFromNow) { var time = tFromNow || 0; var t = ac.currentTime + time; var v = (val + 1) / 2; var rightVal = Math.cos(v * Math.PI / 2); var leftVal = Math.sin(v * Math.PI / 2); this.left.gain.linearRampToValueAtTime(leftVal, t); this.right.gain.linearRampToValueAtTime(rightVal, t); }; p5.Panner.prototype.inputChannels = function (numChannels) { if (numChannels === 1) { this.input.disconnect(); this.input.connect(this.left); this.input.connect(this.right); } else if (numChannels === 2) { if (typeof (this.splitter === 'undefined')) { this.splitter = ac.createChannelSplitter(2); } this.input.disconnect(); this.input.connect(this.splitter); this.splitter.connect(this.left, 1); this.splitter.connect(this.right, 0); } }; p5.Panner.prototype.connect = function (obj) { this.output.connect(obj); }; p5.Panner.prototype.disconnect = function (obj) { this.output.disconnect(); }; } // 3D panner p5.Panner3D = function (input, output) { var panner3D = ac.createPanner(); panner3D.panningModel = 'HRTF'; panner3D.distanceModel = 'linear'; panner3D.setPosition(0, 0, 0); input.connect(panner3D); panner3D.connect(output); panner3D.pan = function (xVal, yVal, zVal) { panner3D.setPosition(xVal, yVal, zVal); }; return panner3D; }; }(master); var soundfile; soundfile = function () { 'use strict'; var p5sound = master; var ac = p5sound.audiocontext; /** * <p>SoundFile object with a path to a file.</p> * * <p>The p5.SoundFile may not be available immediately because * it loads the file information asynchronously.</p> * * <p>To do something with the sound as soon as it loads * pass the name of a function as the second parameter.</p> * * <p>Only one file path is required. However, audio file formats * (i.e. mp3, ogg, wav and m4a/aac) are not supported by all * web browsers. If you want to ensure compatability, instead of a single * file path, you may include an Array of filepaths, and the browser will * choose a format that works.</p> * * @class p5.SoundFile * @constructor * @param {String/Array} path path to a sound file (String). Optionally, * you may include multiple file formats in * an array. Alternately, accepts an object * from the HTML5 File API, or a p5.File. * @param {Function} [callback] Name of a function to call once file loads * @return {Object} p5.SoundFile Object * @example * <div><code> * * function preload() { * mySound = loadSound('assets/doorbell.mp3'); * } * * function setup() { * mySound.setVolume(0.1); * mySound.play(); * } * * </code></div> */ p5.SoundFile = function (paths, onload, whileLoading) { if (typeof paths !== 'undefined') { if (typeof paths == 'string' || typeof paths[0] == 'string') { var path = p5.prototype._checkFileFormats(paths); this.url = path; } else if (typeof paths == 'object') { if (!(window.File && window.FileReader && window.FileList && window.Blob)) { // The File API isn't supported in this browser throw 'Unable to load file because the File API is not supported'; } } // if type is a p5.File...get the actual file if (paths.file) { paths = paths.file; } this.file = paths; } this._looping = false; this._playing = false; this._paused = false; this._pauseTime = 0; // cues for scheduling events with addCue() removeCue() this._cues = []; // position of the most recently played sample this._lastPos = 0; this._counterNode; this._scopeNode; // array of sources so that they can all be stopped! this.bufferSourceNodes = []; // current source this.bufferSourceNode = null; this.buffer = null; this.playbackRate = 1; this.gain = 1; this.input = p5sound.audiocontext.createGain(); this.output = p5sound.audiocontext.createGain(); this.reversed = false; // start and end of playback / loop this.startTime = 0; this.endTime = null; this.pauseTime = 0; // "restart" would stop playback before retriggering this.mode = 'sustain'; // time that playback was started, in millis this.startMillis = null; this.amplitude = new p5.Amplitude(); this.output.connect(this.amplitude.input); // stereo panning this.panPosition = 0; this.panner = new p5.Panner(this.output, p5sound.input, 2); // it is possible to instantiate a soundfile with no path if (this.url || this.file) { this.load(onload); } // add this p5.SoundFile to the soundArray p5sound.soundArray.push(this); if (typeof whileLoading === 'function') { this.whileLoading = whileLoading; } else { this.whileLoading = function () { }; } }; // register preload handling of loadSound p5.prototype.registerPreloadMethod('loadSound', p5.prototype); /** * loadSound() returns a new p5.SoundFile from a specified * path. If called during preload(), the p5.SoundFile will be ready * to play in time for setup() and draw(). If called outside of * preload, the p5.SoundFile will not be ready immediately, so * loadSound accepts a callback as the second parameter. Using a * <a href="https://github.com/processing/p5.js/wiki/Local-server"> * local server</a> is recommended when loading external files. * * @method loadSound * @param {String/Array} path Path to the sound file, or an array with * paths to soundfiles in multiple formats * i.e. ['sound.ogg', 'sound.mp3']. * Alternately, accepts an object: either * from the HTML5 File API, or a p5.File. * @param {Function} [callback] Name of a function to call once file loads * @param {Function} [callback] Name of a function to call while file is loading. * This function will receive a percentage from 0.0 * to 1.0. * @return {SoundFile} Returns a p5.SoundFile * @example * <div><code> * function preload() { * mySound = loadSound('assets/doorbell.mp3'); * } * * function setup() { * mySound.setVolume(0.1); * mySound.play(); * } * </code></div> */ p5.prototype.loadSound = function (path, callback, whileLoading) { // if loading locally without a server if (window.location.origin.indexOf('file://') > -1 && window.cordova === 'undefined') { alert('This sketch may require a server to load external files. Please see http://bit.ly/1qcInwS'); } var s = new p5.SoundFile(path, callback, whileLoading); return s; }; /** * This is a helper function that the p5.SoundFile calls to load * itself. Accepts a callback (the name of another function) * as an optional parameter. * * @private * @param {Function} [callback] Name of a function to call once file loads */ p5.SoundFile.prototype.load = function (callback) { if (this.url != undefined && this.url != '') { var sf = this; var request = new XMLHttpRequest(); request.addEventListener('progress', function (evt) { sf._updateProgress(evt); }, false); request.open('GET', this.url, true); request.responseType = 'arraybuffer'; // decode asyncrohonously var self = this; request.onload = function () { ac.decodeAudioData(request.response, function (buff) { self.buffer = buff; self.panner.inputChannels(buff.numberOfChannels); if (callback) { callback(self); } }); }; request.send(); } else if (this.file != undefined) { var reader = new FileReader(); var self = this; reader.onload = function () { ac.decodeAudioData(reader.result, function (buff) { self.buffer = buff; self.panner.inputChannels(buff.numberOfChannels); if (callback) { callback(self); } }); }; reader.readAsArrayBuffer(this.file); } }; // TO DO: use this method to create a loading bar that shows progress during file upload/decode. p5.SoundFile.prototype._updateProgress = function (evt) { if (evt.lengthComputable) { var percentComplete = Math.log(evt.loaded / evt.total * 9.9); this.whileLoading(percentComplete); } else { console.log('size unknown'); } }; /** * Returns true if the sound file finished loading successfully. * * @method isLoaded * @return {Boolean} */ p5.SoundFile.prototype.isLoaded = function () { if (this.buffer) { return true; } else { return false; } }; /** * Play the p5.SoundFile * * @method play * @param {Number} [startTime] (optional) schedule playback to start (in seconds from now). * @param {Number} [rate] (optional) playback rate * @param {Number} [amp] (optional) amplitude (volume) * of playback * @param {Number} [cueStart] (optional) cue start time in seconds * @param {Number} [duration] (optional) duration of playback in seconds */ p5.SoundFile.prototype.play = function (time, rate, amp, _cueStart, duration) { var self = this; var now = p5sound.audiocontext.currentTime; var cueStart, cueEnd; var time = time || 0; if (time < 0) { time = 0; } time = time + now; // TO DO: if already playing, create array of buffers for easy stop() if (this.buffer) { // reset the pause time (if it was paused) this._pauseTime = 0; // handle restart playmode if (this.mode === 'restart' && this.buffer && this.bufferSourceNode) { var now = p5sound.audiocontext.currentTime; this.bufferSourceNode.stop(time); this._counterNode.stop(time); } // make a new source and counter. They are automatically assigned playbackRate and buffer this.bufferSourceNode = this._initSourceNode(); this._counterNode = this._initCounterNode(); if (_cueStart) { if (_cueStart >= 0 && _cueStart < this.buffer.duration) { // this.startTime = cueStart; cueStart = _cueStart; } else { throw 'start time out of range'; } } else { cueStart = 0; } if (duration) { // if duration is greater than buffer.duration, just play entire file anyway rather than throw an error duration = duration <= this.buffer.duration - cueStart ? duration : this.buffer.duration; } else { duration = this.buffer.duration - cueStart; } // TO DO: Fix this. It broke in Safari // // method of controlling gain for individual bufferSourceNodes, without resetting overall soundfile volume // if (typeof(this.bufferSourceNode.gain === 'undefined' ) ) { // this.bufferSourceNode.gain = p5sound.audiocontext.createGain(); // } // this.bufferSourceNode.connect(this.bufferSourceNode.gain); // set local amp if provided, otherwise 1 var a = amp || 1; // this.bufferSourceNode.gain.gain.setValueAtTime(a, p5sound.audiocontext.currentTime); // this.bufferSourceNode.gain.connect(this.output); this.bufferSourceNode.connect(this.output); this.output.gain.value = a; // not necessary with _initBufferSource ? // this.bufferSourceNode.playbackRate.cancelScheduledValues(now); rate = rate || Math.abs(this.playbackRate); this.bufferSourceNode.playbackRate.setValueAtTime(rate, now); // if it was paused, play at the pause position if (this._paused) { this.bufferSourceNode.start(time, this.pauseTime, duration); this._counterNode.start(time, this.pauseTime, duration); } else { this.bufferSourceNode.start(time, cueStart, duration); this._counterNode.start(time, cueStart, duration); } this._playing = true; this._paused = false; // add source to sources array, which is used in stopAll() this.bufferSourceNodes.push(this.bufferSourceNode); this.bufferSourceNode._arrayIndex = this.bufferSourceNodes.length - 1; // delete this.bufferSourceNode from the sources array when it is done playing: this.bufferSourceNode.onended = function (e) { var theNode = this; // if (self.bufferSourceNodes.length === 1) { this._playing = false; // } setTimeout(function () { self.bufferSourceNodes.splice(theNode._arrayIndex, 1); if (self.bufferSourceNodes.length === 0) { self._playing = false; } }, 1); }; } else { throw 'not ready to play file, buffer has yet to load. Try preload()'; } // if looping, will restart at original time this.bufferSourceNode.loop = this._looping; this._counterNode.loop = this._looping; if (this._looping === true) { var cueEnd = cueStart + duration; this.bufferSourceNode.loopStart = cueStart; this.bufferSourceNode.loopEnd = cueEnd; this._counterNode.loopStart = cueStart; this._counterNode.loopEnd = cueEnd; } }; /** * p5.SoundFile has two play modes: <code>restart</code> and * <code>sustain</code>. Play Mode determines what happens to a * p5.SoundFile if it is triggered while in the middle of playback. * In sustain mode, playback will continue simultaneous to the * new playback. In restart mode, play() will stop playback * and start over. Sustain is the default mode. * * @method playMode * @param {String} str 'restart' or 'sustain' * @example * <div><code> * function setup(){ * mySound = loadSound('assets/Damscray_DancingTiger.mp3'); * } * function mouseClicked() { * mySound.playMode('sustain'); * mySound.play(); * } * function keyPressed() { * mySound.playMode('restart'); * mySound.play(); * } * * </code></div> */ p5.SoundFile.prototype.playMode = function (str) { var s = str.toLowerCase(); // if restart, stop all other sounds from playing if (s === 'restart' && this.buffer && this.bufferSourceNode) { for (var i = 0; i < this.bufferSourceNodes.length - 1; i++) { var now = p5sound.audiocontext.currentTime; this.bufferSourceNodes[i].stop(now); } } // set play mode to effect future playback if (s === 'restart' || s === 'sustain') { this.mode = s; } else { throw 'Invalid play mode. Must be either "restart" or "sustain"'; } }; /** * Pauses a file that is currently playing. If the file is not * playing, then nothing will happen. * * After pausing, .play() will resume from the paused * position. * If p5.SoundFile had been set to loop before it was paused, * it will continue to loop after it is unpaused with .play(). * * @method pause * @param {Number} [startTime] (optional) schedule event to occur * seconds from now * @example * <div><code> * var soundFile; * * function preload() { * soundFormats('ogg', 'mp3'); * soundFile = loadSound('assets/Damscray_-_Dancing_Tiger_02.mp3'); * } * function setup() { * background(0, 255, 0); * soundFile.setVolume(0.1); * soundFile.loop(); * } * function keyTyped() { * if (key == 'p') { * soundFile.pause(); * background(255, 0, 0); * } * } * * function keyReleased() { * if (key == 'p') { * soundFile.play(); * background(0, 255, 0); * } * </code> * </div> */ p5.SoundFile.prototype.pause = function (time) { var now = p5sound.audiocontext.currentTime; var time = time || 0; var pTime = time + now; if (this.isPlaying() && this.buffer && this.bufferSourceNode) { this.pauseTime = this.currentTime(); this.bufferSourceNode.stop(pTime); this._counterNode.stop(pTime); this._paused = true; this._playing = false; this._pauseTime = this.currentTime(); } else { this._pauseTime = 0; } }; /** * Loop the p5.SoundFile. Accepts optional parameters to set the * playback rate, playback volume, loopStart, loopEnd. * * @method loop * @param {Number} [startTime] (optional) schedule event to occur * seconds from now * @param {Number} [rate] (optional) playback rate * @param {Number} [amp] (optional) playback volume * @param {Number} [cueLoopStart](optional) startTime in seconds * @param {Number} [duration] (optional) loop duration in seconds */ p5.SoundFile.prototype.loop = function (startTime, rate, amp, loopStart, duration) { this._looping = true; this.play(startTime, rate, amp, loopStart, duration); }; /** * Set a p5.SoundFile's looping flag to true or false. If the sound * is currently playing, this change will take effect when it * reaches the end of the current playback. * * @param {Boolean} Boolean set looping to true or false */ p5.SoundFile.prototype.setLoop = function (bool) { if (bool === true) { this._looping = true; } else if (bool === false) { this._looping = false; } else { throw 'Error: setLoop accepts either true or false'; } if (this.bufferSourceNode) { this.bufferSourceNode.loop = this._looping; this._counterNode.loop = this._looping; } }; /** * Returns 'true' if a p5.SoundFile is currently looping and playing, 'false' if not. * * @return {Boolean} */ p5.SoundFile.prototype.isLooping = function () { if (!this.bufferSourceNode) { return false; } if (this._looping === true && this.isPlaying() === true) { return true; } return false; }; /** * Returns true if a p5.SoundFile is playing, false if not (i.e. * paused or stopped). * * @method isPlaying * @return {Boolean} */ p5.SoundFile.prototype.isPlaying = function () { return this._playing; }; /** * Returns true if a p5.SoundFile is paused, false if not (i.e. * playing or stopped). * * @method isPaused * @return {Boolean} */ p5.SoundFile.prototype.isPaused = function () { return this._paused; }; /** * Stop soundfile playback. * * @method stop * @param {Number} [startTime] (optional) schedule event to occur * in seconds from now */ p5.SoundFile.prototype.stop = function (timeFromNow) { var time = timeFromNow || 0; if (this.mode == 'sustain') { this.stopAll(time); this._playing = false; this.pauseTime = 0; this._paused = false; } else if (this.buffer && this.bufferSourceNode) { var now = p5sound.audiocontext.currentTime; var t = time || 0; this.pauseTime = 0; this.bufferSourceNode.stop(now + t); this._counterNode.stop(now + t); this._playing = false; this._paused = false; } }; /** * Stop playback on all of this soundfile's sources. * @private */ p5.SoundFile.prototype.stopAll = function (_time) { var now = p5sound.audiocontext.currentTime; var time = _time || 0; if (this.buffer && this.bufferSourceNode) { for (var i = 0; i < this.bufferSourceNodes.length; i++) { if (typeof this.bufferSourceNodes[i] != undefined) { try { this.bufferSourceNodes[i].stop(now + time); } catch (e) { } } } this._counterNode.stop(now + time); } }; /** * Multiply the output volume (amplitude) of a sound file * between 0.0 (silence) and 1.0 (full volume). * 1.0 is the maximum amplitude of a digital sound, so multiplying * by greater than 1.0 may cause digital distortion. To * fade, provide a <code>rampTime</code> parameter. For more * complex fades, see the Env class. * * Alternately, you can pass in a signal source such as an * oscillator to modulate the amplitude with an audio signal. * * @method setVolume * @param {Number|Object} volume Volume (amplitude) between 0.0 * and 1.0 or modulating signal/oscillator * @param {Number} [rampTime] Fade for t seconds * @param {Number} [timeFromNow] Schedule this event to happen at * t seconds in the future */ p5.SoundFile.prototype.setVolume = function (vol, rampTime, tFromNow) { if (typeof vol === 'number') { var rampTime = rampTime || 0; var tFromNow = tFromNow || 0; var now = p5sound.audiocontext.currentTime; var currentVol = this.output.gain.value; this.output.gain.cancelScheduledValues(now + tFromNow); this.output.gain.linearRampToValueAtTime(currentVol, now + tFromNow); this.output.gain.linearRampToValueAtTime(vol, now + tFromNow + rampTime); } else if (vol) { vol.connect(this.output.gain); } else { // return the Gain Node return this.output.gain; } }; // same as setVolume, to match Processing Sound p5.SoundFile.prototype.amp = p5.SoundFile.prototype.setVolume; // these are the same thing p5.SoundFile.prototype.fade = p5.SoundFile.prototype.setVolume; p5.SoundFile.prototype.getVolume = function () { return this.output.gain.value; }; /** * Set the stereo panning of a p5.sound object to * a floating point number between -1.0 (left) and 1.0 (right). * Default is 0.0 (center). * * @method pan * @param {Number} [panValue] Set the stereo panner * @param {Number} timeFromNow schedule this event to happen * seconds from now * @example * <div><code> * * var ball = {}; * var soundFile; * * function setup() { * soundFormats('ogg', 'mp3'); * soundFile = loadSound('assets/beatbox.mp3'); * } * * function draw() { * background(0); * ball.x = constrain(mouseX, 0, width); * ellipse(ball.x, height/2, 20, 20) * } * * function mousePressed(){ * // map the ball's x location to a panning degree * // between -1.0 (left) and 1.0 (right) * var panning = map(ball.x, 0., width,-1.0, 1.0); * soundFile.pan(panning); * soundFile.play(); * } * </div></code> */ p5.SoundFile.prototype.pan = function (pval, tFromNow) { this.panPosition = pval; this.panner.pan(pval, tFromNow); }; /** * Returns the current stereo pan position (-1.0 to 1.0) * * @return {Number} Returns the stereo pan setting of the Oscillator * as a number between -1.0 (left) and 1.0 (right). * 0.0 is center and default. */ p5.SoundFile.prototype.getPan = function () { return this.panPosition; }; /** * Set the playback rate of a sound file. Will change the speed and the pitch. * Values less than zero will reverse the audio buffer. * * @method rate * @param {Number} [playbackRate] Set the playback rate. 1.0 is normal, * .5 is half-speed, 2.0 is twice as fast. * Must be greater than zero. * @example * <div><code> * var song; * * function preload() { * song = loadSound('assets/Damscray_DancingTiger.mp3'); * } * * function setup() { * song.loop(); * } * * function draw() { * background(200); * * // Set the rate to a range between 0.1 and 4 * // Changing the rate also alters the pitch * var speed = map(mouseY, 0.1, height, 0, 2); * speed = constrain(speed, 0.01, 4); * song.rate(speed); * * // Draw a circle to show what is going on * stroke(0); * fill(51, 100); * ellipse(mouseX, 100, 48, 48); * } * * </code> * </div> * */ p5.SoundFile.prototype.rate = function (playbackRate) { if (this.playbackRate === playbackRate && this.bufferSourceNode) { if (this.bufferSourceNode.playbackRate.value === playbackRate) { return; } } this.playbackRate = playbackRate; var rate = playbackRate; if (this.playbackRate === 0 && this._playing) { this.pause(); } if (this.playbackRate < 0 && !this.reversed) { var cPos = this.currentTime(); var cRate = this.bufferSourceNode.playbackRate.value; // this.pause(); this.reverseBuffer(); rate = Math.abs(playbackRate); var newPos = (cPos - this.duration()) / rate; this.pauseTime = newPos; } else if (this.playbackRate > 0 && this.reversed) { this.reverseBuffer(); } if (this.bufferSourceNode) { var now = p5sound.audiocontext.currentTime; this.bufferSourceNode.playbackRate.cancelScheduledValues(now); this.bufferSourceNode.playbackRate.linearRampToValueAtTime(Math.abs(rate), now); this._counterNode.playbackRate.cancelScheduledValues(now); this._counterNode.playbackRate.linearRampToValueAtTime(Math.abs(rate), now); } }; // TO DO: document this p5.SoundFile.prototype.setPitch = function (num) { var newPlaybackRate = midiToFreq(num) / midiToFreq(60); this.rate(newPlaybackRate); }; p5.SoundFile.prototype.getPlaybackRate = function () { return this.playbackRate; }; /** * Returns the duration of a sound file in seconds. * * @method duration * @return {Number} The duration of the soundFile in seconds. */ p5.SoundFile.prototype.duration = function () { // Return Duration if (this.buffer) { return this.buffer.duration; } else { return 0; } }; /** * Return the current position of the p5.SoundFile playhead, in seconds. * Note that if you change the playbackRate while the p5.SoundFile is * playing, the results may not be accurate. * * @method currentTime * @return {Number} currentTime of the soundFile in seconds. */ p5.SoundFile.prototype.currentTime = function () { // TO DO --> make reverse() flip these values appropriately if (this._pauseTime > 0) { return this._pauseTime; } else { return this._lastPos / ac.sampleRate; } }; /** * Move the playhead of the song to a position, in seconds. Start * and Stop time. If none are given, will reset the file to play * entire duration from start to finish. * * @method jump * @param {Number} cueTime cueTime of the soundFile in seconds. * @param {Number} uuration duration in seconds. */ p5.SoundFile.prototype.jump = function (cueTime, duration) { if (cueTime < 0 || cueTime > this.buffer.duration) { throw 'jump time out of range'; } if (duration > this.buffer.duration - cueTime) { throw 'end time out of range'; } var cTime = cueTime || 0; var eTime = duration || this.buffer.duration - cueTime; if (this.isPlaying()) { this.stop(); } this.play(0, this.playbackRate, this.output.gain.value, cTime, eTime); }; /** * Return the number of channels in a sound file. * For example, Mono = 1, Stereo = 2. * * @method channels * @return {Number} [channels] */ p5.SoundFile.prototype.channels = function () { return this.buffer.numberOfChannels; }; /** * Return the sample rate of the sound file. * * @method sampleRate * @return {Number} [sampleRate] */ p5.SoundFile.prototype.sampleRate = function () { return this.buffer.sampleRate; }; /** * Return the number of samples in a sound file. * Equal to sampleRate * duration. * * @method frames * @return {Number} [sampleCount] */ p5.SoundFile.prototype.frames = function () { return this.buffer.length; }; /** * Returns an array of amplitude peaks in a p5.SoundFile that can be * used to draw a static waveform. Scans through the p5.SoundFile's * audio buffer to find the greatest amplitudes. Accepts one * parameter, 'length', which determines size of the array. * Larger arrays result in more precise waveform visualizations. * * Inspired by Wavesurfer.js. * * @method getPeaks * @params {Number} [length] length is the size of the returned array. * Larger length results in more precision. * Defaults to 5*width of the browser window. * @returns {Float32Array} Array of peaks. */ p5.SoundFile.prototype.getPeaks = function (length) { if (this.buffer) { // set length to window's width if no length is provided if (!length) { length = window.width * 5; } if (this.buffer) { var buffer = this.buffer; var sampleSize = buffer.length / length; var sampleStep = ~~(sampleSize / 10) || 1; var channels = buffer.numberOfChannels; var peaks = new Float32Array(Math.round(length)); for (var c = 0; c < channels; c++) { var chan = buffer.getChannelData(c); for (var i = 0; i < length; i++) { var start = ~~(i * sampleSize); var end = ~~(start + sampleSize); var max = 0; for (var j = start; j < end; j += sampleStep) { var value = chan[j]; if (value > max) { max = value; } else if (-value > max) { max = value; } } if (c === 0 || Math.abs(max) > peaks[i]) { peaks[i] = max; } } } return peaks; } } else { throw 'Cannot load peaks yet, buffer is not loaded'; } }; /** * Reverses the p5.SoundFile's buffer source. * Playback must be handled separately (see example). * * @method reverseBuffer * @example * <div><code> * var drum; * * function preload() { * drum = loadSound('assets/drum.mp3'); * } * * function setup() { * drum.reverseBuffer(); * drum.play(); * } * * </code> * </div> */ p5.SoundFile.prototype.reverseBuffer = function () { var curVol = this.getVolume(); this.setVolume(0, 0.01, 0); this.pause(); if (this.buffer) { for (var i = 0; i < this.buffer.numberOfChannels; i++) { Array.prototype.reverse.call(this.buffer.getChannelData(i)); } // set reversed flag this.reversed = !this.reversed; } else { throw 'SoundFile is not done loading'; } this.setVolume(curVol, 0.01, 0.0101); this.play(); }; // private function for onended behavior p5.SoundFile.prototype._onEnded = function (s) { s.onended = function (s) { var now = p5sound.audiocontext.currentTime; s.stop(now); }; }; p5.SoundFile.prototype.add = function () { }; p5.SoundFile.prototype.dispose = function () { var now = p5sound.audiocontext.currentTime; this.stop(now); if (this.buffer && this.bufferSourceNode) { for (var i = 0; i < this.bufferSourceNodes.length - 1; i++) { if (this.bufferSourceNodes[i] !== null) { // this.bufferSourceNodes[i].disconnect(); this.bufferSourceNodes[i].stop(now); this.bufferSourceNodes[i] = null; } } if (this.isPlaying()) { try { this._counterNode.stop(now); } catch (e) { console.log(e); } this._counterNode = null; } } if (this.output) { this.output.disconnect(); this.output = null; } if (this.panner) { this.panner.disconnect(); this.panner = null; } }; /** * Connects the output of a p5sound object to input of another * p5.sound object. For example, you may connect a p5.SoundFile to an * FFT or an Effect. If no parameter is given, it will connect to * the master output. Most p5sound objects connect to the master * output when they are created. * * @method connect * @param {Object} [object] Audio object that accepts an input */ p5.SoundFile.prototype.connect = function (unit) { if (!unit) { this.panner.connect(p5sound.input); } else { if (unit.hasOwnProperty('input')) { this.panner.connect(unit.input); } else { this.panner.connect(unit); } } }; /** * Disconnects the output of this p5sound object. * * @method disconnect */ p5.SoundFile.prototype.disconnect = function (unit) { this.panner.disconnect(unit); }; /** * Read the Amplitude (volume level) of a p5.SoundFile. The * p5.SoundFile class contains its own instance of the Amplitude * class to help make it easy to get a SoundFile's volume level. * Accepts an optional smoothing value (0.0 < 1.0). * * @method getLevel * @param {Number} [smoothing] Smoothing is 0.0 by default. * Smooths values based on previous values. * @return {Number} Volume level (between 0.0 and 1.0) */ p5.SoundFile.prototype.getLevel = function (smoothing) { if (smoothing) { this.amplitude.smoothing = smoothing; } return this.amplitude.getLevel(); }; /** * Reset the source for this SoundFile to a * new path (URL). * * @method setPath * @param {String} path path to audio file * @param {Function} callback Callback */ p5.SoundFile.prototype.setPath = function (p, callback) { var path = p5.prototype._checkFileFormats(p); this.url = path; this.load(callback); }; /** * Replace the current Audio Buffer with a new Buffer. * * @param {Array} buf Array of Float32 Array(s). 2 Float32 Arrays * will create a stereo source. 1 will create * a mono source. */ p5.SoundFile.prototype.setBuffer = function (buf) { var numChannels = buf.length; var size = buf[0].length; var newBuffer = ac.createBuffer(numChannels, size, ac.sampleRate); if (!buf[0] instanceof Float32Array) { buf[0] = new Float32Array(buf[0]); } for (var channelNum = 0; channelNum < numChannels; channelNum++) { var channel = newBuffer.getChannelData(channelNum); channel.set(buf[channelNum]); } this.buffer = newBuffer; // set numbers of channels on input to the panner this.panner.inputChannels(numChannels); }; ////////////////////////////////////////////////// // script processor node with an empty buffer to help // keep a sample-accurate position in playback buffer. // Inspired by Chinmay Pendharkar's technique for Sonoport --> http://bit.ly/1HwdCsV // Copyright [2015] [Sonoport (Asia) Pte. Ltd.], // Licensed under the Apache License http://apache.org/licenses/LICENSE-2.0 //////////////////////////////////////////////////////////////////////////////////// // initialize counterNode, set its initial buffer and playbackRate p5.SoundFile.prototype._initCounterNode = function () { var self = this; var now = ac.currentTime; var cNode = ac.createBufferSource(); // dispose of scope node if it already exists if (self._scopeNode) { self._scopeNode.disconnect(); self._scopeNode = null; } self._scopeNode = ac.createScriptProcessor(256, 1, 1); // create counter buffer of the same length as self.buffer cNode.buffer = _createCounterBuffer(self.buffer); cNode.playbackRate.setValueAtTime(self.playbackRate, now); cNode.connect(self._scopeNode); self._scopeNode.connect(p5.soundOut._silentNode); self._scopeNode.onaudioprocess = function (processEvent) { var inputBuffer = processEvent.inputBuffer.getChannelData(0); // update the lastPos self._lastPos = inputBuffer[inputBuffer.length - 1] || 0; // do any callbacks that have been scheduled self._onTimeUpdate(self._lastPos); }; return cNode; }; // initialize sourceNode, set its initial buffer and playbackRate p5.SoundFile.prototype._initSourceNode = function () { var self = this; var now = ac.currentTime; var bufferSourceNode = ac.createBufferSource(); bufferSourceNode.buffer = self.buffer; bufferSourceNode.playbackRate.setValueAtTime(self.playbackRate, now); return bufferSourceNode; }; var _createCounterBuffer = function (buffer) { var array = new Float32Array(buffer.length); var audioBuf = ac.createBuffer(1, buffer.length, 44100); for (var index = 0; index < buffer.length; index++) { array[index] = index; } audioBuf.getChannelData(0).set(array); return audioBuf; }; /** * processPeaks returns an array of timestamps where it thinks there is a beat. * * This is an asynchronous function that processes the soundfile in an offline audio context, * and sends the results to your callback function. * * The process involves running the soundfile through a lowpass filter, and finding all of the * peaks above the initial threshold. If the total number of peaks are below the minimum number of peaks, * it decreases the threshold and re-runs the analysis until either minPeaks or minThreshold are reached. * * @method processPeaks * @param {Function} callback a function to call once this data is returned * @param {Number} [initThreshold] initial threshold defaults to 0.9 * @param {Number} [minThreshold] minimum threshold defaults to 0.22 * @param {Number} [minPeaks] minimum number of peaks defaults to 200 * @return {Array} Array of timestamped peaks */ p5.SoundFile.prototype.processPeaks = function (callback, _initThreshold, _minThreshold, _minPeaks) { var bufLen = this.buffer.length; var sampleRate = this.buffer.sampleRate; var buffer = this.buffer; var initialThreshold = _initThreshold || 0.9, threshold = initialThreshold, minThreshold = _minThreshold || 0.22, minPeaks = _minPeaks || 200; // Create offline context var offlineContext = new OfflineAudioContext(1, bufLen, sampleRate); // create buffer source var source = offlineContext.createBufferSource(); source.buffer = buffer; // Create filter. TO DO: allow custom setting of filter var filter = offlineContext.createBiquadFilter(); filter.type = 'lowpass'; source.connect(filter); filter.connect(offlineContext.destination); // start playing at time:0 source.start(0); offlineContext.startRendering(); // Render the song // act on the result offlineContext.oncomplete = function (e) { var data = {}; var filteredBuffer = e.renderedBuffer; var bufferData = filteredBuffer.getChannelData(0); // step 1: // create Peak instances, add them to array, with strength and sampleIndex do { allPeaks = getPeaksAtThreshold(bufferData, threshold); threshold -= 0.005; } while (Object.keys(allPeaks).length < minPeaks && threshold >= minThreshold); // step 2: // find intervals for each peak in the sampleIndex, add tempos array var intervalCounts = countIntervalsBetweenNearbyPeaks(allPeaks); // step 3: find top tempos var groups = groupNeighborsByTempo(intervalCounts, filteredBuffer.sampleRate); // sort top intervals var topTempos = groups.sort(function (intA, intB) { return intB.count - intA.count; }).splice(0, 5); // set this SoundFile's tempo to the top tempo ?? this.tempo = topTempos[0].tempo; // step 4: // new array of peaks at top tempo within a bpmVariance var bpmVariance = 5; var tempoPeaks = getPeaksAtTopTempo(allPeaks, topTempos[0].tempo, filteredBuffer.sampleRate, bpmVariance); callback(tempoPeaks); }; }; // process peaks var Peak = function (amp, i) { this.sampleIndex = i; this.amplitude = amp; this.tempos = []; this.intervals = []; }; var allPeaks = []; // 1. for processPeaks() Function to identify peaks above a threshold // returns an array of peak indexes as frames (samples) of the original soundfile function getPeaksAtThreshold(data, threshold) { var peaksObj = {}; var length = data.length; for (var i = 0; i < length; i++) { if (data[i] > threshold) { var amp = data[i]; var peak = new Peak(amp, i); peaksObj[i] = peak; // Skip forward ~ 1/8s to get past this peak. i += 6000; } i++; } return peaksObj; } // 2. for processPeaks() function countIntervalsBetweenNearbyPeaks(peaksObj) { var intervalCounts = []; var peaksArray = Object.keys(peaksObj).sort(); for (var index = 0; index < peaksArray.length; index++) { // find intervals in comparison to nearby peaks for (var i = 0; i < 10; i++) { var startPeak = peaksObj[peaksArray[index]]; var endPeak = peaksObj[peaksArray[index + i]]; if (startPeak && endPeak) { var startPos = startPeak.sampleIndex; var endPos = endPeak.sampleIndex; var interval = endPos - startPos; // add a sample interval to the startPeek in the allPeaks array if (interval > 0) { startPeak.intervals.push(interval); } // tally the intervals and return interval counts var foundInterval = intervalCounts.some(function (intervalCount, p) { if (intervalCount.interval === interval) { intervalCount.count++; return intervalCount; } }); // store with JSON like formatting if (!foundInterval) { intervalCounts.push({ interval: interval, count: 1 }); } } } } return intervalCounts; } // 3. for processPeaks --> find tempo function groupNeighborsByTempo(intervalCounts, sampleRate) { var tempoCounts = []; intervalCounts.forEach(function (intervalCount, i) { try { // Convert an interval to tempo var theoreticalTempo = Math.abs(60 / (intervalCount.interval / sampleRate)); theoreticalTempo = mapTempo(theoreticalTempo); var foundTempo = tempoCounts.some(function (tempoCount) { if (tempoCount.tempo === theoreticalTempo) return tempoCount.count += intervalCount.count; }); if (!foundTempo) { if (isNaN(theoreticalTempo)) { return; } tempoCounts.push({ tempo: Math.round(theoreticalTempo), count: intervalCount.count }); } } catch (e) { throw e; } }); return tempoCounts; } // 4. for processPeaks - get peaks at top tempo function getPeaksAtTopTempo(peaksObj, tempo, sampleRate, bpmVariance) { var peaksAtTopTempo = []; var peaksArray = Object.keys(peaksObj).sort(); // TO DO: filter out peaks that have the tempo and return for (var i = 0; i < peaksArray.length; i++) { var key = peaksArray[i]; var peak = peaksObj[key]; for (var j = 0; j < peak.intervals.length; j++) { var intervalBPM = Math.round(Math.abs(60 / (peak.intervals[j] / sampleRate))); intervalBPM = mapTempo(intervalBPM); var dif = intervalBPM - tempo; if (Math.abs(intervalBPM - tempo) < bpmVariance) { // convert sampleIndex to seconds peaksAtTopTempo.push(peak.sampleIndex / 44100); } } } // filter out peaks that are very close to each other peaksAtTopTempo = peaksAtTopTempo.filter(function (peakTime, index, arr) { var dif = arr[index + 1] - peakTime; if (dif > 0.01) { return true; } }); return peaksAtTopTempo; } // helper function for processPeaks function mapTempo(theoreticalTempo) { // these scenarios create infinite while loop if (!isFinite(theoreticalTempo) || theoreticalTempo == 0) { return; } // Adjust the tempo to fit within the 90-180 BPM range while (theoreticalTempo < 90) theoreticalTempo *= 2; while (theoreticalTempo > 180 && theoreticalTempo > 90) theoreticalTempo /= 2; return theoreticalTempo; } /*** SCHEDULE EVENTS ***/ /** * Schedule events to trigger every time a MediaElement * (audio/video) reaches a playback cue point. * * Accepts a callback function, a time (in seconds) at which to trigger * the callback, and an optional parameter for the callback. * * Time will be passed as the first parameter to the callback function, * and param will be the second parameter. * * * @method addCue * @param {Number} time Time in seconds, relative to this media * element's playback. For example, to trigger * an event every time playback reaches two * seconds, pass in the number 2. This will be * passed as the first parameter to * the callback function. * @param {Function} callback Name of a function that will be * called at the given time. The callback will * receive time and (optionally) param as its * two parameters. * @param {Object} [value] An object to be passed as the * second parameter to the * callback function. * @return {Number} id ID of this cue, * useful for removeCue(id) * @example * <div><code> * function setup() { * background(0); * noStroke(); * fill(255); * textAlign(CENTER); * text('click to play', width/2, height/2); * * mySound = loadSound('assets/beat.mp3'); * * // schedule calls to changeText * mySound.addCue(0.50, changeText, "hello" ); * mySound.addCue(1.00, changeText, "p5" ); * mySound.addCue(1.50, changeText, "what" ); * mySound.addCue(2.00, changeText, "do" ); * mySound.addCue(2.50, changeText, "you" ); * mySound.addCue(3.00, changeText, "want" ); * mySound.addCue(4.00, changeText, "to" ); * mySound.addCue(5.00, changeText, "make" ); * mySound.addCue(6.00, changeText, "?" ); * } * * function changeText(val) { * background(0); * text(val, width/2, height/2); * } * * function mouseClicked() { * if (mouseX > 0 && mouseX < width && mouseY > 0 && mouseY < height) { * if (mySound.isPlaying() ) { * mySound.stop(); * } else { * mySound.play(); * } * } * } * </code></div> */ p5.SoundFile.prototype.addCue = function (time, callback, val) { var id = this._cueIDCounter++; var cue = new Cue(callback, time, id, val); this._cues.push(cue); // if (!this.elt.ontimeupdate) { // this.elt.ontimeupdate = this._onTimeUpdate.bind(this); // } return id; }; /** * Remove a callback based on its ID. The ID is returned by the * addCue method. * * @method removeCue * @param {Number} id ID of the cue, as returned by addCue */ p5.SoundFile.prototype.removeCue = function (id) { for (var i = 0; i < this._cues.length; i++) { var cue = this._cues[i]; if (cue.id === id) { this.cues.splice(i, 1); } } if (this._cues.length === 0) { } }; /** * Remove all of the callbacks that had originally been scheduled * via the addCue method. * * @method clearCues */ p5.SoundFile.prototype.clearCues = function () { this._cues = []; }; // private method that checks for cues to be fired if events // have been scheduled using addCue(callback, time). p5.SoundFile.prototype._onTimeUpdate = function (position) { var playbackTime = position / this.buffer.sampleRate; for (var i = 0; i < this._cues.length; i++) { var callbackTime = this._cues[i].time; var val = this._cues[i].val; if (this._prevTime < callbackTime && callbackTime <= playbackTime) { // pass the scheduled callbackTime as parameter to the callback this._cues[i].callback(val); } } this._prevTime = playbackTime; }; // Cue inspired by JavaScript setTimeout, and the // Tone.js Transport Timeline Event, MIT License Yotam Mann 2015 tonejs.org var Cue = function (callback, time, id, val) { this.callback = callback; this.time = time; this.id = id; this.val = val; }; }(sndcore, master); var amplitude; amplitude = function () { 'use strict'; var p5sound = master; /** * Amplitude measures volume between 0.0 and 1.0. * Listens to all p5sound by default, or use setInput() * to listen to a specific sound source. Accepts an optional * smoothing value, which defaults to 0. * * @class p5.Amplitude * @constructor * @param {Number} [smoothing] between 0.0 and .999 to smooth * amplitude readings (defaults to 0) * @return {Object} Amplitude Object * @example * <div><code> * var sound, amplitude, cnv; * * function preload(){ * sound = loadSound('assets/beat.mp3'); * } * function setup() { * cnv = createCanvas(100,100); * amplitude = new p5.Amplitude(); * * // start / stop the sound when canvas is clicked * cnv.mouseClicked(function() { * if (sound.isPlaying() ){ * sound.stop(); * } else { * sound.play(); * } * }); * } * function draw() { * background(0); * fill(255); * var level = amplitude.getLevel(); * var size = map(level, 0, 1, 0, 200); * ellipse(width/2, height/2, size, size); * } * * </code></div> */ p5.Amplitude = function (smoothing) { // Set to 2048 for now. In future iterations, this should be inherited or parsed from p5sound's default this.bufferSize = 2048; // set audio context this.audiocontext = p5sound.audiocontext; this.processor = this.audiocontext.createScriptProcessor(this.bufferSize, 2, 1); // for connections this.input = this.processor; this.output = this.audiocontext.createGain(); // smoothing defaults to 0 this.smoothing = smoothing || 0; // the variables to return this.volume = 0; this.average = 0; this.stereoVol = [ 0, 0 ]; this.stereoAvg = [ 0, 0 ]; this.stereoVolNorm = [ 0, 0 ]; this.volMax = 0.001; this.normalize = false; this.processor.onaudioprocess = this._audioProcess.bind(this); this.processor.connect(this.output); this.output.gain.value = 0; // this may only be necessary because of a Chrome bug this.output.connect(this.audiocontext.destination); // connect to p5sound master output by default, unless set by input() p5sound.meter.connect(this.processor); }; /** * Connects to the p5sound instance (master output) by default. * Optionally, you can pass in a specific source (i.e. a soundfile). * * @method setInput * @param {soundObject|undefined} [snd] set the sound source * (optional, defaults to * master output) * @param {Number|undefined} [smoothing] a range between 0.0 and 1.0 * to smooth amplitude readings * @example * <div><code> * function preload(){ * sound1 = loadSound('assets/beat.mp3'); * sound2 = loadSound('assets/drum.mp3'); * } * function setup(){ * amplitude = new p5.Amplitude(); * sound1.play(); * sound2.play(); * amplitude.setInput(sound2); * } * function draw() { * background(0); * fill(255); * var level = amplitude.getLevel(); * var size = map(level, 0, 1, 0, 200); * ellipse(width/2, height/2, size, size); * } * function mouseClicked(){ * sound1.stop(); * sound2.stop(); * } * </code></div> */ p5.Amplitude.prototype.setInput = function (source, smoothing) { p5sound.meter.disconnect(); if (smoothing) { this.smoothing = smoothing; } // connect to the master out of p5s instance if no snd is provided if (source == null) { console.log('Amplitude input source is not ready! Connecting to master output instead'); p5sound.meter.connect(this.processor); } else if (source instanceof p5.Signal) { source.output.connect(this.processor); } else if (source) { source.connect(this.processor); this.processor.disconnect(); this.processor.connect(this.output); } else { p5sound.meter.connect(this.processor); } }; p5.Amplitude.prototype.connect = function (unit) { if (unit) { if (unit.hasOwnProperty('input')) { this.output.connect(unit.input); } else { this.output.connect(unit); } } else { this.output.connect(this.panner.connect(p5sound.input)); } }; p5.Amplitude.prototype.disconnect = function (unit) { this.output.disconnect(); }; // TO DO make this stereo / dependent on # of audio channels p5.Amplitude.prototype._audioProcess = function (event) { for (var channel = 0; channel < event.inputBuffer.numberOfChannels; channel++) { var inputBuffer = event.inputBuffer.getChannelData(channel); var bufLength = inputBuffer.length; var total = 0; var sum = 0; var x; for (var i = 0; i < bufLength; i++) { x = inputBuffer[i]; if (this.normalize) { total += Math.max(Math.min(x / this.volMax, 1), -1); sum += Math.max(Math.min(x / this.volMax, 1), -1) * Math.max(Math.min(x / this.volMax, 1), -1); } else { total += x; sum += x * x; } } var average = total / bufLength; // ... then take the square root of the sum. var rms = Math.sqrt(sum / bufLength); this.stereoVol[channel] = Math.max(rms, this.stereoVol[channel] * this.smoothing); this.stereoAvg[channel] = Math.max(average, this.stereoVol[channel] * this.smoothing); this.volMax = Math.max(this.stereoVol[channel], this.volMax); } // add volume from all channels together var self = this; var volSum = this.stereoVol.reduce(function (previousValue, currentValue, index) { self.stereoVolNorm[index - 1] = Math.max(Math.min(self.stereoVol[index - 1] / self.volMax, 1), 0); self.stereoVolNorm[index] = Math.max(Math.min(self.stereoVol[index] / self.volMax, 1), 0); return previousValue + currentValue; }); // volume is average of channels this.volume = volSum / this.stereoVol.length; // normalized value this.volNorm = Math.max(Math.min(this.volume / this.volMax, 1), 0); }; /** * Returns a single Amplitude reading at the moment it is called. * For continuous readings, run in the draw loop. * * @method getLevel * @param {Number} [channel] Optionally return only channel 0 (left) or 1 (right) * @return {Number} Amplitude as a number between 0.0 and 1.0 * @example * <div><code> * function preload(){ * sound = loadSound('assets/beat.mp3'); * } * function setup() { * amplitude = new p5.Amplitude(); * sound.play(); * } * function draw() { * background(0); * fill(255); * var level = amplitude.getLevel(); * var size = map(level, 0, 1, 0, 200); * ellipse(width/2, height/2, size, size); * } * function mouseClicked(){ * sound.stop(); * } * </code></div> */ p5.Amplitude.prototype.getLevel = function (channel) { if (typeof channel !== 'undefined') { if (this.normalize) { return this.stereoVolNorm[channel]; } else { return this.stereoVol[channel]; } } else if (this.normalize) { return this.volNorm; } else { return this.volume; } }; /** * Determines whether the results of Amplitude.process() will be * Normalized. To normalize, Amplitude finds the difference the * loudest reading it has processed and the maximum amplitude of * 1.0. Amplitude adds this difference to all values to produce * results that will reliably map between 0.0 and 1.0. However, * if a louder moment occurs, the amount that Normalize adds to * all the values will change. Accepts an optional boolean parameter * (true or false). Normalizing is off by default. * * @method toggleNormalize * @param {boolean} [boolean] set normalize to true (1) or false (0) */ p5.Amplitude.prototype.toggleNormalize = function (bool) { if (typeof bool === 'boolean') { this.normalize = bool; } else { this.normalize = !this.normalize; } }; /** * Smooth Amplitude analysis by averaging with the last analysis * frame. Off by default. * * @method smooth * @param {Number} set smoothing from 0.0 <= 1 */ p5.Amplitude.prototype.smooth = function (s) { if (s >= 0 && s < 1) { this.smoothing = s; } else { console.log('Error: smoothing must be between 0 and 1'); } }; }(master); var fft; fft = function () { 'use strict'; var p5sound = master; /** * <p>FFT (Fast Fourier Transform) is an analysis algorithm that * isolates individual * <a href="https://en.wikipedia.org/wiki/Audio_frequency"> * audio frequencies</a> within a waveform.</p> * * <p>Once instantiated, a p5.FFT object can return an array based on * two types of analyses: <br> • <code>FFT.waveform()</code> computes * amplitude values along the time domain. The array indices correspond * to samples across a brief moment in time. Each value represents * amplitude of the waveform at that sample of time.<br> * • <code>FFT.analyze() </code> computes amplitude values along the * frequency domain. The array indices correspond to frequencies (i.e. * pitches), from the lowest to the highest that humans can hear. Each * value represents amplitude at that slice of the frequency spectrum. * Use with <code>getEnergy()</code> to measure amplitude at specific * frequencies, or within a range of frequencies. </p> * * <p>FFT analyzes a very short snapshot of sound called a sample * buffer. It returns an array of amplitude measurements, referred * to as <code>bins</code>. The array is 1024 bins long by default. * You can change the bin array length, but it must be a power of 2 * between 16 and 1024 in order for the FFT algorithm to function * correctly. The actual size of the FFT buffer is twice the * number of bins, so given a standard sample rate, the buffer is * 2048/44100 seconds long.</p> * * * @class p5.FFT * @constructor * @param {Number} [smoothing] Smooth results of Freq Spectrum. * 0.0 < smoothing < 1.0. * Defaults to 0.8. * @param {Number} [bins] Length of resulting array. * Must be a power of two between * 16 and 1024. Defaults to 1024. * @return {Object} FFT Object * @example * <div><code> * function preload(){ * sound = loadSound('assets/Damscray_DancingTiger.mp3'); * } * * function setup(){ * cnv = createCanvas(100,100); * sound.amp(0); * sound.loop(); * fft = new p5.FFT(); * } * * function draw(){ * background(0); * * var spectrum = fft.analyze(); * noStroke(); * fill(0,255,0); // spectrum is green * for (var i = 0; i< spectrum.length; i++){ * var x = map(i, 0, spectrum.length, 0, width); * var h = -height + map(spectrum[i], 0, 255, height, 0); * rect(x, height, width / spectrum.length, h ) * } * * var waveform = fft.waveform(); * noFill(); * beginShape(); * stroke(255,0,0); // waveform is red * strokeWeight(1); * for (var i = 0; i< waveform.length; i++){ * var x = map(i, 0, waveform.length, 0, width); * var y = map( waveform[i], -1, 1, 0, height); * vertex(x,y); * } * endShape(); * * isMouseOverCanvas(); * } * * // fade sound if mouse is over canvas * function isMouseOverCanvas() { * var mX = mouseX, mY = mouseY; * if (mX > 0 && mX < width && mY < height && mY > 0) { * sound.amp(0.5, 0.2); * } else { * sound.amp(0, 0.2); * } * } * </code></div> */ p5.FFT = function (smoothing, bins) { this.smoothing = smoothing || 0.8; this.bins = bins || 1024; var FFT_SIZE = bins * 2 || 2048; this.input = this.analyser = p5sound.audiocontext.createAnalyser(); // default connections to p5sound fftMeter p5sound.fftMeter.connect(this.analyser); this.analyser.smoothingTimeConstant = this.smoothing; this.analyser.fftSize = FFT_SIZE; this.freqDomain = new Uint8Array(this.analyser.frequencyBinCount); this.timeDomain = new Uint8Array(this.analyser.frequencyBinCount); // predefined frequency ranages, these will be tweakable this.bass = [ 20, 140 ]; this.lowMid = [ 140, 400 ]; this.mid = [ 400, 2600 ]; this.highMid = [ 2600, 5200 ]; this.treble = [ 5200, 14000 ]; }; /** * Set the input source for the FFT analysis. If no source is * provided, FFT will analyze all sound in the sketch. * * @method setInput * @param {Object} [source] p5.sound object (or web audio API source node) */ p5.FFT.prototype.setInput = function (source) { if (!source) { p5sound.fftMeter.connect(this.analyser); } else { if (source.output) { source.output.connect(this.analyser); } else if (source.connect) { source.connect(this.analyser); } p5sound.fftMeter.disconnect(); } }; /** * Returns an array of amplitude values (between -1.0 and +1.0) that represent * a snapshot of amplitude readings in a single buffer. Length will be * equal to bins (defaults to 1024). Can be used to draw the waveform * of a sound. * * @method waveform * @param {Number} [bins] Must be a power of two between * 16 and 1024. Defaults to 1024. * @param {String} [precision] If any value is provided, will return results * in a Float32 Array which is more precise * than a regular array. * @return {Array} Array Array of amplitude values (-1 to 1) * over time. Array length = bins. * */ p5.FFT.prototype.waveform = function () { var bins, mode, normalArray; for (var i = 0; i < arguments.length; i++) { if (typeof arguments[i] === 'number') { bins = arguments[i]; this.analyser.fftSize = bins * 2; } if (typeof arguments[i] === 'string') { mode = arguments[i]; } } // getFloatFrequencyData doesnt work in Safari as of 5/2015 if (mode && !p5.prototype._isSafari()) { timeToFloat(this, this.timeDomain); this.analyser.getFloatTimeDomainData(this.timeDomain); return this.timeDomain; } else { timeToInt(this, this.timeDomain); this.analyser.getByteTimeDomainData(this.timeDomain); var normalArray = new Array(); for (var i = 0; i < this.timeDomain.length; i++) { var scaled = p5.prototype.map(this.timeDomain[i], 0, 255, -1, 1); normalArray.push(scaled); } return normalArray; } }; /** * Returns an array of amplitude values (between 0 and 255) * across the frequency spectrum. Length is equal to FFT bins * (1024 by default). The array indices correspond to frequencies * (i.e. pitches), from the lowest to the highest that humans can * hear. Each value represents amplitude at that slice of the * frequency spectrum. Must be called prior to using * <code>getEnergy()</code>. * * @method analyze * @param {Number} [bins] Must be a power of two between * 16 and 1024. Defaults to 1024. * @param {Number} [scale] If "dB," returns decibel * float measurements between * -140 and 0 (max). * Otherwise returns integers from 0-255. * @return {Array} spectrum Array of energy (amplitude/volume) * values across the frequency spectrum. * Lowest energy (silence) = 0, highest * possible is 255. * @example * <div><code> * var osc; * var fft; * * function setup(){ * createCanvas(100,100); * osc = new p5.Oscillator(); * osc.amp(0); * osc.start(); * fft = new p5.FFT(); * } * * function draw(){ * background(0); * * var freq = map(mouseX, 0, 800, 20, 15000); * freq = constrain(freq, 1, 20000); * osc.freq(freq); * * var spectrum = fft.analyze(); * noStroke(); * fill(0,255,0); // spectrum is green * for (var i = 0; i< spectrum.length; i++){ * var x = map(i, 0, spectrum.length, 0, width); * var h = -height + map(spectrum[i], 0, 255, height, 0); * rect(x, height, width / spectrum.length, h ); * } * * stroke(255); * text('Freq: ' + round(freq)+'Hz', 10, 10); * * isMouseOverCanvas(); * } * * // only play sound when mouse is over canvas * function isMouseOverCanvas() { * var mX = mouseX, mY = mouseY; * if (mX > 0 && mX < width && mY < height && mY > 0) { * osc.amp(0.5, 0.2); * } else { * osc.amp(0, 0.2); * } * } * </code></div> * * */ p5.FFT.prototype.analyze = function () { var bins, mode; for (var i = 0; i < arguments.length; i++) { if (typeof arguments[i] === 'number') { bins = this.bins = arguments[i]; this.analyser.fftSize = this.bins * 2; } if (typeof arguments[i] === 'string') { mode = arguments[i]; } } if (mode && mode.toLowerCase() === 'db') { freqToFloat(this); this.analyser.getFloatFrequencyData(this.freqDomain); return this.freqDomain; } else { freqToInt(this, this.freqDomain); this.analyser.getByteFrequencyData(this.freqDomain); var normalArray = Array.apply([], this.freqDomain); normalArray.length === this.analyser.fftSize; normalArray.constructor === Array; return normalArray; } }; /** * Returns the amount of energy (volume) at a specific * <a href="en.wikipedia.org/wiki/Audio_frequency" target="_blank"> * frequency</a>, or the average amount of energy between two * frequencies. Accepts Number(s) corresponding * to frequency (in Hz), or a String corresponding to predefined * frequency ranges ("bass", "lowMid", "mid", "highMid", "treble"). * Returns a range between 0 (no energy/volume at that frequency) and * 255 (maximum energy). * <em>NOTE: analyze() must be called prior to getEnergy(). Analyze() * tells the FFT to analyze frequency data, and getEnergy() uses * the results determine the value at a specific frequency or * range of frequencies.</em></p> * * @method getEnergy * @param {Number|String} frequency1 Will return a value representing * energy at this frequency. Alternately, * the strings "bass", "lowMid" "mid", * "highMid", and "treble" will return * predefined frequency ranges. * @param {Number} [frequency2] If a second frequency is given, * will return average amount of * energy that exists between the * two frequencies. * @return {Number} Energy Energy (volume/amplitude) from * 0 and 255. * */ p5.FFT.prototype.getEnergy = function (frequency1, frequency2) { var nyquist = p5sound.audiocontext.sampleRate / 2; if (frequency1 === 'bass') { frequency1 = this.bass[0]; frequency2 = this.bass[1]; } else if (frequency1 === 'lowMid') { frequency1 = this.lowMid[0]; frequency2 = this.lowMid[1]; } else if (frequency1 === 'mid') { frequency1 = this.mid[0]; frequency2 = this.mid[1]; } else if (frequency1 === 'highMid') { frequency1 = this.highMid[0]; frequency2 = this.highMid[1]; } else if (frequency1 === 'treble') { frequency1 = this.treble[0]; frequency2 = this.treble[1]; } if (typeof frequency1 !== 'number') { throw 'invalid input for getEnergy()'; } else if (!frequency2) { var index = Math.round(frequency1 / nyquist * this.freqDomain.length); return this.freqDomain[index]; } else if (frequency1 && frequency2) { // if second is higher than first if (frequency1 > frequency2) { var swap = frequency2; frequency2 = frequency1; frequency1 = swap; } var lowIndex = Math.round(frequency1 / nyquist * this.freqDomain.length); var highIndex = Math.round(frequency2 / nyquist * this.freqDomain.length); var total = 0; var numFrequencies = 0; // add up all of the values for the frequencies for (var i = lowIndex; i <= highIndex; i++) { total += this.freqDomain[i]; numFrequencies += 1; } // divide by total number of frequencies var toReturn = total / numFrequencies; return toReturn; } else { throw 'invalid input for getEnergy()'; } }; // compatability with v.012, changed to getEnergy in v.0121. Will be deprecated... p5.FFT.prototype.getFreq = function (freq1, freq2) { console.log('getFreq() is deprecated. Please use getEnergy() instead.'); var x = this.getEnergy(freq1, freq2); return x; }; /** * Smooth FFT analysis by averaging with the last analysis frame. * * @method smooth * @param {Number} smoothing 0.0 < smoothing < 1.0. * Defaults to 0.8. */ p5.FFT.prototype.smooth = function (s) { if (s) { this.smoothing = s; } this.analyser.smoothingTimeConstant = s; }; // helper methods to convert type from float (dB) to int (0-255) var freqToFloat = function (fft) { if (fft.freqDomain instanceof Float32Array === false) { fft.freqDomain = new Float32Array(fft.analyser.frequencyBinCount); } }; var freqToInt = function (fft) { if (fft.freqDomain instanceof Uint8Array === false) { fft.freqDomain = new Uint8Array(fft.analyser.frequencyBinCount); } }; var timeToFloat = function (fft) { if (fft.timeDomain instanceof Float32Array === false) { fft.timeDomain = new Float32Array(fft.analyser.frequencyBinCount); } }; var timeToInt = function (fft) { if (fft.timeDomain instanceof Uint8Array === false) { fft.timeDomain = new Uint8Array(fft.analyser.frequencyBinCount); } }; }(master); /** Tone.js module by Yotam Mann, MIT License 2014 http://opensource.org/licenses/MIT **/ var Tone_core_Tone; Tone_core_Tone = function () { 'use strict'; function isUndef(val) { return val === void 0; } var audioContext; if (isUndef(window.AudioContext)) { window.AudioContext = window.webkitAudioContext; } if (isUndef(window.OfflineAudioContext)) { window.OfflineAudioContext = window.webkitOfflineAudioContext; } if (!isUndef(AudioContext)) { audioContext = new AudioContext(); } else { throw new Error('Web Audio is not supported in this browser'); } if (typeof AudioContext.prototype.createGain !== 'function') { AudioContext.prototype.createGain = AudioContext.prototype.createGainNode; } if (typeof AudioContext.prototype.createDelay !== 'function') { AudioContext.prototype.createDelay = AudioContext.prototype.createDelayNode; } if (typeof AudioContext.prototype.createPeriodicWave !== 'function') { AudioContext.prototype.createPeriodicWave = AudioContext.prototype.createWaveTable; } if (typeof AudioBufferSourceNode.prototype.start !== 'function') { AudioBufferSourceNode.prototype.start = AudioBufferSourceNode.prototype.noteGrainOn; } if (typeof AudioBufferSourceNode.prototype.stop !== 'function') { AudioBufferSourceNode.prototype.stop = AudioBufferSourceNode.prototype.noteOff; } if (typeof OscillatorNode.prototype.start !== 'function') { OscillatorNode.prototype.start = OscillatorNode.prototype.noteOn; } if (typeof OscillatorNode.prototype.stop !== 'function') { OscillatorNode.prototype.stop = OscillatorNode.prototype.noteOff; } if (typeof OscillatorNode.prototype.setPeriodicWave !== 'function') { OscillatorNode.prototype.setPeriodicWave = OscillatorNode.prototype.setWaveTable; } if (!window.Tone) { AudioNode.prototype._nativeConnect = AudioNode.prototype.connect; AudioNode.prototype.connect = function (B, outNum, inNum) { if (B.input) { if (Array.isArray(B.input)) { if (isUndef(inNum)) { inNum = 0; } this.connect(B.input[inNum]); } else { this.connect(B.input, outNum, inNum); } } else { try { if (B instanceof AudioNode) { this._nativeConnect(B, outNum, inNum); } else { this._nativeConnect(B, outNum); } } catch (e) { throw new Error('error connecting to node: ' + B); } } }; } var Tone = function (inputs, outputs) { if (isUndef(inputs) || inputs === 1) { this.input = this.context.createGain(); } else if (inputs > 1) { this.input = new Array(inputs); } if (isUndef(outputs) || outputs === 1) { this.output = this.context.createGain(); } else if (outputs > 1) { this.output = new Array(inputs); } }; Tone.context = audioContext; Tone.prototype.context = Tone.context; Tone.prototype.bufferSize = 2048; Tone.prototype.bufferTime = Tone.prototype.bufferSize / Tone.context.sampleRate; Tone.prototype.connect = function (unit, outputNum, inputNum) { if (Array.isArray(this.output)) { outputNum = this.defaultArg(outputNum, 0); this.output[outputNum].connect(unit, 0, inputNum); } else { this.output.connect(unit, outputNum, inputNum); } }; Tone.prototype.disconnect = function (outputNum) { if (Array.isArray(this.output)) { outputNum = this.defaultArg(outputNum, 0); this.output[outputNum].disconnect(); } else { this.output.disconnect(); } }; Tone.prototype.connectSeries = function () { if (arguments.length > 1) { var currentUnit = arguments[0]; for (var i = 1; i < arguments.length; i++) { var toUnit = arguments[i]; currentUnit.connect(toUnit); currentUnit = toUnit; } } }; Tone.prototype.connectParallel = function () { var connectFrom = arguments[0]; if (arguments.length > 1) { for (var i = 1; i < arguments.length; i++) { var connectTo = arguments[i]; connectFrom.connect(connectTo); } } }; Tone.prototype.chain = function () { if (arguments.length > 0) { var currentUnit = this; for (var i = 0; i < arguments.length; i++) { var toUnit = arguments[i]; currentUnit.connect(toUnit); currentUnit = toUnit; } } }; Tone.prototype.fan = function () { if (arguments.length > 0) { for (var i = 1; i < arguments.length; i++) { this.connect(arguments[i]); } } }; AudioNode.prototype.chain = Tone.prototype.chain; AudioNode.prototype.fan = Tone.prototype.fan; Tone.prototype.defaultArg = function (given, fallback) { if (typeof given === 'object' && typeof fallback === 'object') { var ret = {}; for (var givenProp in given) { ret[givenProp] = this.defaultArg(given[givenProp], given[givenProp]); } for (var prop in fallback) { ret[prop] = this.defaultArg(given[prop], fallback[prop]); } return ret; } else { return isUndef(given) ? fallback : given; } }; Tone.prototype.optionsObject = function (values, keys, defaults) { var options = {}; if (values.length === 1 && typeof values[0] === 'object') { options = values[0]; } else { for (var i = 0; i < keys.length; i++) { options[keys[i]] = values[i]; } } if (!this.isUndef(defaults)) { return this.defaultArg(options, defaults); } else { return options; } }; Tone.prototype.isUndef = isUndef; Tone.prototype.equalPowerScale = function (percent) { var piFactor = 0.5 * Math.PI; return Math.sin(percent * piFactor); }; Tone.prototype.logScale = function (gain) { return Math.max(this.normalize(this.gainToDb(gain), -100, 0), 0); }; Tone.prototype.expScale = function (gain) { return this.dbToGain(this.interpolate(gain, -100, 0)); }; Tone.prototype.dbToGain = function (db) { return Math.pow(2, db / 6); }; Tone.prototype.gainToDb = function (gain) { return 20 * (Math.log(gain) / Math.LN10); }; Tone.prototype.interpolate = function (input, outputMin, outputMax) { return input * (outputMax - outputMin) + outputMin; }; Tone.prototype.normalize = function (input, inputMin, inputMax) { if (inputMin > inputMax) { var tmp = inputMax; inputMax = inputMin; inputMin = tmp; } else if (inputMin == inputMax) { return 0; } return (input - inputMin) / (inputMax - inputMin); }; Tone.prototype.dispose = function () { if (!this.isUndef(this.input)) { if (this.input instanceof AudioNode) { this.input.disconnect(); } this.input = null; } if (!this.isUndef(this.output)) { if (this.output instanceof AudioNode) { this.output.disconnect(); } this.output = null; } }; var _silentNode = null; Tone.prototype.noGC = function () { this.output.connect(_silentNode); }; AudioNode.prototype.noGC = function () { this.connect(_silentNode); }; Tone.prototype.now = function () { return this.context.currentTime; }; Tone.prototype.samplesToSeconds = function (samples) { return samples / this.context.sampleRate; }; Tone.prototype.toSamples = function (time) { var seconds = this.toSeconds(time); return Math.round(seconds * this.context.sampleRate); }; Tone.prototype.toSeconds = function (time, now) { now = this.defaultArg(now, this.now()); if (typeof time === 'number') { return time; } else if (typeof time === 'string') { var plusTime = 0; if (time.charAt(0) === '+') { time = time.slice(1); plusTime = now; } return parseFloat(time) + plusTime; } else { return now; } }; Tone.prototype.frequencyToSeconds = function (freq) { return 1 / parseFloat(freq); }; Tone.prototype.secondsToFrequency = function (seconds) { return 1 / seconds; }; var newContextCallbacks = []; Tone._initAudioContext = function (callback) { callback(Tone.context); newContextCallbacks.push(callback); }; Tone.setContext = function (ctx) { Tone.prototype.context = ctx; Tone.context = ctx; for (var i = 0; i < newContextCallbacks.length; i++) { newContextCallbacks[i](ctx); } }; Tone.extend = function (child, parent) { if (isUndef(parent)) { parent = Tone; } function TempConstructor() { } TempConstructor.prototype = parent.prototype; child.prototype = new TempConstructor(); child.prototype.constructor = child; }; Tone.startMobile = function () { var osc = Tone.context.createOscillator(); var silent = Tone.context.createGain(); silent.gain.value = 0; osc.connect(silent); silent.connect(Tone.context.destination); var now = Tone.context.currentTime; osc.start(now); osc.stop(now + 1); }; Tone._initAudioContext(function (audioContext) { Tone.prototype.bufferTime = Tone.prototype.bufferSize / audioContext.sampleRate; _silentNode = audioContext.createGain(); _silentNode.gain.value = 0; _silentNode.connect(audioContext.destination); }); return Tone; }(); /** Tone.js module by Yotam Mann, MIT License 2014 http://opensource.org/licenses/MIT **/ var Tone_signal_SignalBase; Tone_signal_SignalBase = function (Tone) { 'use strict'; Tone.SignalBase = function () { }; Tone.extend(Tone.SignalBase); Tone.SignalBase.prototype.connect = function (node, outputNumber, inputNumber) { if (node instanceof Tone.Signal) { node.setValue(0); } else if (node instanceof AudioParam) { node.value = 0; } Tone.prototype.connect.call(this, node, outputNumber, inputNumber); }; Tone.SignalBase.prototype.dispose = function () { Tone.prototype.dispose.call(this); }; return Tone.SignalBase; }(Tone_core_Tone); /** Tone.js module by Yotam Mann, MIT License 2014 http://opensource.org/licenses/MIT **/ var Tone_signal_WaveShaper; Tone_signal_WaveShaper = function (Tone) { 'use strict'; Tone.WaveShaper = function (mapping, bufferLen) { this._shaper = this.input = this.output = this.context.createWaveShaper(); this._curve = null; if (Array.isArray(mapping)) { this.setCurve(mapping); } else if (isFinite(mapping) || this.isUndef(mapping)) { this._curve = new Float32Array(this.defaultArg(mapping, 1024)); } else if (typeof mapping === 'function') { this._curve = new Float32Array(this.defaultArg(bufferLen, 1024)); this.setMap(mapping); } }; Tone.extend(Tone.WaveShaper, Tone.SignalBase); Tone.WaveShaper.prototype.setMap = function (mapping) { for (var i = 0, len = this._curve.length; i < len; i++) { var normalized = i / len * 2 - 1; var normOffOne = i / (len - 1) * 2 - 1; this._curve[i] = mapping(normalized, i, normOffOne); } this._shaper.curve = this._curve; }; Tone.WaveShaper.prototype.setCurve = function (mapping) { if (this._isSafari()) { var first = mapping[0]; mapping.unshift(first); } this._curve = new Float32Array(mapping); this._shaper.curve = this._curve; }; Tone.WaveShaper.prototype.setOversample = function (oversampling) { this._shaper.oversample = oversampling; }; Tone.WaveShaper.prototype._isSafari = function () { var ua = navigator.userAgent.toLowerCase(); return ua.indexOf('safari') !== -1 && ua.indexOf('chrome') === -1; }; Tone.WaveShaper.prototype.dispose = function () { Tone.prototype.dispose.call(this); this._shaper.disconnect(); this._shaper = null; this._curve = null; }; return Tone.WaveShaper; }(Tone_core_Tone); /** Tone.js module by Yotam Mann, MIT License 2014 http://opensource.org/licenses/MIT **/ var Tone_signal_Signal; Tone_signal_Signal = function (Tone) { 'use strict'; Tone.Signal = function (value) { this._scalar = this.context.createGain(); this.input = this.output = this.context.createGain(); this._syncRatio = 1; this.value = this.defaultArg(value, 0); Tone.Signal._constant.chain(this._scalar, this.output); }; Tone.extend(Tone.Signal, Tone.SignalBase); Tone.Signal.prototype.getValue = function () { return this._scalar.gain.value; }; Tone.Signal.prototype.setValue = function (value) { if (this._syncRatio === 0) { value = 0; } else { value *= this._syncRatio; } this._scalar.gain.value = value; }; Tone.Signal.prototype.setValueAtTime = function (value, time) { value *= this._syncRatio; this._scalar.gain.setValueAtTime(value, this.toSeconds(time)); }; Tone.Signal.prototype.setCurrentValueNow = function (now) { now = this.defaultArg(now, this.now()); var currentVal = this.getValue(); this.cancelScheduledValues(now); this._scalar.gain.setValueAtTime(currentVal, now); return currentVal; }; Tone.Signal.prototype.linearRampToValueAtTime = function (value, endTime) { value *= this._syncRatio; this._scalar.gain.linearRampToValueAtTime(value, this.toSeconds(endTime)); }; Tone.Signal.prototype.exponentialRampToValueAtTime = function (value, endTime) { value *= this._syncRatio; try { this._scalar.gain.exponentialRampToValueAtTime(value, this.toSeconds(endTime)); } catch (e) { this._scalar.gain.linearRampToValueAtTime(value, this.toSeconds(endTime)); } }; Tone.Signal.prototype.exponentialRampToValueNow = function (value, endTime) { var now = this.now(); this.setCurrentValueNow(now); if (endTime.toString().charAt(0) === '+') { endTime = endTime.substr(1); } this.exponentialRampToValueAtTime(value, now + this.toSeconds(endTime)); }; Tone.Signal.prototype.linearRampToValueNow = function (value, endTime) { var now = this.now(); this.setCurrentValueNow(now); value *= this._syncRatio; if (endTime.toString().charAt(0) === '+') { endTime = endTime.substr(1); } this._scalar.gain.linearRampToValueAtTime(value, now + this.toSeconds(endTime)); }; Tone.Signal.prototype.setTargetAtTime = function (value, startTime, timeConstant) { value *= this._syncRatio; this._scalar.gain.setTargetAtTime(value, this.toSeconds(startTime), timeConstant); }; Tone.Signal.prototype.setValueCurveAtTime = function (values, startTime, duration) { for (var i = 0; i < values.length; i++) { values[i] *= this._syncRatio; } this._scalar.gain.setValueCurveAtTime(values, this.toSeconds(startTime), this.toSeconds(duration)); }; Tone.Signal.prototype.cancelScheduledValues = function (startTime) { this._scalar.gain.cancelScheduledValues(this.toSeconds(startTime)); }; Tone.Signal.prototype.sync = function (signal, ratio) { if (ratio) { this._syncRatio = ratio; } else { if (signal.getValue() !== 0) { this._syncRatio = this.getValue() / signal.getValue(); } else { this._syncRatio = 0; } } this._scalar.disconnect(); this._scalar = this.context.createGain(); this.connectSeries(signal, this._scalar, this.output); this._scalar.gain.value = this._syncRatio; }; Tone.Signal.prototype.unsync = function () { var currentGain = this.getValue(); this._scalar.disconnect(); this._scalar = this.context.createGain(); this._scalar.gain.value = currentGain / this._syncRatio; this._syncRatio = 1; Tone.Signal._constant.chain(this._scalar, this.output); }; Tone.Signal.prototype.dispose = function () { Tone.prototype.dispose.call(this); this._scalar.disconnect(); this._scalar = null; }; Object.defineProperty(Tone.Signal.prototype, 'value', { get: function () { return this.getValue(); }, set: function (val) { this.setValue(val); } }); Tone.Signal._generator = null; Tone.Signal._constant = null; Tone._initAudioContext(function (audioContext) { Tone.Signal._generator = audioContext.createOscillator(); Tone.Signal._constant = new Tone.WaveShaper([ 1, 1 ]); Tone.Signal._generator.connect(Tone.Signal._constant); Tone.Signal._generator.start(0); Tone.Signal._generator.noGC(); }); return Tone.Signal; }(Tone_core_Tone); /** Tone.js module by Yotam Mann, MIT License 2014 http://opensource.org/licenses/MIT **/ var Tone_signal_Add; Tone_signal_Add = function (Tone) { 'use strict'; Tone.Add = function (value) { Tone.call(this, 2, 0); this._sum = this.input[0] = this.input[1] = this.output = this.context.createGain(); this._value = null; if (isFinite(value)) { this._value = new Tone.Signal(value); this._value.connect(this._sum); } }; Tone.extend(Tone.Add, Tone.SignalBase); Tone.Add.prototype.setValue = function (value) { if (this._value !== null) { this._value.setValue(value); } else { throw new Error('cannot switch from signal to number'); } }; Tone.Add.prototype.dispose = function () { Tone.prototype.dispose.call(this); this._sum = null; if (this._value) { this._value.dispose(); this._value = null; } }; return Tone.Add; }(Tone_core_Tone); /** Tone.js module by Yotam Mann, MIT License 2014 http://opensource.org/licenses/MIT **/ var Tone_signal_Multiply; Tone_signal_Multiply = function (Tone) { 'use strict'; Tone.Multiply = function (value) { Tone.call(this, 2, 0); this._mult = this.input[0] = this.output = this.context.createGain(); this._factor = this.input[1] = this.output.gain; this._factor.value = this.defaultArg(value, 0); }; Tone.extend(Tone.Multiply, Tone.SignalBase); Tone.Multiply.prototype.setValue = function (value) { this._factor.value = value; }; Tone.Multiply.prototype.dispose = function () { Tone.prototype.dispose.call(this); this._mult = null; this._factor = null; }; return Tone.Multiply; }(Tone_core_Tone); /** Tone.js module by Yotam Mann, MIT License 2014 http://opensource.org/licenses/MIT **/ var Tone_signal_Scale; Tone_signal_Scale = function (Tone) { 'use strict'; Tone.Scale = function (outputMin, outputMax) { this._outputMin = this.defaultArg(outputMin, 0); this._outputMax = this.defaultArg(outputMax, 1); this._scale = this.input = new Tone.Multiply(1); this._add = this.output = new Tone.Add(0); this._scale.connect(this._add); this._setRange(); }; Tone.extend(Tone.Scale, Tone.SignalBase); Tone.Scale.prototype.setMin = function (min) { this._outputMin = min; this._setRange(); }; Tone.Scale.prototype.setMax = function (max) { this._outputMax = max; this._setRange(); }; Tone.Scale.prototype._setRange = function () { this._add.setValue(this._outputMin); this._scale.setValue(this._outputMax - this._outputMin); }; Tone.Scale.prototype.dispose = function () { Tone.prototype.dispose.call(this); this._add.dispose(); this._add = null; this._scale.dispose(); this._scale = null; }; return Tone.Scale; }(Tone_core_Tone, Tone_signal_Add, Tone_signal_Multiply); var signal; signal = function () { 'use strict'; // Signal is built with the Tone.js signal by Yotam Mann // https://github.com/TONEnoTONE/Tone.js/ var Signal = Tone_signal_Signal; var Add = Tone_signal_Add; var Mult = Tone_signal_Multiply; var Scale = Tone_signal_Scale; var Tone = Tone_core_Tone; var p5sound = master; Tone.setContext(p5sound.audiocontext); /** * <p>p5.Signal is a constant audio-rate signal used by p5.Oscillator * and p5.Envelope for modulation math.</p> * * <p>This is necessary because Web Audio is processed on a seprate clock. * For example, the p5 draw loop runs about 60 times per second. But * the audio clock must process samples 44100 times per second. If we * want to add a value to each of those samples, we can't do it in the * draw loop, but we can do it by adding a constant-rate audio signal.</p. * * <p>This class mostly functions behind the scenes in p5.sound, and returns * a Tone.Signal from the Tone.js library by Yotam Mann. * If you want to work directly with audio signals for modular * synthesis, check out * <a href='http://bit.ly/1oIoEng' target=_'blank'>tone.js.</a></p> * * @class p5.Signal * @constructor * @return {Tone.Signal} A Signal object from the Tone.js library * @example * <div><code> * function setup() { * carrier = new p5.Oscillator('sine'); * carrier.amp(1); // set amplitude * carrier.freq(220); // set frequency * carrier.start(); // start oscillating * * modulator = new p5.Oscillator('sawtooth'); * modulator.disconnect(); * modulator.amp(1); * modulator.freq(4); * modulator.start(); * * // Modulator's default amplitude range is -1 to 1. * // Multiply it by -200, so the range is -200 to 200 * // then add 220 so the range is 20 to 420 * carrier.freq( modulator.mult(-200).add(220) ); * } * </code></div> */ p5.Signal = function (value) { var s = new Signal(value); // p5sound.soundArray.push(s); return s; }; /** * Fade to value, for smooth transitions * * @method fade * @param {Number} value Value to set this signal * @param {[Number]} secondsFromNow Length of fade, in seconds from now */ Signal.prototype.fade = Signal.prototype.linearRampToValueAtTime; Mult.prototype.fade = Signal.prototype.fade; Add.prototype.fade = Signal.prototype.fade; Scale.prototype.fade = Signal.prototype.fade; /** * Connect a p5.sound object or Web Audio node to this * p5.Signal so that its amplitude values can be scaled. * * @param {Object} input */ Signal.prototype.setInput = function (_input) { _input.connect(this); }; Mult.prototype.setInput = Signal.prototype.setInput; Add.prototype.setInput = Signal.prototype.setInput; Scale.prototype.setInput = Signal.prototype.setInput; // signals can add / mult / scale themselves /** * Add a constant value to this audio signal, * and return the resulting audio signal. Does * not change the value of the original signal, * instead it returns a new p5.SignalAdd. * * @method add * @param {Number} number * @return {p5.SignalAdd} object */ Signal.prototype.add = function (num) { var add = new Add(num); // add.setInput(this); this.connect(add); return add; }; Mult.prototype.add = Signal.prototype.add; Add.prototype.add = Signal.prototype.add; Scale.prototype.add = Signal.prototype.add; /** * Multiply this signal by a constant value, * and return the resulting audio signal. Does * not change the value of the original signal, * instead it returns a new p5.SignalMult. * * @method mult * @param {Number} number to multiply * @return {Tone.Multiply} object */ Signal.prototype.mult = function (num) { var mult = new Mult(num); // mult.setInput(this); this.connect(mult); return mult; }; Mult.prototype.mult = Signal.prototype.mult; Add.prototype.mult = Signal.prototype.mult; Scale.prototype.mult = Signal.prototype.mult; /** * Scale this signal value to a given range, * and return the result as an audio signal. Does * not change the value of the original signal, * instead it returns a new p5.SignalScale. * * @method scale * @param {Number} number to multiply * @param {Number} inMin input range minumum * @param {Number} inMax input range maximum * @param {Number} outMin input range minumum * @param {Number} outMax input range maximum * @return {p5.SignalScale} object */ Signal.prototype.scale = function (inMin, inMax, outMin, outMax) { var mapOutMin, mapOutMax; if (arguments.length === 4) { mapOutMin = p5.prototype.map(outMin, inMin, inMax, 0, 1) - 0.5; mapOutMax = p5.prototype.map(outMax, inMin, inMax, 0, 1) - 0.5; } else { mapOutMin = arguments[0]; mapOutMax = arguments[1]; } var scale = new Scale(mapOutMin, mapOutMax); this.connect(scale); return scale; }; Mult.prototype.scale = Signal.prototype.scale; Add.prototype.scale = Signal.prototype.scale; Scale.prototype.scale = Signal.prototype.scale; }(Tone_signal_Signal, Tone_signal_Add, Tone_signal_Multiply, Tone_signal_Scale, Tone_core_Tone, master); var oscillator; oscillator = function () { 'use strict'; var p5sound = master; var Signal = Tone_signal_Signal; var Add = Tone_signal_Add; var Mult = Tone_signal_Multiply; var Scale = Tone_signal_Scale; /** * <p>Creates a signal that oscillates between -1.0 and 1.0. * By default, the oscillation takes the form of a sinusoidal * shape ('sine'). Additional types include 'triangle', * 'sawtooth' and 'square'. The frequency defaults to * 440 oscillations per second (440Hz, equal to the pitch of an * 'A' note).</p> * * <p>Set the type of oscillation with setType(), or by creating a * specific oscillator.</p> For example: * <code>new p5.SinOsc(freq)</code> * <code>new p5.TriOsc(freq)</code> * <code>new p5.SqrOsc(freq)</code> * <code>new p5.SawOsc(freq)</code>. * </p> * * @class p5.Oscillator * @constructor * @param {Number} [freq] frequency defaults to 440Hz * @param {String} [type] type of oscillator. Options: * 'sine' (default), 'triangle', * 'sawtooth', 'square' * @return {Object} Oscillator object * @example * <div><code> * var osc; * var playing = false; * * function setup() { * backgroundColor = color(255,0,255); * textAlign(CENTER); * * osc = new p5.Oscillator(); * osc.setType('sine'); * osc.freq(240); * osc.amp(0); * osc.start(); * } * * function draw() { * background(backgroundColor) * text('click to play', width/2, height/2); * } * * function mouseClicked() { * if (mouseX > 0 && mouseX < width && mouseY < height && mouseY > 0) { * if (!playing) { * // ramp amplitude to 0.5 over 0.1 seconds * osc.amp(0.5, 0.05); * playing = true; * backgroundColor = color(0,255,255); * } else { * // ramp amplitude to 0 over 0.5 seconds * osc.amp(0, 0.5); * playing = false; * backgroundColor = color(255,0,255); * } * } * } * </code> </div> */ p5.Oscillator = function (freq, type) { if (typeof freq === 'string') { var f = type; type = freq; freq = f; } if (typeof type === 'number') { var f = type; type = freq; freq = f; } this.started = false; // components this.oscillator = p5sound.audiocontext.createOscillator(); this.f = freq || 440; // frequency this.oscillator.frequency.setValueAtTime(this.f, p5sound.audiocontext.currentTime); this.oscillator.type = type || 'sine'; var o = this.oscillator; // connections this.input = p5sound.audiocontext.createGain(); this.output = p5sound.audiocontext.createGain(); this._freqMods = []; // modulators connected to this oscillator's frequency // set default output gain to 0.5 this.output.gain.value = 0.5; this.output.gain.setValueAtTime(0.5, p5sound.audiocontext.currentTime); this.oscillator.connect(this.output); // stereo panning this.panPosition = 0; this.connection = p5sound.input; // connect to p5sound by default this.panner = new p5.Panner(this.output, this.connection, 1); //array of math operation signal chaining this.mathOps = [this.output]; // add to the soundArray so we can dispose of the osc later p5sound.soundArray.push(this); }; /** * Start an oscillator. Accepts an optional parameter to * determine how long (in seconds from now) until the * oscillator starts. * * @method start * @param {Number} [time] startTime in seconds from now. * @param {Number} [frequency] frequency in Hz. */ p5.Oscillator.prototype.start = function (time, f) { if (this.started) { var now = p5sound.audiocontext.currentTime; this.stop(now); } if (!this.started) { var freq = f || this.f; var type = this.oscillator.type; // var detune = this.oscillator.frequency.value; this.oscillator = p5sound.audiocontext.createOscillator(); this.oscillator.frequency.exponentialRampToValueAtTime(Math.abs(freq), p5sound.audiocontext.currentTime); this.oscillator.type = type; // this.oscillator.detune.value = detune; this.oscillator.connect(this.output); time = time || 0; this.oscillator.start(time + p5sound.audiocontext.currentTime); this.freqNode = this.oscillator.frequency; // if other oscillators are already connected to this osc's freq for (var i in this._freqMods) { if (typeof this._freqMods[i].connect !== 'undefined') { this._freqMods[i].connect(this.oscillator.frequency); } } this.started = true; } }; /** * Stop an oscillator. Accepts an optional parameter * to determine how long (in seconds from now) until the * oscillator stops. * * @method stop * @param {Number} secondsFromNow Time, in seconds from now. */ p5.Oscillator.prototype.stop = function (time) { if (this.started) { var t = time || 0; var now = p5sound.audiocontext.currentTime; this.oscillator.stop(t + now); this.started = false; } }; /** * Set the amplitude between 0 and 1.0. Or, pass in an object * such as an oscillator to modulate amplitude with an audio signal. * * @method amp * @param {Number|Object} vol between 0 and 1.0 * or a modulating signal/oscillator * @param {Number} [rampTime] create a fade that lasts rampTime * @param {Number} [timeFromNow] schedule this event to happen * seconds from now * @return {AudioParam} gain If no value is provided, * returns the Web Audio API * AudioParam that controls * this oscillator's * gain/amplitude/volume) */ p5.Oscillator.prototype.amp = function (vol, rampTime, tFromNow) { var self = this; if (typeof vol === 'number') { var rampTime = rampTime || 0; var tFromNow = tFromNow || 0; var now = p5sound.audiocontext.currentTime; var currentVol = this.output.gain.value; this.output.gain.cancelScheduledValues(now); this.output.gain.linearRampToValueAtTime(currentVol, now + tFromNow); this.output.gain.linearRampToValueAtTime(vol, now + tFromNow + rampTime); } else if (vol) { console.log(vol); vol.connect(self.output.gain); } else { // return the Gain Node return this.output.gain; } }; // these are now the same thing p5.Oscillator.prototype.fade = p5.Oscillator.prototype.amp; p5.Oscillator.prototype.getAmp = function () { return this.output.gain.value; }; /** * Set frequency of an oscillator to a value. Or, pass in an object * such as an oscillator to modulate the frequency with an audio signal. * * @method freq * @param {Number|Object} Frequency Frequency in Hz * or modulating signal/oscillator * @param {Number} [rampTime] Ramp time (in seconds) * @param {Number} [timeFromNow] Schedule this event to happen * at x seconds from now * @return {AudioParam} Frequency If no value is provided, * returns the Web Audio API * AudioParam that controls * this oscillator's frequency * @example * <div><code> * var osc = new p5.Oscillator(300); * osc.start(); * osc.freq(40, 10); * </code></div> */ p5.Oscillator.prototype.freq = function (val, rampTime, tFromNow) { if (typeof val === 'number' && !isNaN(val)) { this.f = val; var now = p5sound.audiocontext.currentTime; var rampTime = rampTime || 0; var tFromNow = tFromNow || 0; var currentFreq = this.oscillator.frequency.value; this.oscillator.frequency.cancelScheduledValues(now); this.oscillator.frequency.setValueAtTime(currentFreq, now + tFromNow); if (val > 0) { this.oscillator.frequency.exponentialRampToValueAtTime(val, tFromNow + rampTime + now); } else { this.oscillator.frequency.linearRampToValueAtTime(val, tFromNow + rampTime + now); } } else if (val) { if (val.output) { val = val.output; } val.connect(this.oscillator.frequency); // keep track of what is modulating this param // so it can be re-connected if this._freqMods.push(val); } else { // return the Frequency Node return this.oscillator.frequency; } }; p5.Oscillator.prototype.getFreq = function () { return this.oscillator.frequency.value; }; /** * Set type to 'sine', 'triangle', 'sawtooth' or 'square'. * * @method setType * @param {String} type 'sine', 'triangle', 'sawtooth' or 'square'. */ p5.Oscillator.prototype.setType = function (type) { this.oscillator.type = type; }; p5.Oscillator.prototype.getType = function () { return this.oscillator.type; }; /** * Connect to a p5.sound / Web Audio object. * * @method connect * @param {Object} unit A p5.sound or Web Audio object */ p5.Oscillator.prototype.connect = function (unit) { if (!unit) { this.panner.connect(p5sound.input); } else if (unit.hasOwnProperty('input')) { this.panner.connect(unit.input); this.connection = unit.input; } else { this.panner.connect(unit); this.connection = unit; } }; /** * Disconnect all outputs * * @method disconnect */ p5.Oscillator.prototype.disconnect = function (unit) { this.output.disconnect(); this.panner.disconnect(); this.output.connect(this.panner); this.oscMods = []; }; /** * Pan between Left (-1) and Right (1) * * @method pan * @param {Number} panning Number between -1 and 1 * @param {Number} timeFromNow schedule this event to happen * seconds from now */ p5.Oscillator.prototype.pan = function (pval, tFromNow) { this.panPosition = pval; this.panner.pan(pval, tFromNow); }; p5.Oscillator.prototype.getPan = function () { return this.panPosition; }; // get rid of the oscillator p5.Oscillator.prototype.dispose = function () { if (this.oscillator) { var now = p5sound.audiocontext.currentTime; this.stop(now); this.disconnect(); this.oscillator.disconnect(); this.panner = null; this.oscillator = null; } // if it is a Pulse if (this.osc2) { this.osc2.dispose(); } }; /** * Set the phase of an oscillator between 0.0 and 1.0 * * @method phase * @param {Number} phase float between 0.0 and 1.0 */ p5.Oscillator.prototype.phase = function (p) { if (!this.dNode) { // create a delay node this.dNode = p5sound.audiocontext.createDelay(); // put the delay node in between output and panner this.output.disconnect(); this.output.connect(this.dNode); this.dNode.connect(this.panner); } // set delay time based on PWM width var now = p5sound.audiocontext.currentTime; this.dNode.delayTime.linearRampToValueAtTime(p5.prototype.map(p, 0, 1, 0, 1 / this.oscillator.frequency.value), now); }; // ========================== // // SIGNAL MATH FOR MODULATION // // ========================== // // return sigChain(this, scale, thisChain, nextChain, Scale); var sigChain = function (o, mathObj, thisChain, nextChain, type) { var chainSource = o.oscillator; // if this type of math already exists in the chain, replace it for (var i in o.mathOps) { if (o.mathOps[i] instanceof type) { chainSource.disconnect(); o.mathOps[i].dispose(); thisChain = i; // assume nextChain is output gain node unless... if (thisChain < o.mathOps.length - 2) { nextChain = o.mathOps[i + 1]; } } } if (thisChain == o.mathOps.length - 1) { o.mathOps.push(nextChain); } // assume source is the oscillator unless i > 0 if (i > 0) { chainSource = o.mathOps[i - 1]; } chainSource.disconnect(); chainSource.connect(mathObj); mathObj.connect(nextChain); o.mathOps[thisChain] = mathObj; return o; }; /** * Add a value to the p5.Oscillator's output amplitude, * and return the oscillator. Calling this method again * will override the initial add() with a new value. * * @method add * @param {Number} number Constant number to add * @return {p5.Oscillator} Oscillator Returns this oscillator * with scaled output * */ p5.Oscillator.prototype.add = function (num) { var add = new Add(num); var thisChain = this.mathOps.length - 1; var nextChain = this.output; return sigChain(this, add, thisChain, nextChain, Add); }; /** * Multiply the p5.Oscillator's output amplitude * by a fixed value (i.e. turn it up!). Calling this method * again will override the initial mult() with a new value. * * @method mult * @param {Number} number Constant number to multiply * @return {p5.Oscillator} Oscillator Returns this oscillator * with multiplied output */ p5.Oscillator.prototype.mult = function (num) { var mult = new Mult(num); var thisChain = this.mathOps.length - 1; var nextChain = this.output; return sigChain(this, mult, thisChain, nextChain, Mult); }; /** * Scale this oscillator's amplitude values to a given * range, and return the oscillator. Calling this method * again will override the initial scale() with new values. * * @method scale * @param {Number} inMin input range minumum * @param {Number} inMax input range maximum * @param {Number} outMin input range minumum * @param {Number} outMax input range maximum * @return {p5.Oscillator} Oscillator Returns this oscillator * with scaled output */ p5.Oscillator.prototype.scale = function (inMin, inMax, outMin, outMax) { var mapOutMin, mapOutMax; if (arguments.length === 4) { mapOutMin = p5.prototype.map(outMin, inMin, inMax, 0, 1) - 0.5; mapOutMax = p5.prototype.map(outMax, inMin, inMax, 0, 1) - 0.5; } else { mapOutMin = arguments[0]; mapOutMax = arguments[1]; } var scale = new Scale(mapOutMin, mapOutMax); var thisChain = this.mathOps.length - 1; var nextChain = this.output; return sigChain(this, scale, thisChain, nextChain, Scale); }; // ============================== // // SinOsc, TriOsc, SqrOsc, SawOsc // // ============================== // /** * Constructor: <code>new p5.SinOsc()</code>. * This creates a Sine Wave Oscillator and is * equivalent to <code> new p5.Oscillator('sine') * </code> or creating a p5.Oscillator and then calling * its method <code>setType('sine')</code>. * See p5.Oscillator for methods. * * @method p5.SinOsc * @param {[Number]} freq Set the frequency */ p5.SinOsc = function (freq) { p5.Oscillator.call(this, freq, 'sine'); }; p5.SinOsc.prototype = Object.create(p5.Oscillator.prototype); /** * Constructor: <code>new p5.TriOsc()</code>. * This creates a Triangle Wave Oscillator and is * equivalent to <code>new p5.Oscillator('triangle') * </code> or creating a p5.Oscillator and then calling * its method <code>setType('triangle')</code>. * See p5.Oscillator for methods. * * @method p5.TriOsc * @param {[Number]} freq Set the frequency */ p5.TriOsc = function (freq) { p5.Oscillator.call(this, freq, 'triangle'); }; p5.TriOsc.prototype = Object.create(p5.Oscillator.prototype); /** * Constructor: <code>new p5.SawOsc()</code>. * This creates a SawTooth Wave Oscillator and is * equivalent to <code> new p5.Oscillator('sawtooth') * </code> or creating a p5.Oscillator and then calling * its method <code>setType('sawtooth')</code>. * See p5.Oscillator for methods. * * @method p5.SawOsc * @param {[Number]} freq Set the frequency */ p5.SawOsc = function (freq) { p5.Oscillator.call(this, freq, 'sawtooth'); }; p5.SawOsc.prototype = Object.create(p5.Oscillator.prototype); /** * Constructor: <code>new p5.SqrOsc()</code>. * This creates a Square Wave Oscillator and is * equivalent to <code> new p5.Oscillator('square') * </code> or creating a p5.Oscillator and then calling * its method <code>setType('square')</code>. * See p5.Oscillator for methods. * * @method p5.SqrOsc * @param {[Number]} freq Set the frequency */ p5.SqrOsc = function (freq) { p5.Oscillator.call(this, freq, 'square'); }; p5.SqrOsc.prototype = Object.create(p5.Oscillator.prototype); }(master, Tone_signal_Signal, Tone_signal_Add, Tone_signal_Multiply, Tone_signal_Scale); var env; env = function () { 'use strict'; var p5sound = master; var Add = Tone_signal_Add; var Mult = Tone_signal_Multiply; var Scale = Tone_signal_Scale; var Tone = Tone_core_Tone; Tone.setContext(p5sound.audiocontext); // oscillator or buffer source to clear on env complete // to save resources if/when it is retriggered var sourceToClear = null; // set to true if attack is set, then false on release var wasTriggered = false; /** * <p>Envelopes are pre-defined amplitude distribution over time. * The p5.Env accepts up to four time/level pairs, where time * determines how long of a ramp before value reaches level. * Typically, envelopes are used to control the output volume * of an object, a series of fades referred to as Attack, Decay, * Sustain and Release (ADSR). But p5.Env can control any * Web Audio Param, for example it can be passed to an Oscillator * frequency like osc.freq(env) </p> * * @class p5.Env * @constructor * @param {Number} aTime Time (in seconds) before level * reaches attackLevel * @param {Number} aLevel Typically an amplitude between * 0.0 and 1.0 * @param {Number} dTime Time * @param {Number} [dLevel] Amplitude (In a standard ADSR envelope, * decayLevel = sustainLevel) * @param {Number} [sTime] Time (in seconds) * @param {Number} [sLevel] Amplitude 0.0 to 1.0 * @param {Number} [rTime] Time (in seconds) * @param {Number} [rLevel] Amplitude 0.0 to 1.0 * @example * <div><code> * var aT = 0.1; // attack time in seconds * var aL = 0.7; // attack level 0.0 to 1.0 * var dT = 0.3; // decay time in seconds * var dL = 0.1; // decay level 0.0 to 1.0 * var sT = 0.2; // sustain time in seconds * var sL = dL; // sustain level 0.0 to 1.0 * var rT = 0.5; // release time in seconds * // release level defaults to zero * * var env; * var triOsc; * * function setup() { * background(0); * noStroke(); * fill(255); * textAlign(CENTER); * text('click to play', width/2, height/2); * * env = new p5.Env(aT, aL, dT, dL, sT, sL, rT); * triOsc = new p5.Oscillator('triangle'); * triOsc.amp(env); // give the env control of the triOsc's amp * triOsc.start(); * } * * // mouseClick triggers envelope if over canvas * function mouseClicked() { * // is mouse over canvas? * if (mouseX > 0 && mouseX < width && mouseY > 0 && mouseY < height) { * env.play(noise); * } * } * </code></div> */ p5.Env = function (t1, l1, t2, l2, t3, l3, t4, l4) { /** * @property attackTime */ this.aTime = t1; /** * @property attackLevel */ this.aLevel = l1; /** * @property decayTime */ this.dTime = t2 || 0; /** * @property decayLevel */ this.dLevel = l2 || 0; /** * @property sustainTime */ this.sTime = t3 || 0; /** * @property sustainLevel */ this.sLevel = l3 || 0; /** * @property releaseTime */ this.rTime = t4 || 0; /** * @property releaseLevel */ this.rLevel = l4 || 0; this.output = p5sound.audiocontext.createGain(); this.control = new p5.Signal(); this.control.connect(this.output); this.connection = null; // store connection //array of math operation signal chaining this.mathOps = [this.control]; // add to the soundArray so we can dispose of the env later p5sound.soundArray.push(this); }; /** * Reset the envelope with a series of time/value pairs. * * @method set * @param {Number} aTime Time (in seconds) before level * reaches attackLevel * @param {Number} aLevel Typically an amplitude between * 0.0 and 1.0 * @param {Number} dTime Time * @param {Number} [dLevel] Amplitude (In a standard ADSR envelope, * decayLevel = sustainLevel) * @param {Number} [sTime] Time (in seconds) * @param {Number} [sLevel] Amplitude 0.0 to 1.0 * @param {Number} [rTime] Time (in seconds) * @param {Number} [rLevel] Amplitude 0.0 to 1.0 */ p5.Env.prototype.set = function (t1, l1, t2, l2, t3, l3, t4, l4) { this.aTime = t1; this.aLevel = l1; this.dTime = t2 || 0; this.dLevel = l2 || 0; this.sTime = t3 || 0; this.sLevel = l3 || 0; this.rTime = t4 || 0; this.rLevel = l4 || 0; }; /** * Assign a parameter to be controlled by this envelope. * If a p5.Sound object is given, then the p5.Env will control its * output gain. If multiple inputs are provided, the env will * control all of them. * * @method setInput * @param {Object} unit A p5.sound object or * Web Audio Param. */ p5.Env.prototype.setInput = function (unit) { for (var i = 0; i < arguments.length; i++) { this.connect(arguments[i]); } }; p5.Env.prototype.ctrl = function (unit) { this.connect(unit); }; /** * Play tells the envelope to start acting on a given input. * If the input is a p5.sound object (i.e. AudioIn, Oscillator, * SoundFile), then Env will control its output volume. * Envelopes can also be used to control any <a href=" * http://docs.webplatform.org/wiki/apis/webaudio/AudioParam"> * Web Audio Audio Param.</a> * * @method play * @param {Object} unit A p5.sound object or * Web Audio Param. * @param {Number} secondsFromNow time from now (in seconds) */ p5.Env.prototype.play = function (unit, secondsFromNow) { var now = p5sound.audiocontext.currentTime; var tFromNow = secondsFromNow || 0; var t = now + tFromNow; if (unit) { if (this.connection !== unit) { this.connect(unit); } } var currentVal = this.control.getValue(); this.control.cancelScheduledValues(t); this.control.linearRampToValueAtTime(currentVal, t); // attack this.control.linearRampToValueAtTime(this.aLevel, t + this.aTime); // decay to decay level this.control.linearRampToValueAtTime(this.dLevel, t + this.aTime + this.dTime); // hold sustain level this.control.linearRampToValueAtTime(this.sLevel, t + this.aTime + this.dTime + this.sTime); // release this.control.linearRampToValueAtTime(this.rLevel, t + this.aTime + this.dTime + this.sTime + this.rTime); var clearTime = t + this.aTime + this.dTime + this.sTime + this.rTime; }; /** * Trigger the Attack, Decay, and Sustain of the Envelope. * Similar to holding down a key on a piano, but it will * hold the sustain level until you let go. Input can be * any p5.sound object, or a <a href=" * http://docs.webplatform.org/wiki/apis/webaudio/AudioParam"> * Web Audio Param</a>. * * @method triggerAttack * @param {Object} unit p5.sound Object or Web Audio Param * @param {Number} secondsFromNow time from now (in seconds) */ p5.Env.prototype.triggerAttack = function (unit, secondsFromNow) { var now = p5sound.audiocontext.currentTime; var tFromNow = secondsFromNow || 0; var t = now + tFromNow; this.lastAttack = t; wasTriggered = true; // we should set current value, but this is not working on Firefox var currentVal = this.control.getValue(); console.log(currentVal); this.control.cancelScheduledValues(t); this.control.linearRampToValueAtTime(currentVal, t); if (unit) { if (this.connection !== unit) { this.connect(unit); } } this.control.linearRampToValueAtTime(this.aLevel, t + this.aTime); // attack this.control.linearRampToValueAtTime(this.aLevel, t + this.aTime); // decay to sustain level this.control.linearRampToValueAtTime(this.dLevel, t + this.aTime + this.dTime); this.control.linearRampToValueAtTime(this.sLevel, t + this.aTime + this.dTime + this.sTime); }; /** * Trigger the Release of the Envelope. This is similar to releasing * the key on a piano and letting the sound fade according to the * release level and release time. * * @method triggerRelease * @param {Object} unit p5.sound Object or Web Audio Param * @param {Number} secondsFromNow time to trigger the release */ p5.Env.prototype.triggerRelease = function (unit, secondsFromNow) { // only trigger a release if an attack was triggered if (!wasTriggered) { return; } var now = p5sound.audiocontext.currentTime; var tFromNow = secondsFromNow || 0; var t = now + tFromNow; var relTime; if (unit) { if (this.connection !== unit) { this.connect(unit); } } this.control.cancelScheduledValues(t); // ideally would get & set currentValue here, // but this.control._scalar.gain.value not working in firefox // release based on how much time has passed since this.lastAttack if (now - this.lastAttack < this.aTime) { var a = this.aTime - (t - this.lastAttack); this.control.linearRampToValueAtTime(this.aLevel, t + a); this.control.linearRampToValueAtTime(this.dLevel, t + a + this.dTime); this.control.linearRampToValueAtTime(this.sLevel, t + a + this.dTime + this.sTime); this.control.linearRampToValueAtTime(this.rLevel, t + a + this.dTime + this.sTime + this.rTime); relTime = t + this.dTime + this.sTime + this.rTime; } else if (now - this.lastAttack < this.aTime + this.dTime) { var d = this.aTime + this.dTime - (now - this.lastAttack); this.control.linearRampToValueAtTime(this.dLevel, t + d); // this.control.linearRampToValueAtTime(this.sLevel, t + d + this.sTime); this.control.linearRampToValueAtTime(this.sLevel, t + d + 0.01); this.control.linearRampToValueAtTime(this.rLevel, t + d + 0.01 + this.rTime); relTime = t + this.sTime + this.rTime; } else if (now - this.lastAttack < this.aTime + this.dTime + this.sTime) { var s = this.aTime + this.dTime + this.sTime - (now - this.lastAttack); this.control.linearRampToValueAtTime(this.sLevel, t + s); this.control.linearRampToValueAtTime(this.rLevel, t + s + this.rTime); relTime = t + this.rTime; } else { this.control.linearRampToValueAtTime(this.sLevel, t); this.control.linearRampToValueAtTime(this.rLevel, t + this.rTime); relTime = t + this.dTime + this.sTime + this.rTime; } // clear osc / sources var clearTime = t + this.aTime + this.dTime + this.sTime + this.rTime; // * 1000; if (this.connection && this.connection.hasOwnProperty('oscillator')) { sourceToClear = this.connection.oscillator; sourceToClear.stop(clearTime + 0.01); } else if (this.connect && this.connection.hasOwnProperty('source')) { sourceToClear = this.connection.source; sourceToClear.stop(clearTime + 0.01); } wasTriggered = false; }; p5.Env.prototype.connect = function (unit) { this.connection = unit; // assume we're talking about output gain // unless given a different audio param if (unit instanceof p5.Oscillator || unit instanceof p5.SoundFile || unit instanceof p5.AudioIn || unit instanceof p5.Reverb || unit instanceof p5.Noise || unit instanceof p5.Filter || unit instanceof p5.Delay) { unit = unit.output.gain; } if (unit instanceof AudioParam) { //set the initial value unit.setValueAtTime(0, p5sound.audiocontext.currentTime); } if (unit instanceof p5.Signal) { unit.setValue(0); } this.output.connect(unit); }; p5.Env.prototype.disconnect = function (unit) { this.output.disconnect(); }; // Signal Math /** * Add a value to the p5.Oscillator's output amplitude, * and return the oscillator. Calling this method * again will override the initial add() with new values. * * @method add * @param {Number} number Constant number to add * @return {p5.Env} Envelope Returns this envelope * with scaled output */ p5.Env.prototype.add = function (num) { var add = new Add(num); var thisChain = this.mathOps.length; var nextChain = this.output; return p5.prototype._mathChain(this, add, thisChain, nextChain, Add); }; /** * Multiply the p5.Env's output amplitude * by a fixed value. Calling this method * again will override the initial mult() with new values. * * @method mult * @param {Number} number Constant number to multiply * @return {p5.Env} Envelope Returns this envelope * with scaled output */ p5.Env.prototype.mult = function (num) { var mult = new Mult(num); var thisChain = this.mathOps.length; var nextChain = this.output; return p5.prototype._mathChain(this, mult, thisChain, nextChain, Mult); }; /** * Scale this envelope's amplitude values to a given * range, and return the envelope. Calling this method * again will override the initial scale() with new values. * * @method scale * @param {Number} inMin input range minumum * @param {Number} inMax input range maximum * @param {Number} outMin input range minumum * @param {Number} outMax input range maximum * @return {p5.Env} Envelope Returns this envelope * with scaled output */ p5.Env.prototype.scale = function (inMin, inMax, outMin, outMax) { var scale = new Scale(inMin, inMax, outMin, outMax); var thisChain = this.mathOps.length; var nextChain = this.output; return p5.prototype._mathChain(this, scale, thisChain, nextChain, Scale); }; // get rid of the oscillator p5.Env.prototype.dispose = function () { var now = p5sound.audiocontext.currentTime; this.disconnect(); try { this.control.dispose(); this.control = null; } catch (e) { } for (var i = 1; i < this.mathOps.length; i++) { mathOps[i].dispose(); } }; }(master, Tone_signal_Add, Tone_signal_Multiply, Tone_signal_Scale, Tone_core_Tone); var pulse; pulse = function () { 'use strict'; var p5sound = master; /** * Creates a Pulse object, an oscillator that implements * Pulse Width Modulation. * The pulse is created with two oscillators. * Accepts a parameter for frequency, and to set the * width between the pulses. See <a href=" * http://p5js.org/reference/#/p5.Oscillator"> * <code>p5.Oscillator</code> for a full list of methods. * * @class p5.Pulse * @constructor * @param {Number} [freq] Frequency in oscillations per second (Hz) * @param {Number} [w] Width between the pulses (0 to 1.0, * defaults to 0) * @example * <div><code> * var pulse; * function setup() { * background(0); * * // Create and start the pulse wave oscillator * pulse = new p5.Pulse(); * pulse.amp(0.5); * pulse.freq(220); * pulse.start(); * } * * function draw() { * var w = map(mouseX, 0, width, 0, 1); * w = constrain(w, 0, 1); * pulse.width(w) * } * </code></div> */ p5.Pulse = function (freq, w) { p5.Oscillator.call(this, freq, 'sawtooth'); // width of PWM, should be betw 0 to 1.0 this.w = w || 0; // create a second oscillator with inverse frequency this.osc2 = new p5.SawOsc(freq); // create a delay node this.dNode = p5sound.audiocontext.createDelay(); // dc offset this.dcOffset = createDCOffset(); this.dcGain = p5sound.audiocontext.createGain(); this.dcOffset.connect(this.dcGain); this.dcGain.connect(this.output); // set delay time based on PWM width this.f = freq || 440; var mW = this.w / this.oscillator.frequency.value; this.dNode.delayTime.value = mW; this.dcGain.gain.value = 1.7 * (0.5 - this.w); // disconnect osc2 and connect it to delay, which is connected to output this.osc2.disconnect(); this.osc2.panner.disconnect(); this.osc2.amp(-1); // inverted amplitude this.osc2.output.connect(this.dNode); this.dNode.connect(this.output); this.output.gain.value = 1; this.output.connect(this.panner); }; p5.Pulse.prototype = Object.create(p5.Oscillator.prototype); /** * Set the width of a Pulse object (an oscillator that implements * Pulse Width Modulation). * * @method width * @param {Number} [width] Width between the pulses (0 to 1.0, * defaults to 0) */ p5.Pulse.prototype.width = function (w) { if (typeof w === 'number') { if (w <= 1 && w >= 0) { this.w = w; // set delay time based on PWM width // var mW = map(this.w, 0, 1.0, 0, 1/this.f); var mW = this.w / this.oscillator.frequency.value; this.dNode.delayTime.value = mW; } this.dcGain.gain.value = 1.7 * (0.5 - this.w); } else { w.connect(this.dNode.delayTime); var sig = new p5.SignalAdd(-0.5); sig.setInput(w); sig = sig.mult(-1); sig = sig.mult(1.7); sig.connect(this.dcGain.gain); } }; p5.Pulse.prototype.start = function (f, time) { var now = p5sound.audiocontext.currentTime; var t = time || 0; if (!this.started) { var freq = f || this.f; var type = this.oscillator.type; this.oscillator = p5sound.audiocontext.createOscillator(); this.oscillator.frequency.setValueAtTime(freq, now); this.oscillator.type = type; this.oscillator.connect(this.output); this.oscillator.start(t + now); // set up osc2 this.osc2.oscillator = p5sound.audiocontext.createOscillator(); this.osc2.oscillator.frequency.setValueAtTime(freq, t + now); this.osc2.oscillator.type = type; this.osc2.oscillator.connect(this.osc2.output); this.osc2.start(t + now); this.freqNode = [ this.oscillator.frequency, this.osc2.oscillator.frequency ]; // start dcOffset, too this.dcOffset = createDCOffset(); this.dcOffset.connect(this.dcGain); this.dcOffset.start(t + now); // if LFO connections depend on these oscillators if (this.mods !== undefined && this.mods.frequency !== undefined) { this.mods.frequency.connect(this.freqNode[0]); this.mods.frequency.connect(this.freqNode[1]); } this.started = true; this.osc2.started = true; } }; p5.Pulse.prototype.stop = function (time) { if (this.started) { var t = time || 0; var now = p5sound.audiocontext.currentTime; this.oscillator.stop(t + now); this.osc2.oscillator.stop(t + now); this.dcOffset.stop(t + now); this.started = false; this.osc2.started = false; } }; p5.Pulse.prototype.freq = function (val, rampTime, tFromNow) { if (typeof val === 'number') { this.f = val; var now = p5sound.audiocontext.currentTime; var rampTime = rampTime || 0; var tFromNow = tFromNow || 0; var currentFreq = this.oscillator.frequency.value; this.oscillator.frequency.cancelScheduledValues(now); this.oscillator.frequency.setValueAtTime(currentFreq, now + tFromNow); this.oscillator.frequency.exponentialRampToValueAtTime(val, tFromNow + rampTime + now); this.osc2.oscillator.frequency.cancelScheduledValues(now); this.osc2.oscillator.frequency.setValueAtTime(currentFreq, now + tFromNow); this.osc2.oscillator.frequency.exponentialRampToValueAtTime(val, tFromNow + rampTime + now); if (this.freqMod) { this.freqMod.output.disconnect(); this.freqMod = null; } } else if (val.output) { val.output.disconnect(); val.output.connect(this.oscillator.frequency); val.output.connect(this.osc2.oscillator.frequency); this.freqMod = val; } }; // inspiration: http://webaudiodemos.appspot.com/oscilloscope/ function createDCOffset() { var ac = p5sound.audiocontext; var buffer = ac.createBuffer(1, 2048, ac.sampleRate); var data = buffer.getChannelData(0); for (var i = 0; i < 2048; i++) data[i] = 1; var bufferSource = ac.createBufferSource(); bufferSource.buffer = buffer; bufferSource.loop = true; return bufferSource; } }(master, oscillator); var noise; noise = function () { 'use strict'; var p5sound = master; /** * Noise is a type of oscillator that generates a buffer with random values. * * @class p5.Noise * @constructor * @param {String} type Type of noise can be 'white' (default), * 'brown' or 'pink'. * @return {Object} Noise Object */ p5.Noise = function (type) { p5.Oscillator.call(this); delete this.f; delete this.freq; delete this.oscillator; this.buffer = _whiteNoise; }; p5.Noise.prototype = Object.create(p5.Oscillator.prototype); // generate noise buffers var _whiteNoise = function () { var bufferSize = 2 * p5sound.audiocontext.sampleRate; var whiteBuffer = p5sound.audiocontext.createBuffer(1, bufferSize, p5sound.audiocontext.sampleRate); var noiseData = whiteBuffer.getChannelData(0); for (var i = 0; i < bufferSize; i++) { noiseData[i] = Math.random() * 2 - 1; } whiteBuffer.type = 'white'; return whiteBuffer; }(); var _pinkNoise = function () { var bufferSize = 2 * p5sound.audiocontext.sampleRate; var pinkBuffer = p5sound.audiocontext.createBuffer(1, bufferSize, p5sound.audiocontext.sampleRate); var noiseData = pinkBuffer.getChannelData(0); var b0, b1, b2, b3, b4, b5, b6; b0 = b1 = b2 = b3 = b4 = b5 = b6 = 0; for (var i = 0; i < bufferSize; i++) { var white = Math.random() * 2 - 1; b0 = 0.99886 * b0 + white * 0.0555179; b1 = 0.99332 * b1 + white * 0.0750759; b2 = 0.969 * b2 + white * 0.153852; b3 = 0.8665 * b3 + white * 0.3104856; b4 = 0.55 * b4 + white * 0.5329522; b5 = -0.7616 * b5 - white * 0.016898; noiseData[i] = b0 + b1 + b2 + b3 + b4 + b5 + b6 + white * 0.5362; noiseData[i] *= 0.11; // (roughly) compensate for gain b6 = white * 0.115926; } pinkBuffer.type = 'pink'; return pinkBuffer; }(); var _brownNoise = function () { var bufferSize = 2 * p5sound.audiocontext.sampleRate; var brownBuffer = p5sound.audiocontext.createBuffer(1, bufferSize, p5sound.audiocontext.sampleRate); var noiseData = brownBuffer.getChannelData(0); var lastOut = 0; for (var i = 0; i < bufferSize; i++) { var white = Math.random() * 2 - 1; noiseData[i] = (lastOut + 0.02 * white) / 1.02; lastOut = noiseData[i]; noiseData[i] *= 3.5; } brownBuffer.type = 'brown'; return brownBuffer; }(); /** * Set type of noise to 'white', 'pink' or 'brown'. * White is the default. * * @method setType * @param {String} [type] 'white', 'pink' or 'brown' */ p5.Noise.prototype.setType = function (type) { switch (type) { case 'white': this.buffer = _whiteNoise; break; case 'pink': this.buffer = _pinkNoise; break; case 'brown': this.buffer = _brownNoise; break; default: this.buffer = _whiteNoise; } if (this.started) { var now = p5sound.audiocontext.currentTime; this.stop(now); this.start(now + 0.01); } }; p5.Noise.prototype.getType = function () { return this.buffer.type; }; /** * Start the noise * * @method start */ p5.Noise.prototype.start = function () { if (this.started) { this.stop(); } this.noise = p5sound.audiocontext.createBufferSource(); this.noise.buffer = this.buffer; this.noise.loop = true; this.noise.connect(this.output); var now = p5sound.audiocontext.currentTime; this.noise.start(now); this.started = true; }; /** * Stop the noise. * * @method stop */ p5.Noise.prototype.stop = function () { var now = p5sound.audiocontext.currentTime; if (this.noise) { this.noise.stop(now); this.started = false; } }; /** * Pan the noise. * * @method pan * @param {Number} panning Number between -1 (left) * and 1 (right) * @param {Number} timeFromNow schedule this event to happen * seconds from now */ /** * Set the amplitude of the noise between 0 and 1.0. Or, * modulate amplitude with an audio signal such as an oscillator. * * @param {Number|Object} volume amplitude between 0 and 1.0 * or modulating signal/oscillator * @param {Number} [rampTime] create a fade that lasts rampTime * @param {Number} [timeFromNow] schedule this event to happen * seconds from now */ /** * Send output to a p5.sound or web audio object * * @method connect * @param {Object} unit */ /** * Disconnect all output. * * @method disconnect */ p5.Noise.prototype.dispose = function () { var now = p5sound.audiocontext.currentTime; if (this.noise) { this.noise.disconnect(); this.stop(now); } if (this.output) { this.output.disconnect(); } if (this.panner) { this.panner.disconnect(); } this.output = null; this.panner = null; this.buffer = null; this.noise = null; }; }(master); var audioin; audioin = function () { 'use strict'; var p5sound = master; /** * <p>Get audio from an input, i.e. your computer's microphone.</p> * * <p>Turn the mic on/off with the start() and stop() methods. When the mic * is on, its volume can be measured with getLevel or by connecting an * FFT object.</p> * * <p>If you want to hear the AudioIn, use the .connect() method. * AudioIn does not connect to p5.sound output by default to prevent * feedback.</p> * * <p><em>Note: This uses the <a href="http://caniuse.com/stream">getUserMedia/ * Stream</a> API, which is not supported by certain browsers.</em></p> * * @class p5.AudioIn * @constructor * @return {Object} AudioIn * @example * <div><code> * var mic; * function setup(){ * mic = new p5.AudioIn() * mic.start(); * } * function draw(){ * background(0); * micLevel = mic.getLevel(); * ellipse(width/2, constrain(height-micLevel*height*5, 0, height), 10, 10); * } * </code></div> */ p5.AudioIn = function () { // set up audio input this.input = p5sound.audiocontext.createGain(); this.output = p5sound.audiocontext.createGain(); this.stream = null; this.mediaStream = null; this.currentSource = 0; /** * Client must allow browser to access their microphone / audioin source. * Default: false. Will become true when the client enables acces. * * @property {Boolean} enabled */ this.enabled = false; // create an amplitude, connect to it by default but not to master out this.amplitude = new p5.Amplitude(); this.output.connect(this.amplitude.input); // Some browsers let developer determine their input sources if (typeof window.MediaStreamTrack === 'undefined') { window.alert('This browser does not support MediaStreamTrack'); } else if (typeof window.MediaStreamTrack.getSources === 'function') { // Chrome supports getSources to list inputs. Dev picks default window.MediaStreamTrack.getSources(this._gotSources); } else { } // add to soundArray so we can dispose on close p5sound.soundArray.push(this); }; /** * Start processing audio input. This enables the use of other * AudioIn methods like getLevel(). Note that by default, AudioIn * is not connected to p5.sound's output. So you won't hear * anything unless you use the connect() method.<br/> * * @method start */ p5.AudioIn.prototype.start = function () { var self = this; // if _gotSources() i.e. developers determine which source to use if (p5sound.inputSources[self.currentSource]) { // set the audio source var audioSource = p5sound.inputSources[self.currentSource].id; var constraints = { audio: { optional: [{ sourceId: audioSource }] } }; navigator.getUserMedia(constraints, this._onStream = function (stream) { self.stream = stream; self.enabled = true; // Wrap a MediaStreamSourceNode around the live input self.mediaStream = p5sound.audiocontext.createMediaStreamSource(stream); self.mediaStream.connect(self.output); // only send to the Amplitude reader, so we can see it but not hear it. self.amplitude.setInput(self.output); }, this._onStreamError = function (stream) { console.error(stream); }); } else { // if Firefox where users select their source via browser // if (typeof MediaStreamTrack.getSources === 'undefined') { // Only get the audio stream. window.navigator.getUserMedia({ 'audio': true }, this._onStream = function (stream) { self.stream = stream; self.enabled = true; // Wrap a MediaStreamSourceNode around the live input self.mediaStream = p5sound.audiocontext.createMediaStreamSource(stream); self.mediaStream.connect(self.output); // only send to the Amplitude reader, so we can see it but not hear it. self.amplitude.setInput(self.output); }, this._onStreamError = function (stream) { console.error(stream); }); } }; /** * Turn the AudioIn off. If the AudioIn is stopped, it cannot getLevel().<br/> * * @method stop */ p5.AudioIn.prototype.stop = function () { if (this.stream) { this.stream.stop(); } }; /** * Connect to an audio unit. If no parameter is provided, will * connect to the master output (i.e. your speakers).<br/> * * @method connect * @param {Object} [unit] An object that accepts audio input, * such as an FFT */ p5.AudioIn.prototype.connect = function (unit) { if (unit) { if (unit.hasOwnProperty('input')) { this.output.connect(unit.input); } else if (unit.hasOwnProperty('analyser')) { this.output.connect(unit.analyser); } else { this.output.connect(unit); } } else { this.output.connect(p5sound.input); } }; /** * Disconnect the AudioIn from all audio units. For example, if * connect() had been called, disconnect() will stop sending * signal to your speakers.<br/> * * @method disconnect */ p5.AudioIn.prototype.disconnect = function (unit) { this.output.disconnect(unit); // stay connected to amplitude even if not outputting to p5 this.output.connect(this.amplitude.input); }; /** * Read the Amplitude (volume level) of an AudioIn. The AudioIn * class contains its own instance of the Amplitude class to help * make it easy to get a microphone's volume level. Accepts an * optional smoothing value (0.0 < 1.0). <em>NOTE: AudioIn must * .start() before using .getLevel().</em><br/> * * @method getLevel * @param {Number} [smoothing] Smoothing is 0.0 by default. * Smooths values based on previous values. * @return {Number} Volume level (between 0.0 and 1.0) */ p5.AudioIn.prototype.getLevel = function (smoothing) { if (smoothing) { this.amplitude.smoothing = smoothing; } return this.amplitude.getLevel(); }; /** * Add input sources to the list of available sources. * * @private */ p5.AudioIn.prototype._gotSources = function (sourceInfos) { for (var i = 0; i < sourceInfos.length; i++) { var sourceInfo = sourceInfos[i]; if (sourceInfo.kind === 'audio') { // add the inputs to inputSources //p5sound.inputSources.push(sourceInfo); return sourceInfo; } } }; /** * Set amplitude (volume) of a mic input between 0 and 1.0. <br/> * * @method amp * @param {Number} vol between 0 and 1.0 * @param {Number} [time] ramp time (optional) */ p5.AudioIn.prototype.amp = function (vol, t) { if (t) { var rampTime = t || 0; var currentVol = this.output.gain.value; this.output.gain.cancelScheduledValues(p5sound.audiocontext.currentTime); this.output.gain.setValueAtTime(currentVol, p5sound.audiocontext.currentTime); this.output.gain.linearRampToValueAtTime(vol, rampTime + p5sound.audiocontext.currentTime); } else { this.output.gain.cancelScheduledValues(p5sound.audiocontext.currentTime); this.output.gain.setValueAtTime(vol, p5sound.audiocontext.currentTime); } }; p5.AudioIn.prototype.listSources = function () { console.log('listSources is deprecated - please use AudioIn.getSources'); console.log('input sources: '); if (p5sound.inputSources.length > 0) { return p5sound.inputSources; } else { return 'This browser does not support MediaStreamTrack.getSources()'; } }; /** * Chrome only. Returns a list of available input sources * and allows the user to set the media source. Firefox allows * the user to choose from input sources in the permissions dialogue * instead of enumerating available sources and selecting one. * Note: in order to have descriptive media names your page must be * served over a secure (HTTPS) connection and the page should * request user media before enumerating devices. Otherwise device * ID will be a long device ID number and does not specify device * type. For example see * https://simpl.info/getusermedia/sources/index.html vs. * http://simpl.info/getusermedia/sources/index.html * * @method getSources * @param {Function} callback a callback to handle the sources * when they have been enumerated * @example * <div><code> * var audiograb; * * function setup(){ * //new audioIn * audioGrab = new p5.AudioIn(); * * audioGrab.getSources(function(sourceList) { * //print out the array of available sources * console.log(sourceList); * //set the source to the first item in the inputSources array * audioGrab.setSource(0); * }); * } * function draw(){ * } * </code></div> */ p5.AudioIn.prototype.getSources = function (callback) { if (typeof window.MediaStreamTrack.getSources === 'function') { window.MediaStreamTrack.getSources(function (data) { for (var i = 0, max = data.length; i < max; i++) { var sourceInfo = data[i]; if (sourceInfo.kind === 'audio') { // add the inputs to inputSources p5sound.inputSources.push(sourceInfo); } } callback(p5sound.inputSources); }); } else { console.log('This browser does not support MediaStreamTrack.getSources()'); } }; /** * Set the input source. Accepts a number representing a * position in the array returned by listSources(). * This is only available in browsers that support * MediaStreamTrack.getSources(). Instead, some browsers * give users the option to set their own media source.<br/> * * @method setSource * @param {number} num position of input source in the array */ p5.AudioIn.prototype.setSource = function (num) { // TO DO - set input by string or # (array position) var self = this; if (p5sound.inputSources.length > 0 && num < p5sound.inputSources.length) { // set the current source self.currentSource = num; console.log('set source to ' + p5sound.inputSources[self.currentSource].id); } else { console.log('unable to set input source'); } }; // private method p5.AudioIn.prototype.dispose = function () { this.stop(); if (this.output) { this.output.disconnect(); } if (this.amplitude) { this.amplitude.disconnect(); } this.amplitude = null; this.output = null; }; }(master); var filter; filter = function () { 'use strict'; var p5sound = master; /** * A p5.Filter uses a Web Audio Biquad Filter to filter * the frequency response of an input source. Inheriting * classes include:<br/> * * <code>p5.LowPass</code> - allows frequencies below * the cutoff frequency to pass through, and attenuates * frequencies above the cutoff.<br/> * * <code>p5.HighPass</code> - the opposite of a lowpass * filter. <br/> * * <code>p5.BandPass</code> - allows a range of * frequencies to pass through and attenuates the frequencies * below and above this frequency range.<br/> * * The <code>.res()</code> method controls either width of the * bandpass, or resonance of the low/highpass cutoff frequency. * * @class p5.Filter * @constructor * @param {[String]} type 'lowpass' (default), 'highpass', 'bandpass' * @return {Object} p5.Filter * @example * <div><code> * var fft, noise, filter; * * function setup() { * fill(255, 40, 255); * * filter = new p5.BandPass(); * * noise = new p5.Noise(); * // disconnect unfiltered noise, * // and connect to filter * noise.disconnect(); * noise.connect(filter); * noise.start(); * * fft = new p5.FFT(); * } * * function draw() { * background(30); * * // set the BandPass frequency based on mouseX * var freq = map(mouseX, 0, width, 20, 10000); * filter.freq(freq); * // give the filter a narrow band (lower res = wider bandpass) * filter.res(50); * * // draw filtered spectrum * var spectrum = fft.analyze(); * noStroke(); * for (var i = 0; i < spectrum.length; i++) { * var x = map(i, 0, spectrum.length, 0, width); * var h = -height + map(spectrum[i], 0, 255, height, 0); * rect(x, height, width/spectrum.length, h); * } * * isMouseOverCanvas(); * } * * function isMouseOverCanvas() { * var mX = mouseX, mY = mouseY; * if (mX > 0 && mX < width && mY < height && mY > 0) { * noise.amp(0.5, 0.2); * } else { * noise.amp(0, 0.2); * } * } * </code></div> */ p5.Filter = function (type) { this.ac = p5sound.audiocontext; this.input = this.ac.createGain(); this.output = this.ac.createGain(); /** * The p5.Filter is built with a * <a href="http://www.w3.org/TR/webaudio/#BiquadFilterNode"> * Web Audio BiquadFilter Node</a>. * * @property biquadFilter * @type {Object} Web Audio Delay Node */ this.biquad = this.ac.createBiquadFilter(); this.input.connect(this.biquad); this.biquad.connect(this.output); this.connect(); if (type) { this.setType(type); } }; /** * Filter an audio signal according to a set * of filter parameters. * * @method process * @param {Object} Signal An object that outputs audio * @param {[Number]} freq Frequency in Hz, from 10 to 22050 * @param {[Number]} res Resonance/Width of the filter frequency * from 0.001 to 1000 */ p5.Filter.prototype.process = function (src, freq, res) { src.connect(this.input); this.set(freq, res); }; /** * Set the frequency and the resonance of the filter. * * @method set * @param {Number} freq Frequency in Hz, from 10 to 22050 * @param {Number} res Resonance (Q) from 0.001 to 1000 * @param {Number} [timeFromNow] schedule this event to happen * seconds from now */ p5.Filter.prototype.set = function (freq, res, time) { if (freq) { this.freq(freq, time); } if (res) { this.res(res, time); } }; /** * Set the filter frequency, in Hz, from 10 to 22050 (the range of * human hearing, although in reality most people hear in a narrower * range). * * @method freq * @param {Number} freq Filter Frequency * @param {Number} [timeFromNow] schedule this event to happen * seconds from now * @return {Number} value Returns the current frequency value */ p5.Filter.prototype.freq = function (freq, time) { var self = this; var t = time || 0; if (freq <= 0) { freq = 1; } if (typeof freq === 'number') { self.biquad.frequency.value = freq; self.biquad.frequency.cancelScheduledValues(this.ac.currentTime + 0.01 + t); self.biquad.frequency.exponentialRampToValueAtTime(freq, this.ac.currentTime + 0.02 + t); } else if (freq) { freq.connect(this.biquad.frequency); } return self.biquad.frequency.value; }; /** * Controls either width of a bandpass frequency, * or the resonance of a low/highpass cutoff frequency. * * @method res * @param {Number} res Resonance/Width of filter freq * from 0.001 to 1000 * @param {Number} [timeFromNow] schedule this event to happen * seconds from now * @return {Number} value Returns the current res value */ p5.Filter.prototype.res = function (res, time) { var self = this; var t = time || 0; if (typeof res == 'number') { self.biquad.Q.value = res; self.biquad.Q.cancelScheduledValues(self.ac.currentTime + 0.01 + t); self.biquad.Q.linearRampToValueAtTime(res, self.ac.currentTime + 0.02 + t); } else if (res) { freq.connect(this.biquad.Q); } return self.biquad.Q.value; }; /** * Set the type of a p5.Filter. Possible types include: * "lowpass" (default), "highpass", "bandpass", * "lowshelf", "highshelf", "peaking", "notch", * "allpass". * * @method setType * @param {String} */ p5.Filter.prototype.setType = function (t) { this.biquad.type = t; }; /** * Set the output level of the filter. * * @method amp * @param {Number} volume amplitude between 0 and 1.0 * @param {Number} [rampTime] create a fade that lasts rampTime * @param {Number} [timeFromNow] schedule this event to happen * seconds from now */ p5.Filter.prototype.amp = function (vol, rampTime, tFromNow) { var rampTime = rampTime || 0; var tFromNow = tFromNow || 0; var now = p5sound.audiocontext.currentTime; var currentVol = this.output.gain.value; this.output.gain.cancelScheduledValues(now); this.output.gain.linearRampToValueAtTime(currentVol, now + tFromNow + 0.001); this.output.gain.linearRampToValueAtTime(vol, now + tFromNow + rampTime + 0.001); }; /** * Send output to a p5.sound or web audio object * * @method connect * @param {Object} unit */ p5.Filter.prototype.connect = function (unit) { var u = unit || p5.soundOut.input; this.output.connect(u); }; /** * Disconnect all output. * * @method disconnect */ p5.Filter.prototype.disconnect = function () { this.output.disconnect(); }; /** * Constructor: <code>new p5.LowPass()</code> Filter. * This is the same as creating a p5.Filter and then calling * its method <code>setType('lowpass')</code>. * See p5.Filter for methods. * * @method p5.LowPass */ p5.LowPass = function () { p5.Filter.call(this, 'lowpass'); }; p5.LowPass.prototype = Object.create(p5.Filter.prototype); /** * Constructor: <code>new p5.HighPass()</code> Filter. * This is the same as creating a p5.Filter and then calling * its method <code>setType('highpass')</code>. * See p5.Filter for methods. * * @method p5.HighPass */ p5.HighPass = function () { p5.Filter.call(this, 'highpass'); }; p5.HighPass.prototype = Object.create(p5.Filter.prototype); /** * Constructor: <code>new p5.BandPass()</code> Filter. * This is the same as creating a p5.Filter and then calling * its method <code>setType('bandpass')</code>. * See p5.Filter for methods. * * @method p5.BandPass */ p5.BandPass = function () { p5.Filter.call(this, 'bandpass'); }; p5.BandPass.prototype = Object.create(p5.Filter.prototype); }(master); var delay; delay = function () { 'use strict'; var p5sound = master; var Filter = filter; /** * Delay is an echo effect. It processes an existing sound source, * and outputs a delayed version of that sound. The p5.Delay can * produce different effects depending on the delayTime, feedback, * filter, and type. In the example below, a feedback of 0.5 will * produce a looping delay that decreases in volume by * 50% each repeat. A filter will cut out the high frequencies so * that the delay does not sound as piercing as the original source. * * @class p5.Delay * @constructor * @return {Object} Returns a p5.Delay object * @example * <div><code> * var noise, env, delay; * * function setup() { * background(0); * noStroke(); * fill(255); * textAlign(CENTER); * text('click to play', width/2, height/2); * * noise = new p5.Noise('brown'); * noise.amp(0); * noise.start(); * * delay = new p5.Delay(); * * // delay.process() accepts 4 parameters: * // source, delayTime, feedback, filter frequency * // play with these numbers!! * delay.process(noise, .12, .7, 2300); * * // play the noise with an envelope, * // a series of fades ( time / value pairs ) * env = new p5.Env(.01, 0.2, .2, .1); * } * * // mouseClick triggers envelope * function mouseClicked() { * // is mouse over canvas? * if (mouseX > 0 && mouseX < width && mouseY > 0 && mouseY < height) { * env.play(noise); * } * } * </code></div> */ p5.Delay = function () { this.ac = p5sound.audiocontext; this.input = this.ac.createGain(); this.output = this.ac.createGain(); this._split = this.ac.createChannelSplitter(2); this._merge = this.ac.createChannelMerger(2); this._leftGain = this.ac.createGain(); this._rightGain = this.ac.createGain(); /** * The p5.Delay is built with two * <a href="http://www.w3.org/TR/webaudio/#DelayNode"> * Web Audio Delay Nodes</a>, one for each stereo channel. * * @property leftDelay * @type {Object} Web Audio Delay Node */ this.leftDelay = this.ac.createDelay(); /** * The p5.Delay is built with two * <a href="http://www.w3.org/TR/webaudio/#DelayNode"> * Web Audio Delay Nodes</a>, one for each stereo channel. * * @property rightDelay * @type {Object} Web Audio Delay Node */ this.rightDelay = this.ac.createDelay(); this._leftFilter = new p5.Filter(); this._rightFilter = new p5.Filter(); this._leftFilter.disconnect(); this._rightFilter.disconnect(); /** * Internal filter. Set to lowPass by default, but can be accessed directly. * See p5.Filter for methods. Or use the p5.Delay.filter() method to change * frequency and q. * * @property lowPass * @type {p5.Filter} */ this.lowPass = this._leftFilter; this._leftFilter.biquad.frequency.setValueAtTime(1200, this.ac.currentTime); this._rightFilter.biquad.frequency.setValueAtTime(1200, this.ac.currentTime); this._leftFilter.biquad.Q.setValueAtTime(0.3, this.ac.currentTime); this._rightFilter.biquad.Q.setValueAtTime(0.3, this.ac.currentTime); // graph routing this.input.connect(this._split); this.leftDelay.connect(this._leftGain); this.rightDelay.connect(this._rightGain); this._leftGain.connect(this._leftFilter.input); this._rightGain.connect(this._rightFilter.input); this._merge.connect(this.output); this.output.connect(p5.soundOut.input); this._leftFilter.biquad.gain.setValueAtTime(1, this.ac.currentTime); this._rightFilter.biquad.gain.setValueAtTime(1, this.ac.currentTime); // default routing this.setType(0); this._maxDelay = this.leftDelay.delayTime.maxValue; }; /** * Add delay to an audio signal according to a set * of delay parameters. * * @method process * @param {Object} Signal An object that outputs audio * @param {Number} [delayTime] Time (in seconds) of the delay/echo. * Some browsers limit delayTime to * 1 second. * @param {Number} [feedback] sends the delay back through itself * in a loop that decreases in volume * each time. * @param {Number} [lowPass] Cutoff frequency. Only frequencies * below the lowPass will be part of the * delay. */ p5.Delay.prototype.process = function (src, _delayTime, _feedback, _filter) { var feedback = _feedback || 0; var delayTime = _delayTime || 0; if (feedback >= 1) { throw new Error('Feedback value will force a positive feedback loop.'); } if (delayTime >= this._maxDelay) { throw new Error('Delay Time exceeds maximum delay time of ' + this._maxDelay + ' second.'); } src.connect(this.input); this.leftDelay.delayTime.setValueAtTime(delayTime, this.ac.currentTime); this.rightDelay.delayTime.setValueAtTime(delayTime, this.ac.currentTime); this._leftGain.gain.setValueAtTime(feedback, this.ac.currentTime); this._rightGain.gain.setValueAtTime(feedback, this.ac.currentTime); if (_filter) { this._leftFilter.freq(_filter); this._rightFilter.freq(_filter); } }; /** * Set the delay (echo) time, in seconds. Usually this value will be * a floating point number between 0.0 and 1.0. * * @method delayTime * @param {Number} delayTime Time (in seconds) of the delay */ p5.Delay.prototype.delayTime = function (t) { // if t is an audio node... if (typeof t !== 'number') { t.connect(this.leftDelay.delayTime); t.connect(this.rightDelay.delayTime); } else { this.leftDelay.delayTime.cancelScheduledValues(this.ac.currentTime); this.rightDelay.delayTime.cancelScheduledValues(this.ac.currentTime); this.leftDelay.delayTime.linearRampToValueAtTime(t, this.ac.currentTime); this.rightDelay.delayTime.linearRampToValueAtTime(t, this.ac.currentTime); } }; /** * Feedback occurs when Delay sends its signal back through its input * in a loop. The feedback amount determines how much signal to send each * time through the loop. A feedback greater than 1.0 is not desirable because * it will increase the overall output each time through the loop, * creating an infinite feedback loop. * * @method feedback * @param {Number|Object} feedback 0.0 to 1.0, or an object such as an * Oscillator that can be used to * modulate this param */ p5.Delay.prototype.feedback = function (f) { // if f is an audio node... if (typeof f !== 'number') { f.connect(this._leftGain.gain); f.connect(this._rightGain.gain); } else if (f >= 1) { throw new Error('Feedback value will force a positive feedback loop.'); } else { this._leftGain.gain.exponentialRampToValueAtTime(f, this.ac.currentTime); this._rightGain.gain.exponentialRampToValueAtTime(f, this.ac.currentTime); } }; /** * Set a lowpass filter frequency for the delay. A lowpass filter * will cut off any frequencies higher than the filter frequency. * * @method filter * @param {Number|Object} cutoffFreq A lowpass filter will cut off any * frequencies higher than the filter frequency. * @param {Number|Object} res Resonance of the filter frequency * cutoff, or an object (i.e. a p5.Oscillator) * that can be used to modulate this parameter. * High numbers (i.e. 15) will produce a resonance, * low numbers (i.e. .2) will produce a slope. */ p5.Delay.prototype.filter = function (freq, q) { this._leftFilter.set(freq, q); this._rightFilter.set(freq, q); }; /** * Choose a preset type of delay. 'pingPong' bounces the signal * from the left to the right channel to produce a stereo effect. * Any other parameter will revert to the default delay setting. * * @method setType * @param {String|Number} type 'pingPong' (1) or 'default' (0) */ p5.Delay.prototype.setType = function (t) { if (t === 1) { t = 'pingPong'; } this._split.disconnect(); this._leftFilter.disconnect(); this._rightFilter.disconnect(); this._split.connect(this.leftDelay, 0); this._split.connect(this.rightDelay, 1); switch (t) { case 'pingPong': this._rightFilter.setType(this._leftFilter.biquad.type); this._leftFilter.output.connect(this._merge, 0, 0); this._rightFilter.output.connect(this._merge, 0, 1); this._leftFilter.output.connect(this.rightDelay); this._rightFilter.output.connect(this.leftDelay); break; default: this._leftFilter.output.connect(this._merge, 0, 0); this._leftFilter.output.connect(this._merge, 0, 1); this._leftFilter.output.connect(this.leftDelay); this._leftFilter.output.connect(this.rightDelay); } }; /** * Set the output level of the delay effect. * * @method amp * @param {Number} volume amplitude between 0 and 1.0 * @param {Number} [rampTime] create a fade that lasts rampTime * @param {Number} [timeFromNow] schedule this event to happen * seconds from now */ p5.Delay.prototype.amp = function (vol, rampTime, tFromNow) { var rampTime = rampTime || 0; var tFromNow = tFromNow || 0; var now = p5sound.audiocontext.currentTime; var currentVol = this.output.gain.value; this.output.gain.cancelScheduledValues(now); this.output.gain.linearRampToValueAtTime(currentVol, now + tFromNow + 0.001); this.output.gain.linearRampToValueAtTime(vol, now + tFromNow + rampTime + 0.001); }; /** * Send output to a p5.sound or web audio object * * @method connect * @param {Object} unit */ p5.Delay.prototype.connect = function (unit) { var u = unit || p5.soundOut.input; this.output.connect(u); }; /** * Disconnect all output. * * @method disconnect */ p5.Delay.prototype.disconnect = function () { this.output.disconnect(); }; }(master, filter); var reverb; reverb = function () { 'use strict'; var p5sound = master; /** * Reverb adds depth to a sound through a large number of decaying * echoes. It creates the perception that sound is occurring in a * physical space. The p5.Reverb has paramters for Time (how long does the * reverb last) and decayRate (how much the sound decays with each echo) * that can be set with the .set() or .process() methods. The p5.Convolver * extends p5.Reverb allowing you to recreate the sound of actual physical * spaces through convolution. * * @class p5.Reverb * @constructor * @example * <div><code> * var soundFile, reverb; * function preload() { * soundFile = loadSound('assets/Damscray_DancingTiger.mp3'); * } * * function setup() { * reverb = new p5.Reverb(); * soundFile.disconnect(); // so we'll only hear reverb... * * // connect soundFile to reverb, process w/ * // 3 second reverbTime, decayRate of 2% * reverb.process(soundFile, 3, 2); * soundFile.play(); * } * </code></div> */ p5.Reverb = function () { this.ac = p5sound.audiocontext; this.convolverNode = this.ac.createConvolver(); this.input = this.ac.createGain(); this.output = this.ac.createGain(); // otherwise, Safari distorts this.input.gain.value = 0.5; this.input.connect(this.convolverNode); this.convolverNode.connect(this.output); // default params this._seconds = 3; this._decay = 2; this._reverse = false; this._buildImpulse(); this.connect(); p5sound.soundArray.push(this); }; /** * Connect a source to the reverb, and assign reverb parameters. * * @method process * @param {Object} src p5.sound / Web Audio object with a sound * output. * @param {Number} [seconds] Duration of the reverb, in seconds. * Min: 0, Max: 10. Defaults to 3. * @param {Number} [decayRate] Percentage of decay with each echo. * Min: 0, Max: 100. Defaults to 2. * @param {Boolean} [reverse] Play the reverb backwards or forwards. */ p5.Reverb.prototype.process = function (src, seconds, decayRate, reverse) { src.connect(this.input); var rebuild = false; if (seconds) { this._seconds = seconds; rebuild = true; } if (decayRate) { this._decay = decayRate; } if (reverse) { this._reverse = reverse; } if (rebuild) { this._buildImpulse(); } }; /** * Set the reverb settings. Similar to .process(), but without * assigning a new input. * * @method set * @param {Number} [seconds] Duration of the reverb, in seconds. * Min: 0, Max: 10. Defaults to 3. * @param {Number} [decayRate] Percentage of decay with each echo. * Min: 0, Max: 100. Defaults to 2. * @param {Boolean} [reverse] Play the reverb backwards or forwards. */ p5.Reverb.prototype.set = function (seconds, decayRate, reverse) { var rebuild = false; if (seconds) { this._seconds = seconds; rebuild = true; } if (decayRate) { this._decay = decayRate; } if (reverse) { this._reverse = reverse; } if (rebuild) { this._buildImpulse(); } }; /** * Set the output level of the delay effect. * * @method amp * @param {Number} volume amplitude between 0 and 1.0 * @param {Number} [rampTime] create a fade that lasts rampTime * @param {Number} [timeFromNow] schedule this event to happen * seconds from now */ p5.Reverb.prototype.amp = function (vol, rampTime, tFromNow) { var rampTime = rampTime || 0; var tFromNow = tFromNow || 0; var now = p5sound.audiocontext.currentTime; var currentVol = this.output.gain.value; this.output.gain.cancelScheduledValues(now); this.output.gain.linearRampToValueAtTime(currentVol, now + tFromNow + 0.001); this.output.gain.linearRampToValueAtTime(vol, now + tFromNow + rampTime + 0.001); }; /** * Send output to a p5.sound or web audio object * * @method connect * @param {Object} unit */ p5.Reverb.prototype.connect = function (unit) { var u = unit || p5.soundOut.input; this.output.connect(u.input ? u.input : u); }; /** * Disconnect all output. * * @method disconnect */ p5.Reverb.prototype.disconnect = function () { this.output.disconnect(); }; /** * Inspired by Simple Reverb by Jordan Santell * https://github.com/web-audio-components/simple-reverb/blob/master/index.js * * Utility function for building an impulse response * based on the module parameters. * * @private */ p5.Reverb.prototype._buildImpulse = function () { var rate = this.ac.sampleRate; var length = rate * this._seconds; var decay = this._decay; var impulse = this.ac.createBuffer(2, length, rate); var impulseL = impulse.getChannelData(0); var impulseR = impulse.getChannelData(1); var n, i; for (i = 0; i < length; i++) { n = this.reverse ? length - i : i; impulseL[i] = (Math.random() * 2 - 1) * Math.pow(1 - n / length, decay); impulseR[i] = (Math.random() * 2 - 1) * Math.pow(1 - n / length, decay); } this.convolverNode.buffer = impulse; }; p5.Reverb.prototype.dispose = function () { if (this.convolverNode) { this.convolverNode.buffer = null; this.convolverNode = null; } if (typeof this.output !== 'undefined') { this.output.disconnect(); this.output = null; } if (typeof this.panner !== 'undefined') { this.panner.disconnect(); this.panner = null; } }; // ======================================================================= // *** p5.Convolver *** // ======================================================================= /** * <p>p5.Convolver extends p5.Reverb. It can emulate the sound of real * physical spaces through a process called <a href=" * https://en.wikipedia.org/wiki/Convolution_reverb#Real_space_simulation"> * convolution</a>.</p> * * <p>Convolution multiplies any audio input by an "impulse response" * to simulate the dispersion of sound over time. The impulse response is * generated from an audio file that you provide. One way to * generate an impulse response is to pop a balloon in a reverberant space * and record the echo. Convolution can also be used to experiment with * sound.</p> * * <p>Use the method <code>createConvolution(path)</code> to instantiate a * p5.Convolver with a path to your impulse response audio file.</p> * * @class p5.Convolver * @constructor * @param {String} path path to a sound file * @param {[Function]} callback function (optional) * @example * <div><code> * var cVerb, sound; * function preload() { * // We have both MP3 and OGG versions of all sound assets * soundFormats('ogg', 'mp3'); * * // Try replacing 'bx-spring' with other soundfiles like * // 'concrete-tunnel' 'small-plate' 'drum' 'beatbox' * cVerb = createConvolver('assets/bx-spring.mp3'); * * // Try replacing 'Damscray_DancingTiger' with * // 'beat', 'doorbell', lucky_dragons_-_power_melody' * sound = loadSound('assets/Damscray_DancingTiger.mp3'); * } * * function setup() { * // disconnect from master output... * sound.disconnect(); * * // ...and process with cVerb * // so that we only hear the convolution * cVerb.process(sound); * * sound.play(); * } * </code></div> */ p5.Convolver = function (path, callback) { this.ac = p5sound.audiocontext; /** * Internally, the p5.Convolver uses the a * <a href="http://www.w3.org/TR/webaudio/#ConvolverNode"> * Web Audio Convolver Node</a>. * * @property convolverNode * @type {Object} Web Audio Convolver Node */ this.convolverNode = this.ac.createConvolver(); this.input = this.ac.createGain(); this.output = this.ac.createGain(); // otherwise, Safari distorts this.input.gain.value = 0.5; this.input.connect(this.convolverNode); this.convolverNode.connect(this.output); if (path) { this.impulses = []; this._loadBuffer(path, callback); } else { // parameters this._seconds = 3; this._decay = 2; this._reverse = false; this._buildImpulse(); } this.connect(); p5sound.soundArray.push(this); }; p5.Convolver.prototype = Object.create(p5.Reverb.prototype); p5.prototype.registerPreloadMethod('createConvolver', p5.prototype); /** * Create a p5.Convolver. Accepts a path to a soundfile * that will be used to generate an impulse response. * * @method createConvolver * @param {String} path path to a sound file * @param {[Function]} callback function (optional) * @return {p5.Convolver} * @example * <div><code> * var cVerb, sound; * function preload() { * // We have both MP3 and OGG versions of all sound assets * soundFormats('ogg', 'mp3'); * * // Try replacing 'bx-spring' with other soundfiles like * // 'concrete-tunnel' 'small-plate' 'drum' 'beatbox' * cVerb = createConvolver('assets/bx-spring.mp3'); * * // Try replacing 'Damscray_DancingTiger' with * // 'beat', 'doorbell', lucky_dragons_-_power_melody' * sound = loadSound('assets/Damscray_DancingTiger.mp3'); * } * * function setup() { * // disconnect from master output... * sound.disconnect(); * * // ...and process with cVerb * // so that we only hear the convolution * cVerb.process(sound); * * sound.play(); * } * </code></div> */ p5.prototype.createConvolver = function (path, callback) { // if loading locally without a server if (window.location.origin.indexOf('file://') > -1 && window.cordova === 'undefined') { alert('This sketch may require a server to load external files. Please see http://bit.ly/1qcInwS'); } var cReverb = new p5.Convolver(path, callback); cReverb.impulses = []; return cReverb; }; /** * Private method to load a buffer as an Impulse Response, * assign it to the convolverNode, and add to the Array of .impulses. * * @param {String} path * @param {Function} callback * @private */ p5.Convolver.prototype._loadBuffer = function (path, callback) { path = p5.prototype._checkFileFormats(path); var request = new XMLHttpRequest(); request.open('GET', path, true); request.responseType = 'arraybuffer'; // decode asyncrohonously var self = this; request.onload = function () { var ac = p5.prototype.getAudioContext(); ac.decodeAudioData(request.response, function (buff) { var buffer = {}; var chunks = path.split('/'); buffer.name = chunks[chunks.length - 1]; buffer.audioBuffer = buff; self.impulses.push(buffer); self.convolverNode.buffer = buffer.audioBuffer; if (callback) { callback(buffer); } }); }; request.send(); }; p5.Convolver.prototype.set = null; /** * Connect a source to the reverb, and assign reverb parameters. * * @method process * @param {Object} src p5.sound / Web Audio object with a sound * output. * @example * <div><code> * var cVerb, sound; * function preload() { * soundFormats('ogg', 'mp3'); * * cVerb = createConvolver('assets/concrete-tunnel.mp3'); * * sound = loadSound('assets/beat.mp3'); * } * * function setup() { * // disconnect from master output... * sound.disconnect(); * * // ...and process with (i.e. connect to) cVerb * // so that we only hear the convolution * cVerb.process(sound); * * sound.play(); * } * </code></div> */ p5.Convolver.prototype.process = function (src) { src.connect(this.input); }; /** * If you load multiple impulse files using the .addImpulse method, * they will be stored as Objects in this Array. Toggle between them * with the <code>toggleImpulse(id)</code> method. * * @property impulses * @type {Array} Array of Web Audio Buffers */ p5.Convolver.prototype.impulses = []; /** * Load and assign a new Impulse Response to the p5.Convolver. * The impulse is added to the <code>.impulses</code> array. Previous * impulses can be accessed with the <code>.toggleImpulse(id)</code> * method. * * @method addImpulse * @param {String} path path to a sound file * @param {[Function]} callback function (optional) */ p5.Convolver.prototype.addImpulse = function (path, callback) { // if loading locally without a server if (window.location.origin.indexOf('file://') > -1 && window.cordova === 'undefined') { alert('This sketch may require a server to load external files. Please see http://bit.ly/1qcInwS'); } this._loadBuffer(path, callback); }; /** * Similar to .addImpulse, except that the <code>.impulses</code> * Array is reset to save memory. A new <code>.impulses</code> * array is created with this impulse as the only item. * * @method resetImpulse * @param {String} path path to a sound file * @param {[Function]} callback function (optional) */ p5.Convolver.prototype.resetImpulse = function (path, callback) { // if loading locally without a server if (window.location.origin.indexOf('file://') > -1 && window.cordova === 'undefined') { alert('This sketch may require a server to load external files. Please see http://bit.ly/1qcInwS'); } this.impulses = []; this._loadBuffer(path, callback); }; /** * If you have used <code>.addImpulse()</code> to add multiple impulses * to a p5.Convolver, then you can use this method to toggle between * the items in the <code>.impulses</code> Array. Accepts a parameter * to identify which impulse you wish to use, identified either by its * original filename (String) or by its position in the <code>.impulses * </code> Array (Number).<br/> * You can access the objects in the .impulses Array directly. Each * Object has two attributes: an <code>.audioBuffer</code> (type: * Web Audio <a href=" * http://webaudio.github.io/web-audio-api/#the-audiobuffer-interface"> * AudioBuffer)</a> and a <code>.name</code>, a String that corresponds * with the original filename. * * @method toggleImpulse * @param {String|Number} id Identify the impulse by its original filename * (String), or by its position in the * <code>.impulses</code> Array (Number). */ p5.Convolver.prototype.toggleImpulse = function (id) { if (typeof id === 'number' && id < this.impulses.length) { this.convolverNode.buffer = this.impulses[id].audioBuffer; } if (typeof id === 'string') { for (var i = 0; i < this.impulses.length; i++) { if (this.impulses[i].name === id) { this.convolverNode.buffer = this.impulses[i].audioBuffer; break; } } } }; p5.Convolver.prototype.dispose = function () { // remove all the Impulse Response buffers for (var i in this.impulses) { this.impulses[i] = null; } this.convolverNode.disconnect(); this.concolverNode = null; if (typeof this.output !== 'undefined') { this.output.disconnect(); this.output = null; } if (typeof this.panner !== 'undefined') { this.panner.disconnect(); this.panner = null; } }; }(master, sndcore); /** Tone.js module by Yotam Mann, MIT License 2014 http://opensource.org/licenses/MIT **/ var Tone_core_Clock; Tone_core_Clock = function (Tone) { 'use strict'; Tone.Clock = function (rate, callback) { this._oscillator = null; this._jsNode = this.context.createScriptProcessor(this.bufferSize, 1, 1); this._jsNode.onaudioprocess = this._processBuffer.bind(this); this._controlSignal = new Tone.Signal(1); this._upTick = false; this.tick = this.defaultArg(callback, function () { }); this._jsNode.noGC(); this.setRate(rate); }; Tone.extend(Tone.Clock); Tone.Clock.prototype.setRate = function (rate, rampTime) { var freqVal = this.secondsToFrequency(this.toSeconds(rate)); if (!rampTime) { this._controlSignal.cancelScheduledValues(0); this._controlSignal.setValue(freqVal); } else { this._controlSignal.exponentialRampToValueNow(freqVal, rampTime); } }; Tone.Clock.prototype.getRate = function () { return this._controlSignal.getValue(); }; Tone.Clock.prototype.start = function (time) { this._oscillator = this.context.createOscillator(); this._oscillator.type = 'square'; this._oscillator.connect(this._jsNode); this._controlSignal.connect(this._oscillator.frequency); this._upTick = false; var startTime = this.toSeconds(time); this._oscillator.start(startTime); this._oscillator.onended = function () { }; }; Tone.Clock.prototype.stop = function (time, onend) { var stopTime = this.toSeconds(time); this._oscillator.onended = onend; this._oscillator.stop(stopTime); }; Tone.Clock.prototype._processBuffer = function (event) { var now = this.defaultArg(event.playbackTime, this.now()); var bufferSize = this._jsNode.bufferSize; var incomingBuffer = event.inputBuffer.getChannelData(0); var upTick = this._upTick; var self = this; for (var i = 0; i < bufferSize; i++) { var sample = incomingBuffer[i]; if (sample > 0 && !upTick) { upTick = true; setTimeout(function () { var tickTime = now + self.samplesToSeconds(i + bufferSize * 2); return function () { self.tick(tickTime); }; }(), 0); } else if (sample < 0 && upTick) { upTick = false; } } this._upTick = upTick; }; Tone.Clock.prototype.dispose = function () { this._jsNode.disconnect(); this._controlSignal.dispose(); if (this._oscillator) { this._oscillator.onended(); this._oscillator.disconnect(); } this._jsNode.onaudioprocess = function () { }; this._jsNode = null; this._controlSignal = null; this._oscillator = null; }; return Tone.Clock; }(Tone_core_Tone); var metro; metro = function () { 'use strict'; var p5sound = master; // requires the Tone.js library's Clock (MIT license, Yotam Mann) // https://github.com/TONEnoTONE/Tone.js/ var Clock = Tone_core_Clock; var ac = p5sound.audiocontext; // var upTick = false; p5.Metro = function () { this.clock = new Clock(ac.sampleRate, this.ontick.bind(this)); this.syncedParts = []; this.bpm = 120; // gets overridden by p5.Part this._init(); this.tickCallback = function () { }; }; var prevTick = 0; var tatumTime = 0; p5.Metro.prototype.ontick = function (tickTime) { var elapsedTime = tickTime - prevTick; var secondsFromNow = tickTime - p5sound.audiocontext.currentTime; if (elapsedTime - tatumTime <= -0.02) { return; } else { prevTick = tickTime; // for all of the active things on the metro: for (var i in this.syncedParts) { var thisPart = this.syncedParts[i]; thisPart.incrementStep(secondsFromNow); // each synced source keeps track of its own beat number for (var j in thisPart.phrases) { var thisPhrase = thisPart.phrases[j]; var phraseArray = thisPhrase.sequence; var bNum = this.metroTicks % phraseArray.length; if (phraseArray[bNum] !== 0 && (this.metroTicks < phraseArray.length || !thisPhrase.looping)) { thisPhrase.callback(secondsFromNow, phraseArray[bNum]); } } } this.metroTicks += 1; this.tickCallback(secondsFromNow); } }; p5.Metro.prototype.setBPM = function (bpm, rampTime) { var beatTime = 60 / (bpm * this.tatums); tatumTime = beatTime; var ramp = rampTime || 0; this.clock.setRate(beatTime, rampTime + p5sound.audiocontext.currentTime); this.bpm = bpm; }; p5.Metro.prototype.getBPM = function (tempo) { return this.clock.getRate() / this.tatums * 60; }; p5.Metro.prototype._init = function () { this.metroTicks = 0; }; // clear existing synced parts, add only this one p5.Metro.prototype.resetSync = function (part) { this.syncedParts = [part]; }; // push a new synced part to the array p5.Metro.prototype.pushSync = function (part) { this.syncedParts.push(part); }; p5.Metro.prototype.start = function (time) { var t = time || 0; this.clock.start(t); this.setBPM(this.bpm); }; p5.Metro.prototype.stop = function (time) { var t = time || 0; if (this.clock._oscillator) { this.clock.stop(t); } }; p5.Metro.prototype.beatLength = function (tatums) { this.tatums = 1 / tatums / 4; }; }(master, Tone_core_Clock); var looper; looper = function () { 'use strict'; var p5sound = master; var bpm = 120; /** * Set the global tempo, in beats per minute, for all * p5.Parts. This method will impact all active p5.Parts. * * @param {Number} BPM Beats Per Minute * @param {Number} rampTime Seconds from now */ p5.prototype.setBPM = function (BPM, rampTime) { bpm = BPM; for (var i in p5sound.parts) { p5sound.parts[i].setBPM(bpm, rampTime); } }; /** * <p>A phrase is a pattern of musical events over time, i.e. * a series of notes and rests.</p> * * <p>Phrases must be added to a p5.Part for playback, and * each part can play multiple phrases at the same time. * For example, one Phrase might be a kick drum, another * could be a snare, and another could be the bassline.</p> * * <p>The first parameter is a name so that the phrase can be * modified or deleted later. The callback is a a function that * this phrase will call at every step—for example it might be * called <code>playNote(value){}</code>. The array determines * which value is passed into the callback at each step of the * phrase. It can be numbers, an object with multiple numbers, * or a zero (0) indicates a rest so the callback won't be called).</p> * * @class p5.Phrase * @constructor * @param {String} name Name so that you can access the Phrase. * @param {Function} callback The name of a function that this phrase * will call. Typically it will play a sound, * and accept two parameters: a time at which * to play the sound (in seconds from now), * and a value from the sequence array. The * time should be passed into the play() or * start() method to ensure precision. * @param {Array} sequence Array of values to pass into the callback * at each step of the phrase. * @example * <div><code> * var mySound, myPhrase, myPart; * var pattern = [1,0,0,2,0,2,0,0]; * var msg = 'click to play'; * * function preload() { * mySound = loadSound('assets/beatbox.mp3'); * } * * function setup() { * noStroke(); * fill(255); * textAlign(CENTER); * masterVolume(0.1); * * myPhrase = new p5.Phrase('bbox', makeSound, pattern); * myPart = new p5.Part(); * myPart.addPhrase(myPhrase); * myPart.setBPM(60); * } * * function draw() { * background(0); * text(msg, width/2, height/2); * } * * function makeSound(time, playbackRate) { * mySound.rate(playbackRate); * mySound.play(time); * } * * function mouseClicked() { * if (mouseX > 0 && mouseX < width && mouseY > 0 && mouseY < height) { * myPart.start(); * msg = 'playing pattern'; * } * } * * </code></div> */ p5.Phrase = function (name, callback, sequence) { this.phraseStep = 0; this.name = name; this.callback = callback; /** * Array of values to pass into the callback * at each step of the phrase. Depending on the callback * function's requirements, these values may be numbers, * strings, or an object with multiple parameters. * Zero (0) indicates a rest. * * @property sequence * @type {Array} */ this.sequence = sequence; }; /** * <p>A p5.Part plays back one or more p5.Phrases. Instantiate a part * with steps and tatums. By default, each step represents 1/16th note.</p> * * <p>See p5.Phrase for more about musical timing.</p> * * @class p5.Part * @constructor * @param {Number} [steps] Steps in the part * @param {Number} [tatums] Divisions of a beat (default is 1/16, a quarter note) * @example * <div><code> * var box, drum, myPart; * var boxPat = [1,0,0,2,0,2,0,0]; * var drumPat = [0,1,1,0,2,0,1,0]; * var msg = 'click to play'; * * function preload() { * box = loadSound('assets/beatbox.mp3'); * drum = loadSound('assets/drum.mp3'); * } * * function setup() { * noStroke(); * fill(255); * textAlign(CENTER); * masterVolume(0.1); * * var boxPhrase = new p5.Phrase('box', playBox, boxPat); * var drumPhrase = new p5.Phrase('drum', playDrum, drumPat); * myPart = new p5.Part(); * myPart.addPhrase(boxPhrase); * myPart.addPhrase(drumPhrase); * myPart.setBPM(60); * masterVolume(0.1); * } * * function draw() { * background(0); * text(msg, width/2, height/2); * } * * function playBox(time, playbackRate) { * box.rate(playbackRate); * box.play(time); * } * * function playDrum(time, playbackRate) { * drum.rate(playbackRate); * drum.play(time); * } * * function mouseClicked() { * if (mouseX > 0 && mouseX < width && mouseY > 0 && mouseY < height) { * myPart.start(); * msg = 'playing part'; * } * } * </code></div> */ p5.Part = function (steps, bLength) { this.length = steps || 0; // how many beats this.partStep = 0; this.phrases = []; this.looping = false; this.isPlaying = false; // what does this looper do when it gets to the last step? this.onended = function () { this.stop(); }; this.tatums = bLength || 0.0625; // defaults to quarter note this.metro = new p5.Metro(); this.metro._init(); this.metro.beatLength(this.tatums); this.metro.setBPM(bpm); p5sound.parts.push(this); this.callback = function () { }; }; /** * Set the tempo of this part, in Beats Per Minute. * * @method setBPM * @param {Number} BPM Beats Per Minute * @param {Number} [rampTime] Seconds from now */ p5.Part.prototype.setBPM = function (tempo, rampTime) { this.metro.setBPM(tempo, rampTime); }; /** * Returns the Beats Per Minute of this currently part. * * @method getBPM * @return {Number} */ p5.Part.prototype.getBPM = function () { return this.metro.getBPM(); }; /** * Start playback of this part. It will play * through all of its phrases at a speed * determined by setBPM. * * @method start * @param {Number} [time] seconds from now */ p5.Part.prototype.start = function (time) { if (!this.isPlaying) { this.isPlaying = true; this.metro.resetSync(this); var t = time || 0; this.metro.start(t); } }; /** * Loop playback of this part. It will begin * looping through all of its phrases at a speed * determined by setBPM. * * @method loop * @param {Number} [time] seconds from now */ p5.Part.prototype.loop = function (time) { this.looping = true; // rest onended function this.onended = function () { this.partStep = 0; }; var t = time || 0; this.start(t); }; /** * Tell the part to stop looping. * * @method noLoop */ p5.Part.prototype.noLoop = function () { this.looping = false; // rest onended function this.onended = function () { this.stop(); }; }; /** * Stop the part and cue it to step 0. * * @method stop * @param {Number} [time] seconds from now */ p5.Part.prototype.stop = function (time) { this.partStep = 0; this.pause(time); }; /** * Pause the part. Playback will resume * from the current step. * * @method pause * @param {Number} time seconds from now */ p5.Part.prototype.pause = function (time) { this.isPlaying = false; var t = time || 0; this.metro.stop(t); }; /** * Add a p5.Phrase to this Part. * * @method addPhrase * @param {p5.Phrase} phrase reference to a p5.Phrase */ p5.Part.prototype.addPhrase = function (name, callback, array) { var p; if (arguments.length === 3) { p = new p5.Phrase(name, callback, array); } else if (arguments[0] instanceof p5.Phrase) { p = arguments[0]; } else { throw 'invalid input. addPhrase accepts name, callback, array or a p5.Phrase'; } this.phrases.push(p); // reset the length if phrase is longer than part's existing length if (p.sequence.length > this.length) { this.length = p.sequence.length; } }; /** * Remove a phrase from this part, based on the name it was * given when it was created. * * @method removePhrase * @param {String} phraseName */ p5.Part.prototype.removePhrase = function (name) { for (var i in this.phrases) { if (this.phrases[i].name === name) { this.phrases.split(i, 1); } } }; /** * Get a phrase from this part, based on the name it was * given when it was created. Now you can modify its array. * * @method getPhrase * @param {String} phraseName */ p5.Part.prototype.getPhrase = function (name) { for (var i in this.phrases) { if (this.phrases[i].name === name) { return this.phrases[i]; } } }; /** * Get a phrase from this part, based on the name it was * given when it was created. Now you can modify its array. * * @method replaceSequence * @param {String} phraseName * @param {Array} sequence Array of values to pass into the callback * at each step of the phrase. */ p5.Part.prototype.replaceSequence = function (name, array) { for (var i in this.phrases) { if (this.phrases[i].name === name) { this.phrases[i].sequence = array; } } }; p5.Part.prototype.incrementStep = function (time) { if (this.partStep < this.length - 1) { this.callback(time); this.partStep += 1; } else { if (this.looping) { this.callback(time); } this.onended(); this.partStep = 0; } }; /** * Fire a callback function at every step. * * @method onStep * @param {Function} callback The name of the callback * you want to fire * on every beat/tatum. */ p5.Part.prototype.onStep = function (callback) { this.callback = callback; }; // =============== // p5.Score // =============== /** * A Score consists of a series of Parts. The parts will * be played back in order. For example, you could have an * A part, a B part, and a C part, and play them back in this order * <code>new p5.Score(a, a, b, a, c)</code> * * @class p5.Score * @constructor * @param {p5.Part} part(s) One or multiple parts, to be played in sequence. * @return {p5.Score} */ p5.Score = function () { // for all of the arguments this.parts = []; this.currentPart = 0; var thisScore = this; for (var i in arguments) { this.parts[i] = arguments[i]; this.parts[i].nextPart = this.parts[i + 1]; this.parts[i].onended = function () { thisScore.resetPart(i); playNextPart(thisScore); }; } this.looping = false; }; p5.Score.prototype.onended = function () { if (this.looping) { // this.resetParts(); this.parts[0].start(); } else { this.parts[this.parts.length - 1].onended = function () { this.stop(); this.resetParts(); }; } this.currentPart = 0; }; /** * Start playback of the score. * * @method start */ p5.Score.prototype.start = function () { this.parts[this.currentPart].start(); this.scoreStep = 0; }; /** * Stop playback of the score. * * @method stop */ p5.Score.prototype.stop = function () { this.parts[this.currentPart].stop(); this.currentPart = 0; this.scoreStep = 0; }; /** * Pause playback of the score. * * @method pause */ p5.Score.prototype.pause = function () { this.parts[this.currentPart].stop(); }; /** * Loop playback of the score. * * @method loop */ p5.Score.prototype.loop = function () { this.looping = true; this.start(); }; /** * Stop looping playback of the score. If it * is currently playing, this will go into effect * after the current round of playback completes. * * @method noLoop */ p5.Score.prototype.noLoop = function () { this.looping = false; }; p5.Score.prototype.resetParts = function () { for (var i in this.parts) { this.resetPart(i); } }; p5.Score.prototype.resetPart = function (i) { this.parts[i].stop(); this.parts[i].partStep = 0; for (var p in this.parts[i].phrases) { this.parts[i].phrases[p].phraseStep = 0; } }; /** * Set the tempo for all parts in the score * * @param {Number} BPM Beats Per Minute * @param {Number} rampTime Seconds from now */ p5.Score.prototype.setBPM = function (bpm, rampTime) { for (var i in this.parts) { this.parts[i].setBPM(bpm, rampTime); } }; function playNextPart(aScore) { aScore.currentPart++; if (aScore.currentPart >= aScore.parts.length) { aScore.scoreStep = 0; aScore.onended(); } else { aScore.scoreStep = 0; aScore.parts[aScore.currentPart - 1].stop(); aScore.parts[aScore.currentPart].start(); } } }(master); var soundRecorder; soundRecorder = function () { 'use strict'; var p5sound = master; var ac = p5sound.audiocontext; /** * <p>Record sounds for playback and/or to save as a .wav file. * The p5.SoundRecorder records all sound output from your sketch, * or can be assigned a specific source with setInput().</p> * <p>The record() method accepts a p5.SoundFile as a parameter. * When playback is stopped (either after the given amount of time, * or with the stop() method), the p5.SoundRecorder will send its * recording to that p5.SoundFile for playback.</p> * * @class p5.SoundRecorder * @constructor * @example * <div><code> * var mic, recorder, soundFile; * var state = 0; * * function setup() { * background(200); * // create an audio in * mic = new p5.AudioIn(); * * // prompts user to enable their browser mic * mic.start(); * * // create a sound recorder * recorder = new p5.SoundRecorder(); * * // connect the mic to the recorder * recorder.setInput(mic); * * // this sound file will be used to * // playback & save the recording * soundFile = new p5.SoundFile(); * * text('keyPress to record', 20, 20); * } * * function keyPressed() { * // make sure user enabled the mic * if (state === 0 && mic.enabled) { * * // record to our p5.SoundFile * recorder.record(soundFile); * * background(255,0,0); * text('Recording!', 20, 20); * state++; * } * else if (state === 1) { * background(0,255,0); * * // stop recorder and * // send result to soundFile * recorder.stop(); * * text('Stopped', 20, 20); * state++; * } * * else if (state === 2) { * soundFile.play(); // play the result! * save(soundFile, 'mySound.wav'); * state++; * } * } * </div></code> */ p5.SoundRecorder = function () { this.input = ac.createGain(); this.output = ac.createGain(); this.recording = false; this.bufferSize = 1024; this._channels = 2; // stereo (default) this._clear(); // initialize variables this._jsNode = ac.createScriptProcessor(this.bufferSize, this._channels, 2); this._jsNode.onaudioprocess = this._audioprocess.bind(this); /** * callback invoked when the recording is over * @private * @type {function(Float32Array)} */ this._callback = function () { }; // connections this._jsNode.connect(p5.soundOut._silentNode); this.setInput(); // add this p5.SoundFile to the soundArray p5sound.soundArray.push(this); }; /** * Connect a specific device to the p5.SoundRecorder. * If no parameter is given, p5.SoundRecorer will record * all audible p5.sound from your sketch. * * @method setInput * @param {Object} [unit] p5.sound object or a web audio unit * that outputs sound */ p5.SoundRecorder.prototype.setInput = function (unit) { this.input.disconnect(); this.input = null; this.input = ac.createGain(); this.input.connect(this._jsNode); this.input.connect(this.output); if (unit) { unit.connect(this.input); } else { p5.soundOut.output.connect(this.input); } }; /** * Start recording. To access the recording, provide * a p5.SoundFile as the first parameter. The p5.SoundRecorder * will send its recording to that p5.SoundFile for playback once * recording is complete. Optional parameters include duration * (in seconds) of the recording, and a callback function that * will be called once the complete recording has been * transfered to the p5.SoundFile. * * @method record * @param {p5.SoundFile} soundFile p5.SoundFile * @param {Number} [duration] Time (in seconds) * @param {Function} [callback] The name of a function that will be * called once the recording completes */ p5.SoundRecorder.prototype.record = function (sFile, duration, callback) { this.recording = true; if (duration) { this.sampleLimit = Math.round(duration * ac.sampleRate); } if (sFile && callback) { this._callback = function () { this.buffer = this._getBuffer(); sFile.setBuffer(this.buffer); callback(); }; } else if (sFile) { this._callback = function () { this.buffer = this._getBuffer(); sFile.setBuffer(this.buffer); }; } }; /** * Stop the recording. Once the recording is stopped, * the results will be sent to the p5.SoundFile that * was given on .record(), and if a callback function * was provided on record, that function will be called. * * @method stop */ p5.SoundRecorder.prototype.stop = function () { this.recording = false; this._callback(); this._clear(); }; p5.SoundRecorder.prototype._clear = function () { this._leftBuffers = []; this._rightBuffers = []; this.recordedSamples = 0; this.sampleLimit = null; }; /** * internal method called on audio process * * @private * @param {AudioProcessorEvent} event */ p5.SoundRecorder.prototype._audioprocess = function (event) { if (this.recording === false) { return; } else if (this.recording === true) { // if we are past the duration, then stop... else: if (this.sampleLimit && this.recordedSamples >= this.sampleLimit) { this.stop(); } else { // get channel data var left = event.inputBuffer.getChannelData(0); var right = event.inputBuffer.getChannelData(1); // clone the samples this._leftBuffers.push(new Float32Array(left)); this._rightBuffers.push(new Float32Array(right)); this.recordedSamples += this.bufferSize; } } }; p5.SoundRecorder.prototype._getBuffer = function () { var buffers = []; buffers.push(this._mergeBuffers(this._leftBuffers)); buffers.push(this._mergeBuffers(this._rightBuffers)); return buffers; }; p5.SoundRecorder.prototype._mergeBuffers = function (channelBuffer) { var result = new Float32Array(this.recordedSamples); var offset = 0; var lng = channelBuffer.length; for (var i = 0; i < lng; i++) { var buffer = channelBuffer[i]; result.set(buffer, offset); offset += buffer.length; } return result; }; p5.SoundRecorder.prototype.dispose = function () { this._clear(); this._callback = function () { }; if (this.input) { this.input.disconnect(); } this.input = null; this._jsNode = null; }; /** * Save a p5.SoundFile as a .wav audio file. * * @method saveSound * @param {p5.SoundFile} soundFile p5.SoundFile that you wish to save * @param {String} name name of the resulting .wav file. */ p5.prototype.saveSound = function (soundFile, name) { var leftChannel = soundFile.buffer.getChannelData(0); var rightChannel = soundFile.buffer.getChannelData(1); var interleaved = interleave(leftChannel, rightChannel); // create the buffer and view to create the .WAV file var buffer = new ArrayBuffer(44 + interleaved.length * 2); var view = new DataView(buffer); // write the WAV container, // check spec at: https://ccrma.stanford.edu/courses/422/projects/WaveFormat/ // RIFF chunk descriptor writeUTFBytes(view, 0, 'RIFF'); view.setUint32(4, 44 + interleaved.length * 2, true); writeUTFBytes(view, 8, 'WAVE'); // FMT sub-chunk writeUTFBytes(view, 12, 'fmt '); view.setUint32(16, 16, true); view.setUint16(20, 1, true); // stereo (2 channels) view.setUint16(22, 2, true); view.setUint32(24, 44100, true); view.setUint32(28, 44100 * 4, true); view.setUint16(32, 4, true); view.setUint16(34, 16, true); // data sub-chunk writeUTFBytes(view, 36, 'data'); view.setUint32(40, interleaved.length * 2, true); // write the PCM samples var lng = interleaved.length; var index = 44; var volume = 1; for (var i = 0; i < lng; i++) { view.setInt16(index, interleaved[i] * (32767 * volume), true); index += 2; } p5.prototype.writeFile([view], name, 'wav'); }; // helper methods to save waves function interleave(leftChannel, rightChannel) { var length = leftChannel.length + rightChannel.length; var result = new Float32Array(length); var inputIndex = 0; for (var index = 0; index < length;) { result[index++] = leftChannel[inputIndex]; result[index++] = rightChannel[inputIndex]; inputIndex++; } return result; } function writeUTFBytes(view, offset, string) { var lng = string.length; for (var i = 0; i < lng; i++) { view.setUint8(offset + i, string.charCodeAt(i)); } } }(sndcore, master); var peakdetect; peakdetect = function () { 'use strict'; var p5sound = master; /** * <p>PeakDetect works in conjunction with p5.FFT to * look for onsets in some or all of the frequency spectrum. * </p> * <p> * To use p5.PeakDetect, call <code>update</code> in the draw loop * and pass in a p5.FFT object. * </p> * <p> * You can listen for a specific part of the frequency spectrum by * setting the range between <code>freq1</code> and <code>freq2</code>. * </p> * * <p><code>threshold</code> is the threshold for detecting a peak, * scaled between 0 and 1. It is logarithmic, so 0.1 is half as loud * as 1.0.</p> * * <p> * The update method is meant to be run in the draw loop, and * <b>frames</b> determines how many loops must pass before * another peak can be detected. * For example, if the frameRate() = 60, you could detect the beat of a * 120 beat-per-minute song with this equation: * <code> framesPerPeak = 60 / (estimatedBPM / 60 );</code> * </p> * * <p> * Based on example contribtued by @b2renger, and a simple beat detection * explanation by <a * href="http://www.airtightinteractive.com/2013/10/making-audio-reactive-visuals/" * target="_blank">Felix Turner</a>. * </p> * * @class p5.PeakDetect * @constructor * @param {Number} [freq1] lowFrequency - defaults to 20Hz * @param {Number} [freq2] highFrequency - defaults to 20000 Hz * @param {Number} [threshold] Threshold for detecting a beat between 0 and 1 * scaled logarithmically where 0.1 is 1/2 the loudness * of 1.0. Defaults to 0.35. * @param {Number} [framesPerPeak] Defaults to 20. * @example * <div><code> * * var cnv, soundFile, fft, peakDetect; * var ellipseWidth = 10; * * function setup() { * background(0); * noStroke(); * fill(255); * textAlign(CENTER); * * soundFile = loadSound('assets/beat.mp3'); * * // p5.PeakDetect requires a p5.FFT * fft = new p5.FFT(); * peakDetect = new p5.PeakDetect(); * * } * * function draw() { * background(0); * text('click to play/pause', width/2, height/2); * * // peakDetect accepts an fft post-analysis * fft.analyze(); * peakDetect.update(fft); * * if ( peakDetect.isDetected ) { * ellipseWidth = 50; * } else { * ellipseWidth *= 0.95; * } * * ellipse(width/2, height/2, ellipseWidth, ellipseWidth); * } * * // toggle play/stop when canvas is clicked * function mouseClicked() { * if (mouseX > 0 && mouseX < width && mouseY > 0 && mouseY < height) { * if (soundFile.isPlaying() ) { * soundFile.stop(); * } else { * soundFile.play(); * } * } * } * </code></div> */ p5.PeakDetect = function (freq1, freq2, threshold, _framesPerPeak) { var framesPerPeak; // framesPerPeak determines how often to look for a beat. // If a beat is provided, try to look for a beat based on bpm this.framesPerPeak = _framesPerPeak || 20; this.framesSinceLastPeak = 0; this.decayRate = 0.95; this.threshold = threshold || 0.35; this.cutoff = 0; // how much to increase the cutoff // TO DO: document this / figure out how to make it accessible this.cutoffMult = 1.5; this.energy = 0; this.penergy = 0; // TO DO: document this property / figure out how to make it accessible this.currentValue = 0; /** * isDetected is set to true when a peak is detected. * * @attribute isDetected * @type {Boolean} * @default false */ this.isDetected = false; this.f1 = freq1 || 40; this.f2 = freq2 || 20000; // function to call when a peak is detected this._onPeak = function () { }; }; /** * The update method is run in the draw loop. * * Accepts an FFT object. You must call .analyze() * on the FFT object prior to updating the peakDetect * because it relies on a completed FFT analysis. * * @method update * @param {p5.FFT} fftObject A p5.FFT object */ p5.PeakDetect.prototype.update = function (fftObject) { var nrg = this.energy = fftObject.getEnergy(this.f1, this.f2) / 255; if (nrg > this.cutoff && nrg > this.threshold && nrg - this.penergy > 0) { // trigger callback this._onPeak(); this.isDetected = true; // debounce this.cutoff = nrg * this.cutoffMult; this.framesSinceLastPeak = 0; } else { this.isDetected = false; if (this.framesSinceLastPeak <= this.framesPerPeak) { this.framesSinceLastPeak++; } else { this.cutoff *= this.decayRate; this.cutoff = Math.max(this.cutoff, this.threshold); } } this.currentValue = nrg; this.penergy = nrg; }; /** * onPeak accepts two arguments: a function to call when * a peak is detected. The value of the peak, * between 0.0 and 1.0, is passed to the callback. * * @method onPeak * @param {Function} callback Name of a function that will * be called when a peak is * detected. * @param {Object} [val] Optional value to pass * into the function when * a peak is detected. * @example * <div><code> * var cnv, soundFile, fft, peakDetect; * var ellipseWidth = 0; * * function setup() { * cnv = createCanvas(100,100); * textAlign(CENTER); * * soundFile = loadSound('assets/beat.mp3'); * fft = new p5.FFT(); * peakDetect = new p5.PeakDetect(); * * setupSound(); * * // when a beat is detected, call triggerBeat() * peakDetect.onPeak(triggerBeat); * } * * function draw() { * background(0); * fill(255); * text('click to play', width/2, height/2); * * fft.analyze(); * peakDetect.update(fft); * * ellipseWidth *= 0.95; * ellipse(width/2, height/2, ellipseWidth, ellipseWidth); * } * * // this function is called by peakDetect.onPeak * function triggerBeat() { * ellipseWidth = 50; * } * * // mouseclick starts/stops sound * function setupSound() { * cnv.mouseClicked( function() { * if (soundFile.isPlaying() ) { * soundFile.stop(); * } else { * soundFile.play(); * } * }); * } * </code></div> */ p5.PeakDetect.prototype.onPeak = function (callback, val) { var self = this; self._onPeak = function () { callback(self.energy, val); }; }; }(master); var gain; gain = function () { 'use strict'; var p5sound = master; /** * A gain node is usefull to set the relative volume of sound. * It's typically used to build mixers. * * @class p5.Gain * @constructor * @example * <div><code> * * // load two soundfile and crossfade beetween them * var sound1,sound2; * var gain1, gain2, gain3; * * function preload(){ * soundFormats('ogg', 'mp3'); * sound1 = loadSound('../_files/Damscray_-_Dancing_Tiger_01'); * sound2 = loadSound('../_files/beat.mp3'); * } * * function setup() { * createCanvas(400,200); * * // create a 'master' gain to which we will connect both soundfiles * gain3 = new p5.Gain(); * gain3.connect(); * * // setup first sound for playing * sound1.rate(1); * sound1.loop(); * sound1.disconnect(); // diconnect from p5 output * * gain1 = new p5.Gain(); // setup a gain node * gain1.setInput(sound1); // connect the first sound to its input * gain1.connect(gain3); // connect its output to the 'master' * * sound2.rate(1); * sound2.disconnect(); * sound2.loop(); * * gain2 = new p5.Gain(); * gain2.setInput(sound2); * gain2.connect(gain3); * * } * * function draw(){ * background(180); * * // calculate the horizontal distance beetween the mouse and the right of the screen * var d = dist(mouseX,0,width,0); * * // map the horizontal position of the mouse to values useable for volume control of sound1 * var vol1 = map(mouseX,0,width,0,1); * var vol2 = 1-vol1; // when sound1 is loud, sound2 is quiet and vice versa * * gain1.amp(vol1,0.5,0); * gain2.amp(vol2,0.5,0); * * // map the vertical position of the mouse to values useable for 'master volume control' * var vol3 = map(mouseY,0,height,0,1); * gain3.amp(vol3,0.5,0); * } *</code></div> * */ p5.Gain = function () { this.ac = p5sound.audiocontext; this.input = this.ac.createGain(); this.output = this.ac.createGain(); // otherwise, Safari distorts this.input.gain.value = 0.5; this.input.connect(this.output); }; /** * Connect a source to the gain node. * * @method setInput * @param {Object} src p5.sound / Web Audio object with a sound * output. */ p5.Gain.prototype.setInput = function (src) { src.connect(this.input); }; /** * Send output to a p5.sound or web audio object * * @method connect * @param {Object} unit */ p5.Gain.prototype.connect = function (unit) { var u = unit || p5.soundOut.input; this.output.connect(u.input ? u.input : u); }; /** * Disconnect all output. * * @method disconnect */ p5.Gain.prototype.disconnect = function () { this.output.disconnect(); }; /** * Set the output level of the gain node. * * @method amp * @param {Number} volume amplitude between 0 and 1.0 * @param {Number} [rampTime] create a fade that lasts rampTime * @param {Number} [timeFromNow] schedule this event to happen * seconds from now */ p5.Gain.prototype.amp = function (vol, rampTime, tFromNow) { var rampTime = rampTime || 0; var tFromNow = tFromNow || 0; var now = p5sound.audiocontext.currentTime; var currentVol = this.output.gain.value; this.output.gain.cancelScheduledValues(now); this.output.gain.linearRampToValueAtTime(currentVol, now + tFromNow); this.output.gain.linearRampToValueAtTime(vol, now + tFromNow + rampTime); }; }(master, sndcore); var src_app; src_app = function () { 'use strict'; var p5SOUND = sndcore; return p5SOUND; }(sndcore, master, helpers, panner, soundfile, amplitude, fft, signal, oscillator, env, pulse, noise, audioin, filter, delay, reverb, metro, looper, soundRecorder, peakdetect, gain); }));
var _createPredicateIndexFinder = require('./_createPredicateIndexFinder.js'); // Returns the first index on an array-like that passes a truth test. var findIndex = _createPredicateIndexFinder(1); module.exports = findIndex;
// @flow // $WithVersion >=0.0.0 (123: string); // should be suppressed // $WithVersion >=1000000.0.0 (123: string); // should not be suppressed
/*! * FileInput Chinese Translations * * This file must be loaded after 'fileinput.js'. Patterns in braces '{}', or * any HTML markup tags in the messages must not be converted or translated. * * @see http://github.com/kartik-v/bootstrap-fileinput * @author kangqf <kangqingfei@gmail.com> * * NOTE: this file must be saved in UTF-8 encoding. */ (function ($) { "use strict"; $.fn.fileinputLocales['zh'] = { fileSingle: '文件', filePlural: '个文件', browseLabel: '选择 &hellip;', removeLabel: '移除', removeTitle: '清除选中文件', cancelLabel: '取消', cancelTitle: '取消进行中的上传', pauseLabel: 'Pause', pauseTitle: 'Pause ongoing upload', uploadLabel: '上传', uploadTitle: '上传选中文件', msgNo: '没有', msgNoFilesSelected: '未选择文件', msgPaused: 'Paused', msgCancelled: '取消', msgPlaceholder: '选择 {files} ...', msgZoomModalHeading: '详细预览', msgFileRequired: '必须选择一个文件上传.', msgSizeTooSmall: '文件 "{name}" (<b>{size} KB</b>) 必须大于限定大小 <b>{minSize} KB</b>.', msgSizeTooLarge: '文件 "{name}" (<b>{size} KB</b>) 超过了允许大小 <b>{maxSize} KB</b>.', msgFilesTooLess: '你必须选择最少 <b>{n}</b> {files} 来上传. ', msgFilesTooMany: '选择的上传文件个数 <b>({n})</b> 超出最大文件的限制个数 <b>{m}</b>.', msgTotalFilesTooMany: 'You can upload a maximum of <b>{m}</b> files (<b>{n}</b> files detected).', msgFileNotFound: '文件 "{name}" 未找到!', msgFileSecured: '安全限制,为了防止读取文件 "{name}".', msgFileNotReadable: '文件 "{name}" 不可读.', msgFilePreviewAborted: '取消 "{name}" 的预览.', msgFilePreviewError: '读取 "{name}" 时出现了一个错误.', msgInvalidFileName: '文件名 "{name}" 包含非法字符.', msgInvalidFileType: '不正确的类型 "{name}". 只支持 "{types}" 类型的文件.', msgInvalidFileExtension: '不正确的文件扩展名 "{name}". 只支持 "{extensions}" 的文件扩展名.', msgFileTypes: { 'image': 'image', 'html': 'HTML', 'text': 'text', 'video': 'video', 'audio': 'audio', 'flash': 'flash', 'pdf': 'PDF', 'object': 'object' }, msgUploadAborted: '该文件上传被中止', msgUploadThreshold: '处理中 &hellip;', msgUploadBegin: '正在初始化 &hellip;', msgUploadEnd: '完成', msgUploadResume: 'Resuming upload &hellip;', msgUploadEmpty: '无效的文件上传.', msgUploadError: 'Upload Error', msgDeleteError: 'Delete Error', msgProgressError: '上传出错', msgValidationError: '验证错误', msgLoading: '加载第 {index} 文件 共 {files} &hellip;', msgProgress: '加载第 {index} 文件 共 {files} - {name} - {percent}% 完成.', msgSelected: '{n} {files} 选中', msgFoldersNotAllowed: '只支持拖拽文件! 跳过 {n} 拖拽的文件夹.', msgImageWidthSmall: '图像文件的"{name}"的宽度必须是至少{size}像素.', msgImageHeightSmall: '图像文件的"{name}"的高度必须至少为{size}像素.', msgImageWidthLarge: '图像文件"{name}"的宽度不能超过{size}像素.', msgImageHeightLarge: '图像文件"{name}"的高度不能超过{size}像素.', msgImageResizeError: '无法获取的图像尺寸调整。', msgImageResizeException: '调整图像大小时发生错误。<pre>{errors}</pre>', msgAjaxError: '{operation} 发生错误. 请重试!', msgAjaxProgressError: '{operation} 失败', msgDuplicateFile: 'File "{name}" of same size "{size} KB" has already been selected earlier. Skipping duplicate selection.', msgResumableUploadRetriesExceeded: 'Upload aborted beyond <b>{max}</b> retries for file <b>{file}</b>! Error Details: <pre>{error}</pre>', msgPendingTime: '{time} remaining', msgCalculatingTime: 'calculating time remaining', ajaxOperations: { deleteThumb: '删除文件', uploadThumb: '上传文件', uploadBatch: '批量上传', uploadExtra: '表单数据上传' }, dropZoneTitle: '拖拽文件到这里 &hellip;<br>支持多文件同时上传', dropZoneClickTitle: '<br>(或点击{files}按钮选择文件)', fileActionSettings: { removeTitle: '删除文件', uploadTitle: '上传文件', downloadTitle: '下载文件', uploadRetryTitle: '重试', zoomTitle: '查看详情', dragTitle: '移动 / 重置', indicatorNewTitle: '没有上传', indicatorSuccessTitle: '上传', indicatorErrorTitle: '上传错误', indicatorPausedTitle: 'Upload Paused', indicatorLoadingTitle: '上传 &hellip;' }, previewZoomButtonTitles: { prev: '预览上一个文件', next: '预览下一个文件', toggleheader: '缩放', fullscreen: '全屏', borderless: '无边界模式', close: '关闭当前预览' } }; })(window.jQuery);
var assert = require('assert'); var versionChecker = require('..'); var lodash = require('lodash'); describe('ember-cli-version-checker', function() { function FakeAddonAtVersion(version, projectProperties) { this.name = 'fake-addon'; this.project = lodash.assign({}, { emberCLIVersion: function() { return version; } }, projectProperties); } describe('VersionChecker#for', function() { var addon, checker; beforeEach(function() { addon = new FakeAddonAtVersion('0.1.15-addon-discovery-752a419d85', { bowerDirectory: 'tests/fixtures/bower-1', nodeModulesPath: 'tests/fixtures/npm-1' }); checker = new versionChecker(addon); }); describe('version', function() { it('can return a bower version', function() { var thing = checker.for('ember', 'bower'); assert.equal(thing.version, '1.12.1'); }); it('can return a fallback bower version for non-tagged releases', function() { addon.project.bowerDirectory = 'tests/fixtures/bower-2'; var thing = checker.for('ember', 'bower'); assert.equal(thing.version, '1.13.2'); }); it('can return a npm version', function() { var thing = checker.for('ember', 'npm'); assert.equal(thing.version, '2.0.0'); }); it('does not exist in bower_components', function() { var thing = checker.for('does-not-exist-dummy', 'bower'); assert.equal(thing.version, null); }); it('does not exist in nodeModulesPath', function() { var thing = checker.for('does-not-exist-dummy', 'npm'); assert.equal(thing.version, null); }); }); describe('satisfies', function() { it('returns true if version is included within range', function() { var thing = checker.for('ember', 'npm'); assert.equal(thing.satisfies('>= 0.0.1'), true); }); it('returns false if version is not included within range', function() { var thing = checker.for('ember', 'npm'); assert.equal(thing.satisfies('>= 99.0.0'), false); }); }); describe('isAbove', function() { it('returns true if version is above the specified range', function() { var thing = checker.for('ember', 'npm'); assert.equal(thing.isAbove('0.0.1'), true); }); it('returns false if version is below the specified range', function() { var thing = checker.for('ember', 'npm'); assert.equal(thing.isAbove('99.0.0'), false); }); }); describe('gt', function() { it('returns true if version is above the specified range', function() { var thing = checker.for('ember', 'npm'); assert.equal(thing.gt('0.0.1'), true); }); it('returns false if version is below the specified range', function() { var thing = checker.for('ember', 'npm'); assert.equal(thing.gt('99.0.0'), false); }); }); describe('lt', function() { it('returns false if version is above the specified range', function() { var thing = checker.for('ember', 'npm'); assert.equal(thing.lt('0.0.1'), false); }); it('returns true if version is below the specified range', function() { var thing = checker.for('ember', 'npm'); assert.equal(thing.lt('99.0.0'), true); }); }); describe('assertAbove', function() { it('throws an error with a default message if a matching version was not found', function() { var thing = checker.for('ember', 'npm'); var message = 'The addon `fake-addon` requires the npm package `ember` to be above 999.0.0, but you have 2.0.0.'; assert.throws(function() { thing.assertAbove('999.0.0'); }, new RegExp(message)); }); it('throws an error with the given message if a matching version was not found', function() { var message = 'Must use at least Ember CLI 0.1.2 to use xyz feature'; var thing = checker.for('ember', 'npm'); assert.throws(function() { thing.assertAbove('999.0.0', message); }, new RegExp(message)); }); it('throws a silent error', function() { var message = 'Must use at least Ember CLI 0.1.2 to use xyz feature'; var thing = checker.for('ember', 'npm'); assert.throws(function() { thing.assertAbove('999.0.0', message); }, function(err) { return err.suppressStacktrace; }); }); }); }); describe('isAbove', function() { it('handles metadata after version number', function() { var addon = new FakeAddonAtVersion('0.1.15-addon-discovery-752a419d85'); assert.ok(versionChecker.isAbove(addon, '0.0.0')); addon = new FakeAddonAtVersion('0.1.15-addon-discovery-752a419d85'); assert.ok(!versionChecker.isAbove(addon, '100.0.0')); }); it('does not error if addon does not have `project`', function() { var addon = {}; assert.ok(!versionChecker.isAbove(addon, '0.0.0')); }); it('`0.0.1` should be above `0.0.0`', function() { var addon = new FakeAddonAtVersion('0.0.1'); assert.ok(versionChecker.isAbove(addon, '0.0.0')); }); it('`0.1.0` should be above `0.0.46`', function() { var addon = new FakeAddonAtVersion('0.1.0'); assert.ok(versionChecker.isAbove(addon, '0.0.46')); }); it('`0.1.1` should be above `0.1.0`', function() { var addon = new FakeAddonAtVersion('0.1.1'); assert.ok(versionChecker.isAbove(addon, '0.1.0')); }); it('`1.0.0` should be above `0.1.0`', function() { var addon = new FakeAddonAtVersion('1.0.0'); assert.ok(versionChecker.isAbove(addon, '0.1.0')); }); it('`0.1.0` should be below `1.0.0`', function() { var addon = new FakeAddonAtVersion('0.1.0'); assert.ok(!versionChecker.isAbove(addon, '1.0.0')); }); it('`0.1.0` should be below `0.1.2`', function() { var addon = new FakeAddonAtVersion('0.1.0'); assert.ok(!versionChecker.isAbove(addon, '0.1.2')); }); }); describe('assertAbove', function() { it('throws an error with a default message if a matching version was not found', function() { var addon = new FakeAddonAtVersion('0.1.0'); var message = 'The addon `fake-addon` requires an Ember CLI version of 0.1.2 or above, but you are running 0.1.0.'; assert.throws(function() { versionChecker.assertAbove(addon, '0.1.2',message); }, new RegExp(message)); }); it('throws an error with the given message if a matching version was not found', function() { var addon = new FakeAddonAtVersion('0.1.0'); var message = 'Must use at least Ember CLI 0.1.2 to use xyz feature'; assert.throws(function() { versionChecker.assertAbove(addon, '0.1.2',message); }, new RegExp(message)); }); it('throws a silent error', function() { var addon = new FakeAddonAtVersion('0.1.0'); var message = 'Must use at least Ember CLI 0.1.2 to use xyz feature'; assert.throws(function() { versionChecker.assertAbove(addon, '0.1.2',message); }, function(err) { return err.suppressStacktrace; }); }); }); });
/*! * @atlassian/aui - Atlassian User Interface Framework * @version v7.6.0 * @link https://docs.atlassian.com/aui/latest/ * @license SEE LICENSE IN LICENSE.md * @author Atlassian Pty Ltd. */ // src/js-vendor/jquery/jquery-ui/jquery.ui.datepicker.js (typeof window === 'undefined' ? global : window).__38fc196a0b1b19c55ba3d238f6ed4f0e = (function () { var module = { exports: {} }; var exports = module.exports; /*! * jQuery UI Datepicker 1.8.24 * * Copyright 2012, AUTHORS.txt (http://jqueryui.com/about) * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license * * http://docs.jquery.com/UI/Datepicker * * Depends: * jquery.ui.core.js */ (function( $, undefined ) { $.extend($.ui, { datepicker: { version: "1.8.24" } }); var PROP_NAME = 'datepicker'; var dpuuid = new Date().getTime(); var instActive; /* Date picker manager. Use the singleton instance of this class, $.datepicker, to interact with the date picker. Settings for (groups of) date pickers are maintained in an instance object, allowing multiple different settings on the same page. */ function Datepicker() { this.debug = false; // Change this to true to start debugging this._curInst = null; // The current instance in use this._keyEvent = false; // If the last event was a key event this._disabledInputs = []; // List of date picker inputs that have been disabled this._datepickerShowing = false; // True if the popup picker is showing , false if not this._inDialog = false; // True if showing within a "dialog", false if not this._mainDivId = 'ui-datepicker-div'; // The ID of the main datepicker division this._inlineClass = 'ui-datepicker-inline'; // The name of the inline marker class this._appendClass = 'ui-datepicker-append'; // The name of the append marker class this._triggerClass = 'ui-datepicker-trigger'; // The name of the trigger marker class this._dialogClass = 'ui-datepicker-dialog'; // The name of the dialog marker class this._disableClass = 'ui-datepicker-disabled'; // The name of the disabled covering marker class this._unselectableClass = 'ui-datepicker-unselectable'; // The name of the unselectable cell marker class this._currentClass = 'ui-datepicker-current-day'; // The name of the current day marker class this._dayOverClass = 'ui-datepicker-days-cell-over'; // The name of the day hover marker class this.regional = []; // Available regional settings, indexed by language code this.regional[''] = { // Default regional settings closeText: 'Done', // Display text for close link prevText: 'Prev', // Display text for previous month link nextText: 'Next', // Display text for next month link currentText: 'Today', // Display text for current month link monthNames: ['January','February','March','April','May','June', 'July','August','September','October','November','December'], // Names of months for drop-down and formatting monthNamesShort: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'], // For formatting dayNames: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'], // For formatting dayNamesShort: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'], // For formatting dayNamesMin: ['Su','Mo','Tu','We','Th','Fr','Sa'], // Column headings for days starting at Sunday weekHeader: 'Wk', // Column header for week of the year dateFormat: 'mm/dd/yy', // See format options on parseDate firstDay: 0, // The first day of the week, Sun = 0, Mon = 1, ... isRTL: false, // True if right-to-left language, false if left-to-right showMonthAfterYear: false, // True if the year select precedes month, false for month then year yearSuffix: '' // Additional text to append to the year in the month headers }; this._defaults = { // Global defaults for all the date picker instances showOn: 'focus', // 'focus' for popup on focus, // 'button' for trigger button, or 'both' for either showAnim: 'fadeIn', // Name of jQuery animation for popup showOptions: {}, // Options for enhanced animations defaultDate: null, // Used when field is blank: actual date, // +/-number for offset from today, null for today appendText: '', // Display text following the input box, e.g. showing the format buttonText: '...', // Text for trigger button buttonImage: '', // URL for trigger button image buttonImageOnly: false, // True if the image appears alone, false if it appears on a button hideIfNoPrevNext: false, // True to hide next/previous month links // if not applicable, false to just disable them navigationAsDateFormat: false, // True if date formatting applied to prev/today/next links gotoCurrent: false, // True if today link goes back to current selection instead changeMonth: false, // True if month can be selected directly, false if only prev/next changeYear: false, // True if year can be selected directly, false if only prev/next yearRange: 'c-10:c+10', // Range of years to display in drop-down, // either relative to today's year (-nn:+nn), relative to currently displayed year // (c-nn:c+nn), absolute (nnnn:nnnn), or a combination of the above (nnnn:-n) showOtherMonths: false, // True to show dates in other months, false to leave blank selectOtherMonths: false, // True to allow selection of dates in other months, false for unselectable showWeek: false, // True to show week of the year, false to not show it calculateWeek: this.iso8601Week, // How to calculate the week of the year, // takes a Date and returns the number of the week for it shortYearCutoff: '+10', // Short year values < this are in the current century, // > this are in the previous century, // string value starting with '+' for current year + value minDate: null, // The earliest selectable date, or null for no limit maxDate: null, // The latest selectable date, or null for no limit duration: 'fast', // Duration of display/closure beforeShowDay: null, // Function that takes a date and returns an array with // [0] = true if selectable, false if not, [1] = custom CSS class name(s) or '', // [2] = cell title (optional), e.g. $.datepicker.noWeekends beforeShow: null, // Function that takes an input field and // returns a set of custom settings for the date picker onSelect: null, // Define a callback function when a date is selected onChangeMonthYear: null, // Define a callback function when the month or year is changed onClose: null, // Define a callback function when the datepicker is closed numberOfMonths: 1, // Number of months to show at a time showCurrentAtPos: 0, // The position in multipe months at which to show the current month (starting at 0) stepMonths: 1, // Number of months to step back/forward stepBigMonths: 12, // Number of months to step back/forward for the big links altField: '', // Selector for an alternate field to store selected dates into altFormat: '', // The date format to use for the alternate field constrainInput: true, // The input is constrained by the current date format showButtonPanel: false, // True to show button panel, false to not show it autoSize: false, // True to size the input for the date format, false to leave as is disabled: false // The initial disabled state }; $.extend(this._defaults, this.regional['']); this.dpDiv = bindHover($('<div id="' + this._mainDivId + '" class="ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all"></div>')); } $.extend(Datepicker.prototype, { /* Class name added to elements to indicate already configured with a date picker. */ markerClassName: 'hasDatepicker', //Keep track of the maximum number of rows displayed (see #7043) maxRows: 4, /* Debug logging (if enabled). */ log: function () { if (this.debug) console.log.apply('', arguments); }, // TODO rename to "widget" when switching to widget factory _widgetDatepicker: function() { return this.dpDiv; }, /* Override the default settings for all instances of the date picker. @param settings object - the new settings to use as defaults (anonymous object) @return the manager object */ setDefaults: function(settings) { extendRemove(this._defaults, settings || {}); return this; }, /* Attach the date picker to a jQuery selection. @param target element - the target input field or division or span @param settings object - the new settings to use for this date picker instance (anonymous) */ _attachDatepicker: function(target, settings) { // check for settings on the control itself - in namespace 'date:' var inlineSettings = null; for (var attrName in this._defaults) { var attrValue = target.getAttribute('date:' + attrName); if (attrValue) { inlineSettings = inlineSettings || {}; try { inlineSettings[attrName] = eval(attrValue); } catch (err) { inlineSettings[attrName] = attrValue; } } } var nodeName = target.nodeName.toLowerCase(); var inline = (nodeName == 'div' || nodeName == 'span'); if (!target.id) { this.uuid += 1; target.id = 'dp' + this.uuid; } var inst = this._newInst($(target), inline); inst.settings = $.extend({}, settings || {}, inlineSettings || {}); if (nodeName == 'input') { this._connectDatepicker(target, inst); } else if (inline) { this._inlineDatepicker(target, inst); } }, /* Create a new instance object. */ _newInst: function(target, inline) { var id = target[0].id.replace(/([^A-Za-z0-9_-])/g, '\\\\$1'); // escape jQuery meta chars return {id: id, input: target, // associated target selectedDay: 0, selectedMonth: 0, selectedYear: 0, // current selection drawMonth: 0, drawYear: 0, // month being drawn inline: inline, // is datepicker inline or not dpDiv: (!inline ? this.dpDiv : // presentation div bindHover($('<div class="' + this._inlineClass + ' ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all"></div>')))}; }, /* Attach the date picker to an input field. */ _connectDatepicker: function(target, inst) { var input = $(target); inst.append = $([]); inst.trigger = $([]); if (input.hasClass(this.markerClassName)) return; this._attachments(input, inst); input.addClass(this.markerClassName).keydown(this._doKeyDown). keypress(this._doKeyPress).keyup(this._doKeyUp). bind("setData.datepicker", function(event, key, value) { inst.settings[key] = value; }).bind("getData.datepicker", function(event, key) { return this._get(inst, key); }); this._autoSize(inst); $.data(target, PROP_NAME, inst); //If disabled option is true, disable the datepicker once it has been attached to the input (see ticket #5665) if( inst.settings.disabled ) { this._disableDatepicker( target ); } }, /* Make attachments based on settings. */ _attachments: function(input, inst) { var appendText = this._get(inst, 'appendText'); var isRTL = this._get(inst, 'isRTL'); if (inst.append) inst.append.remove(); if (appendText) { inst.append = $('<span class="' + this._appendClass + '">' + appendText + '</span>'); input[isRTL ? 'before' : 'after'](inst.append); } input.unbind('focus', this._showDatepicker); if (inst.trigger) inst.trigger.remove(); var showOn = this._get(inst, 'showOn'); if (showOn == 'focus' || showOn == 'both') // pop-up date picker when in the marked field input.focus(this._showDatepicker); if (showOn == 'button' || showOn == 'both') { // pop-up date picker when button clicked var buttonText = this._get(inst, 'buttonText'); var buttonImage = this._get(inst, 'buttonImage'); inst.trigger = $(this._get(inst, 'buttonImageOnly') ? $('<img/>').addClass(this._triggerClass). attr({ src: buttonImage, alt: buttonText, title: buttonText }) : $('<button type="button"></button>').addClass(this._triggerClass). html(buttonImage == '' ? buttonText : $('<img/>').attr( { src:buttonImage, alt:buttonText, title:buttonText }))); input[isRTL ? 'before' : 'after'](inst.trigger); inst.trigger.click(function() { if ($.datepicker._datepickerShowing && $.datepicker._lastInput == input[0]) $.datepicker._hideDatepicker(); else if ($.datepicker._datepickerShowing && $.datepicker._lastInput != input[0]) { $.datepicker._hideDatepicker(); $.datepicker._showDatepicker(input[0]); } else $.datepicker._showDatepicker(input[0]); return false; }); } }, /* Apply the maximum length for the date format. */ _autoSize: function(inst) { if (this._get(inst, 'autoSize') && !inst.inline) { var date = new Date(2009, 12 - 1, 20); // Ensure double digits var dateFormat = this._get(inst, 'dateFormat'); if (dateFormat.match(/[DM]/)) { var findMax = function(names) { var max = 0; var maxI = 0; for (var i = 0; i < names.length; i++) { if (names[i].length > max) { max = names[i].length; maxI = i; } } return maxI; }; date.setMonth(findMax(this._get(inst, (dateFormat.match(/MM/) ? 'monthNames' : 'monthNamesShort')))); date.setDate(findMax(this._get(inst, (dateFormat.match(/DD/) ? 'dayNames' : 'dayNamesShort'))) + 20 - date.getDay()); } inst.input.attr('size', this._formatDate(inst, date).length); } }, /* Attach an inline date picker to a div. */ _inlineDatepicker: function(target, inst) { var divSpan = $(target); if (divSpan.hasClass(this.markerClassName)) return; divSpan.addClass(this.markerClassName).append(inst.dpDiv). bind("setData.datepicker", function(event, key, value){ inst.settings[key] = value; }).bind("getData.datepicker", function(event, key){ return this._get(inst, key); }); $.data(target, PROP_NAME, inst); this._setDate(inst, this._getDefaultDate(inst), true); this._updateDatepicker(inst); this._updateAlternate(inst); //If disabled option is true, disable the datepicker before showing it (see ticket #5665) if( inst.settings.disabled ) { this._disableDatepicker( target ); } // Set display:block in place of inst.dpDiv.show() which won't work on disconnected elements // http://bugs.jqueryui.com/ticket/7552 - A Datepicker created on a detached div has zero height inst.dpDiv.css( "display", "block" ); }, /* Pop-up the date picker in a "dialog" box. @param input element - ignored @param date string or Date - the initial date to display @param onSelect function - the function to call when a date is selected @param settings object - update the dialog date picker instance's settings (anonymous object) @param pos int[2] - coordinates for the dialog's position within the screen or event - with x/y coordinates or leave empty for default (screen centre) @return the manager object */ _dialogDatepicker: function(input, date, onSelect, settings, pos) { var inst = this._dialogInst; // internal instance if (!inst) { this.uuid += 1; var id = 'dp' + this.uuid; this._dialogInput = $('<input type="text" id="' + id + '" style="position: absolute; top: -100px; width: 0px;"/>'); this._dialogInput.keydown(this._doKeyDown); $('body').append(this._dialogInput); inst = this._dialogInst = this._newInst(this._dialogInput, false); inst.settings = {}; $.data(this._dialogInput[0], PROP_NAME, inst); } extendRemove(inst.settings, settings || {}); date = (date && date.constructor == Date ? this._formatDate(inst, date) : date); this._dialogInput.val(date); this._pos = (pos ? (pos.length ? pos : [pos.pageX, pos.pageY]) : null); if (!this._pos) { var browserWidth = document.documentElement.clientWidth; var browserHeight = document.documentElement.clientHeight; var scrollX = document.documentElement.scrollLeft || document.body.scrollLeft; var scrollY = document.documentElement.scrollTop || document.body.scrollTop; this._pos = // should use actual width/height below [(browserWidth / 2) - 100 + scrollX, (browserHeight / 2) - 150 + scrollY]; } // move input on screen for focus, but hidden behind dialog this._dialogInput.css('left', (this._pos[0] + 20) + 'px').css('top', this._pos[1] + 'px'); inst.settings.onSelect = onSelect; this._inDialog = true; this.dpDiv.addClass(this._dialogClass); this._showDatepicker(this._dialogInput[0]); if ($.blockUI) $.blockUI(this.dpDiv); $.data(this._dialogInput[0], PROP_NAME, inst); return this; }, /* Detach a datepicker from its control. @param target element - the target input field or division or span */ _destroyDatepicker: function(target) { var $target = $(target); var inst = $.data(target, PROP_NAME); if (!$target.hasClass(this.markerClassName)) { return; } var nodeName = target.nodeName.toLowerCase(); $.removeData(target, PROP_NAME); if (nodeName == 'input') { inst.append.remove(); inst.trigger.remove(); $target.removeClass(this.markerClassName). unbind('focus', this._showDatepicker). unbind('keydown', this._doKeyDown). unbind('keypress', this._doKeyPress). unbind('keyup', this._doKeyUp); } else if (nodeName == 'div' || nodeName == 'span') $target.removeClass(this.markerClassName).empty(); }, /* Enable the date picker to a jQuery selection. @param target element - the target input field or division or span */ _enableDatepicker: function(target) { var $target = $(target); var inst = $.data(target, PROP_NAME); if (!$target.hasClass(this.markerClassName)) { return; } var nodeName = target.nodeName.toLowerCase(); if (nodeName == 'input') { target.disabled = false; inst.trigger.filter('button'). each(function() { this.disabled = false; }).end(). filter('img').css({opacity: '1.0', cursor: ''}); } else if (nodeName == 'div' || nodeName == 'span') { var inline = $target.children('.' + this._inlineClass); inline.children().removeClass('ui-state-disabled'); inline.find("select.ui-datepicker-month, select.ui-datepicker-year"). removeAttr("disabled"); } this._disabledInputs = $.map(this._disabledInputs, function(value) { return (value == target ? null : value); }); // delete entry }, /* Disable the date picker to a jQuery selection. @param target element - the target input field or division or span */ _disableDatepicker: function(target) { var $target = $(target); var inst = $.data(target, PROP_NAME); if (!$target.hasClass(this.markerClassName)) { return; } var nodeName = target.nodeName.toLowerCase(); if (nodeName == 'input') { target.disabled = true; inst.trigger.filter('button'). each(function() { this.disabled = true; }).end(). filter('img').css({opacity: '0.5', cursor: 'default'}); } else if (nodeName == 'div' || nodeName == 'span') { var inline = $target.children('.' + this._inlineClass); inline.children().addClass('ui-state-disabled'); inline.find("select.ui-datepicker-month, select.ui-datepicker-year"). attr("disabled", "disabled"); } this._disabledInputs = $.map(this._disabledInputs, function(value) { return (value == target ? null : value); }); // delete entry this._disabledInputs[this._disabledInputs.length] = target; }, /* Is the first field in a jQuery collection disabled as a datepicker? @param target element - the target input field or division or span @return boolean - true if disabled, false if enabled */ _isDisabledDatepicker: function(target) { if (!target) { return false; } for (var i = 0; i < this._disabledInputs.length; i++) { if (this._disabledInputs[i] == target) return true; } return false; }, /* Retrieve the instance data for the target control. @param target element - the target input field or division or span @return object - the associated instance data @throws error if a jQuery problem getting data */ _getInst: function(target) { try { return $.data(target, PROP_NAME); } catch (err) { throw 'Missing instance data for this datepicker'; } }, /* Update or retrieve the settings for a date picker attached to an input field or division. @param target element - the target input field or division or span @param name object - the new settings to update or string - the name of the setting to change or retrieve, when retrieving also 'all' for all instance settings or 'defaults' for all global defaults @param value any - the new value for the setting (omit if above is an object or to retrieve a value) */ _optionDatepicker: function(target, name, value) { var inst = this._getInst(target); if (arguments.length == 2 && typeof name == 'string') { return (name == 'defaults' ? $.extend({}, $.datepicker._defaults) : (inst ? (name == 'all' ? $.extend({}, inst.settings) : this._get(inst, name)) : null)); } var settings = name || {}; if (typeof name == 'string') { settings = {}; settings[name] = value; } if (inst) { if (this._curInst == inst) { this._hideDatepicker(); } var date = this._getDateDatepicker(target, true); var minDate = this._getMinMaxDate(inst, 'min'); var maxDate = this._getMinMaxDate(inst, 'max'); extendRemove(inst.settings, settings); // reformat the old minDate/maxDate values if dateFormat changes and a new minDate/maxDate isn't provided if (minDate !== null && settings['dateFormat'] !== undefined && settings['minDate'] === undefined) inst.settings.minDate = this._formatDate(inst, minDate); if (maxDate !== null && settings['dateFormat'] !== undefined && settings['maxDate'] === undefined) inst.settings.maxDate = this._formatDate(inst, maxDate); this._attachments($(target), inst); this._autoSize(inst); this._setDate(inst, date); this._updateAlternate(inst); this._updateDatepicker(inst); } }, // change method deprecated _changeDatepicker: function(target, name, value) { this._optionDatepicker(target, name, value); }, /* Redraw the date picker attached to an input field or division. @param target element - the target input field or division or span */ _refreshDatepicker: function(target) { var inst = this._getInst(target); if (inst) { this._updateDatepicker(inst); } }, /* Set the dates for a jQuery selection. @param target element - the target input field or division or span @param date Date - the new date */ _setDateDatepicker: function(target, date) { var inst = this._getInst(target); if (inst) { this._setDate(inst, date); this._updateDatepicker(inst); this._updateAlternate(inst); } }, /* Get the date(s) for the first entry in a jQuery selection. @param target element - the target input field or division or span @param noDefault boolean - true if no default date is to be used @return Date - the current date */ _getDateDatepicker: function(target, noDefault) { var inst = this._getInst(target); if (inst && !inst.inline) this._setDateFromField(inst, noDefault); return (inst ? this._getDate(inst) : null); }, /* Handle keystrokes. */ _doKeyDown: function(event) { var inst = $.datepicker._getInst(event.target); var handled = true; var isRTL = inst.dpDiv.is('.ui-datepicker-rtl'); inst._keyEvent = true; if ($.datepicker._datepickerShowing) switch (event.keyCode) { case 9: $.datepicker._hideDatepicker(); handled = false; break; // hide on tab out case 13: var sel = $('td.' + $.datepicker._dayOverClass + ':not(.' + $.datepicker._currentClass + ')', inst.dpDiv); if (sel[0]) $.datepicker._selectDay(event.target, inst.selectedMonth, inst.selectedYear, sel[0]); var onSelect = $.datepicker._get(inst, 'onSelect'); if (onSelect) { var dateStr = $.datepicker._formatDate(inst); // trigger custom callback onSelect.apply((inst.input ? inst.input[0] : null), [dateStr, inst]); } else $.datepicker._hideDatepicker(); return false; // don't submit the form break; // select the value on enter case 27: $.datepicker._hideDatepicker(); break; // hide on escape case 33: $.datepicker._adjustDate(event.target, (event.ctrlKey ? -$.datepicker._get(inst, 'stepBigMonths') : -$.datepicker._get(inst, 'stepMonths')), 'M'); break; // previous month/year on page up/+ ctrl case 34: $.datepicker._adjustDate(event.target, (event.ctrlKey ? +$.datepicker._get(inst, 'stepBigMonths') : +$.datepicker._get(inst, 'stepMonths')), 'M'); break; // next month/year on page down/+ ctrl case 35: if (event.ctrlKey || event.metaKey) $.datepicker._clearDate(event.target); handled = event.ctrlKey || event.metaKey; break; // clear on ctrl or command +end case 36: if (event.ctrlKey || event.metaKey) $.datepicker._gotoToday(event.target); handled = event.ctrlKey || event.metaKey; break; // current on ctrl or command +home case 37: if (event.ctrlKey || event.metaKey) $.datepicker._adjustDate(event.target, (isRTL ? +1 : -1), 'D'); handled = event.ctrlKey || event.metaKey; // -1 day on ctrl or command +left if (event.originalEvent.altKey) $.datepicker._adjustDate(event.target, (event.ctrlKey ? -$.datepicker._get(inst, 'stepBigMonths') : -$.datepicker._get(inst, 'stepMonths')), 'M'); // next month/year on alt +left on Mac break; case 38: if (event.ctrlKey || event.metaKey) $.datepicker._adjustDate(event.target, -7, 'D'); handled = event.ctrlKey || event.metaKey; break; // -1 week on ctrl or command +up case 39: if (event.ctrlKey || event.metaKey) $.datepicker._adjustDate(event.target, (isRTL ? -1 : +1), 'D'); handled = event.ctrlKey || event.metaKey; // +1 day on ctrl or command +right if (event.originalEvent.altKey) $.datepicker._adjustDate(event.target, (event.ctrlKey ? +$.datepicker._get(inst, 'stepBigMonths') : +$.datepicker._get(inst, 'stepMonths')), 'M'); // next month/year on alt +right break; case 40: if (event.ctrlKey || event.metaKey) $.datepicker._adjustDate(event.target, +7, 'D'); handled = event.ctrlKey || event.metaKey; break; // +1 week on ctrl or command +down default: handled = false; } else if (event.keyCode == 36 && event.ctrlKey) // display the date picker on ctrl+home $.datepicker._showDatepicker(this); else { handled = false; } if (handled) { event.preventDefault(); event.stopPropagation(); } }, /* Filter entered characters - based on date format. */ _doKeyPress: function(event) { var inst = $.datepicker._getInst(event.target); if ($.datepicker._get(inst, 'constrainInput')) { var chars = $.datepicker._possibleChars($.datepicker._get(inst, 'dateFormat')); var chr = String.fromCharCode(event.charCode == undefined ? event.keyCode : event.charCode); return event.ctrlKey || event.metaKey || (chr < ' ' || !chars || chars.indexOf(chr) > -1); } }, /* Synchronise manual entry and field/alternate field. */ _doKeyUp: function(event) { var inst = $.datepicker._getInst(event.target); if (inst.input.val() != inst.lastVal) { try { var date = $.datepicker.parseDate($.datepicker._get(inst, 'dateFormat'), (inst.input ? inst.input.val() : null), $.datepicker._getFormatConfig(inst)); if (date) { // only if valid $.datepicker._setDateFromField(inst); $.datepicker._updateAlternate(inst); $.datepicker._updateDatepicker(inst); } } catch (err) { $.datepicker.log(err); } } return true; }, /* Pop-up the date picker for a given input field. If false returned from beforeShow event handler do not show. @param input element - the input field attached to the date picker or event - if triggered by focus */ _showDatepicker: function(input) { input = input.target || input; if (input.nodeName.toLowerCase() != 'input') // find from button/image trigger input = $('input', input.parentNode)[0]; if ($.datepicker._isDisabledDatepicker(input) || $.datepicker._lastInput == input) // already here return; var inst = $.datepicker._getInst(input); if ($.datepicker._curInst && $.datepicker._curInst != inst) { $.datepicker._curInst.dpDiv.stop(true, true); if ( inst && $.datepicker._datepickerShowing ) { $.datepicker._hideDatepicker( $.datepicker._curInst.input[0] ); } } var beforeShow = $.datepicker._get(inst, 'beforeShow'); var beforeShowSettings = beforeShow ? beforeShow.apply(input, [input, inst]) : {}; if(beforeShowSettings === false){ //false return; } extendRemove(inst.settings, beforeShowSettings); inst.lastVal = null; $.datepicker._lastInput = input; $.datepicker._setDateFromField(inst); if ($.datepicker._inDialog) // hide cursor input.value = ''; if (!$.datepicker._pos) { // position below input $.datepicker._pos = $.datepicker._findPos(input); $.datepicker._pos[1] += input.offsetHeight; // add the height } var isFixed = false; $(input).parents().each(function() { isFixed |= $(this).css('position') == 'fixed'; return !isFixed; }); if (isFixed && $.browser.opera) { // correction for Opera when fixed and scrolled $.datepicker._pos[0] -= document.documentElement.scrollLeft; $.datepicker._pos[1] -= document.documentElement.scrollTop; } var offset = {left: $.datepicker._pos[0], top: $.datepicker._pos[1]}; $.datepicker._pos = null; //to avoid flashes on Firefox inst.dpDiv.empty(); // determine sizing offscreen inst.dpDiv.css({position: 'absolute', display: 'block', top: '-1000px'}); $.datepicker._updateDatepicker(inst); // fix width for dynamic number of date pickers // and adjust position before showing offset = $.datepicker._checkOffset(inst, offset, isFixed); inst.dpDiv.css({position: ($.datepicker._inDialog && $.blockUI ? 'static' : (isFixed ? 'fixed' : 'absolute')), display: 'none', left: offset.left + 'px', top: offset.top + 'px'}); if (!inst.inline) { var showAnim = $.datepicker._get(inst, 'showAnim'); var duration = $.datepicker._get(inst, 'duration'); var postProcess = function() { var cover = inst.dpDiv.find('iframe.ui-datepicker-cover'); // IE6- only if( !! cover.length ){ var borders = $.datepicker._getBorders(inst.dpDiv); cover.css({left: -borders[0], top: -borders[1], width: inst.dpDiv.outerWidth(), height: inst.dpDiv.outerHeight()}); } }; inst.dpDiv.zIndex($(input).zIndex()+1); $.datepicker._datepickerShowing = true; if ($.effects && $.effects[showAnim]) inst.dpDiv.show(showAnim, $.datepicker._get(inst, 'showOptions'), duration, postProcess); else inst.dpDiv[showAnim || 'show']((showAnim ? duration : null), postProcess); if (!showAnim || !duration) postProcess(); if (inst.input.is(':visible') && !inst.input.is(':disabled')) inst.input.focus(); $.datepicker._curInst = inst; } }, /* Generate the date picker content. */ _updateDatepicker: function(inst) { var self = this; self.maxRows = 4; //Reset the max number of rows being displayed (see #7043) var borders = $.datepicker._getBorders(inst.dpDiv); instActive = inst; // for delegate hover events inst.dpDiv.empty().append(this._generateHTML(inst)); this._attachHandlers(inst); var cover = inst.dpDiv.find('iframe.ui-datepicker-cover'); // IE6- only if( !!cover.length ){ //avoid call to outerXXXX() when not in IE6 cover.css({left: -borders[0], top: -borders[1], width: inst.dpDiv.outerWidth(), height: inst.dpDiv.outerHeight()}) } inst.dpDiv.find('.' + this._dayOverClass + ' a').mouseover(); var numMonths = this._getNumberOfMonths(inst); var cols = numMonths[1]; var width = 17; inst.dpDiv.removeClass('ui-datepicker-multi-2 ui-datepicker-multi-3 ui-datepicker-multi-4').width(''); if (cols > 1) inst.dpDiv.addClass('ui-datepicker-multi-' + cols).css('width', (width * cols) + 'em'); inst.dpDiv[(numMonths[0] != 1 || numMonths[1] != 1 ? 'add' : 'remove') + 'Class']('ui-datepicker-multi'); inst.dpDiv[(this._get(inst, 'isRTL') ? 'add' : 'remove') + 'Class']('ui-datepicker-rtl'); if (inst == $.datepicker._curInst && $.datepicker._datepickerShowing && inst.input && // #6694 - don't focus the input if it's already focused // this breaks the change event in IE inst.input.is(':visible') && !inst.input.is(':disabled') && inst.input[0] != document.activeElement) inst.input.focus(); // deffered render of the years select (to avoid flashes on Firefox) if( inst.yearshtml ){ var origyearshtml = inst.yearshtml; setTimeout(function(){ //assure that inst.yearshtml didn't change. if( origyearshtml === inst.yearshtml && inst.yearshtml ){ inst.dpDiv.find('select.ui-datepicker-year:first').replaceWith(inst.yearshtml); } origyearshtml = inst.yearshtml = null; }, 0); } }, /* Retrieve the size of left and top borders for an element. @param elem (jQuery object) the element of interest @return (number[2]) the left and top borders */ _getBorders: function(elem) { var convert = function(value) { return {thin: 1, medium: 2, thick: 3}[value] || value; }; return [parseFloat(convert(elem.css('border-left-width'))), parseFloat(convert(elem.css('border-top-width')))]; }, /* Check positioning to remain on screen. */ _checkOffset: function(inst, offset, isFixed) { var dpWidth = inst.dpDiv.outerWidth(); var dpHeight = inst.dpDiv.outerHeight(); var inputWidth = inst.input ? inst.input.outerWidth() : 0; var inputHeight = inst.input ? inst.input.outerHeight() : 0; var viewWidth = document.documentElement.clientWidth + (isFixed ? 0 : $(document).scrollLeft()); var viewHeight = document.documentElement.clientHeight + (isFixed ? 0 : $(document).scrollTop()); offset.left -= (this._get(inst, 'isRTL') ? (dpWidth - inputWidth) : 0); offset.left -= (isFixed && offset.left == inst.input.offset().left) ? $(document).scrollLeft() : 0; offset.top -= (isFixed && offset.top == (inst.input.offset().top + inputHeight)) ? $(document).scrollTop() : 0; // now check if datepicker is showing outside window viewport - move to a better place if so. offset.left -= Math.min(offset.left, (offset.left + dpWidth > viewWidth && viewWidth > dpWidth) ? Math.abs(offset.left + dpWidth - viewWidth) : 0); offset.top -= Math.min(offset.top, (offset.top + dpHeight > viewHeight && viewHeight > dpHeight) ? Math.abs(dpHeight + inputHeight) : 0); return offset; }, /* Find an object's position on the screen. */ _findPos: function(obj) { var inst = this._getInst(obj); var isRTL = this._get(inst, 'isRTL'); while (obj && (obj.type == 'hidden' || obj.nodeType != 1 || $.expr.filters.hidden(obj))) { obj = obj[isRTL ? 'previousSibling' : 'nextSibling']; } var position = $(obj).offset(); return [position.left, position.top]; }, /* Hide the date picker from view. @param input element - the input field attached to the date picker */ _hideDatepicker: function(input) { var inst = this._curInst; if (!inst || (input && inst != $.data(input, PROP_NAME))) return; if (this._datepickerShowing) { var showAnim = this._get(inst, 'showAnim'); var duration = this._get(inst, 'duration'); var postProcess = function() { $.datepicker._tidyDialog(inst); }; if ($.effects && $.effects[showAnim]) inst.dpDiv.hide(showAnim, $.datepicker._get(inst, 'showOptions'), duration, postProcess); else inst.dpDiv[(showAnim == 'slideDown' ? 'slideUp' : (showAnim == 'fadeIn' ? 'fadeOut' : 'hide'))]((showAnim ? duration : null), postProcess); if (!showAnim) postProcess(); this._datepickerShowing = false; var onClose = this._get(inst, 'onClose'); if (onClose) onClose.apply((inst.input ? inst.input[0] : null), [(inst.input ? inst.input.val() : ''), inst]); this._lastInput = null; if (this._inDialog) { this._dialogInput.css({ position: 'absolute', left: '0', top: '-100px' }); if ($.blockUI) { $.unblockUI(); $('body').append(this.dpDiv); } } this._inDialog = false; } }, /* Tidy up after a dialog display. */ _tidyDialog: function(inst) { inst.dpDiv.removeClass(this._dialogClass).unbind('.ui-datepicker-calendar'); }, /* Close date picker if clicked elsewhere. */ _checkExternalClick: function(event) { if (!$.datepicker._curInst) return; var $target = $(event.target), inst = $.datepicker._getInst($target[0]); if ( ( ( $target[0].id != $.datepicker._mainDivId && $target.parents('#' + $.datepicker._mainDivId).length == 0 && !$target.hasClass($.datepicker.markerClassName) && !$target.closest("." + $.datepicker._triggerClass).length && $.datepicker._datepickerShowing && !($.datepicker._inDialog && $.blockUI) ) ) || ( $target.hasClass($.datepicker.markerClassName) && $.datepicker._curInst != inst ) ) $.datepicker._hideDatepicker(); }, /* Adjust one of the date sub-fields. */ _adjustDate: function(id, offset, period) { var target = $(id); var inst = this._getInst(target[0]); if (this._isDisabledDatepicker(target[0])) { return; } this._adjustInstDate(inst, offset + (period == 'M' ? this._get(inst, 'showCurrentAtPos') : 0), // undo positioning period); this._updateDatepicker(inst); }, /* Action for current link. */ _gotoToday: function(id) { var target = $(id); var inst = this._getInst(target[0]); if (this._get(inst, 'gotoCurrent') && inst.currentDay) { inst.selectedDay = inst.currentDay; inst.drawMonth = inst.selectedMonth = inst.currentMonth; inst.drawYear = inst.selectedYear = inst.currentYear; } else { var date = new Date(); inst.selectedDay = date.getDate(); inst.drawMonth = inst.selectedMonth = date.getMonth(); inst.drawYear = inst.selectedYear = date.getFullYear(); } this._notifyChange(inst); this._adjustDate(target); }, /* Action for selecting a new month/year. */ _selectMonthYear: function(id, select, period) { var target = $(id); var inst = this._getInst(target[0]); inst['selected' + (period == 'M' ? 'Month' : 'Year')] = inst['draw' + (period == 'M' ? 'Month' : 'Year')] = parseInt(select.options[select.selectedIndex].value,10); this._notifyChange(inst); this._adjustDate(target); }, /* Action for selecting a day. */ _selectDay: function(id, month, year, td) { var target = $(id); if ($(td).hasClass(this._unselectableClass) || this._isDisabledDatepicker(target[0])) { return; } var inst = this._getInst(target[0]); inst.selectedDay = inst.currentDay = $('a', td).html(); inst.selectedMonth = inst.currentMonth = month; inst.selectedYear = inst.currentYear = year; this._selectDate(id, this._formatDate(inst, inst.currentDay, inst.currentMonth, inst.currentYear)); }, /* Erase the input field and hide the date picker. */ _clearDate: function(id) { var target = $(id); var inst = this._getInst(target[0]); this._selectDate(target, ''); }, /* Update the input field with the selected date. */ _selectDate: function(id, dateStr) { var target = $(id); var inst = this._getInst(target[0]); dateStr = (dateStr != null ? dateStr : this._formatDate(inst)); if (inst.input) inst.input.val(dateStr); this._updateAlternate(inst); var onSelect = this._get(inst, 'onSelect'); if (onSelect) onSelect.apply((inst.input ? inst.input[0] : null), [dateStr, inst]); // trigger custom callback else if (inst.input) inst.input.trigger('change'); // fire the change event if (inst.inline) this._updateDatepicker(inst); else { this._hideDatepicker(); this._lastInput = inst.input[0]; if (typeof(inst.input[0]) != 'object') inst.input.focus(); // restore focus this._lastInput = null; } }, /* Update any alternate field to synchronise with the main field. */ _updateAlternate: function(inst) { var altField = this._get(inst, 'altField'); if (altField) { // update alternate field too var altFormat = this._get(inst, 'altFormat') || this._get(inst, 'dateFormat'); var date = this._getDate(inst); var dateStr = this.formatDate(altFormat, date, this._getFormatConfig(inst)); $(altField).each(function() { $(this).val(dateStr); }); } }, /* Set as beforeShowDay function to prevent selection of weekends. @param date Date - the date to customise @return [boolean, string] - is this date selectable?, what is its CSS class? */ noWeekends: function(date) { var day = date.getDay(); return [(day > 0 && day < 6), '']; }, /* Set as calculateWeek to determine the week of the year based on the ISO 8601 definition. @param date Date - the date to get the week for @return number - the number of the week within the year that contains this date */ iso8601Week: function(date) { var checkDate = new Date(date.getTime()); // Find Thursday of this week starting on Monday checkDate.setDate(checkDate.getDate() + 4 - (checkDate.getDay() || 7)); var time = checkDate.getTime(); checkDate.setMonth(0); // Compare with Jan 1 checkDate.setDate(1); return Math.floor(Math.round((time - checkDate) / 86400000) / 7) + 1; }, /* Parse a string value into a date object. See formatDate below for the possible formats. @param format string - the expected format of the date @param value string - the date in the above format @param settings Object - attributes include: shortYearCutoff number - the cutoff year for determining the century (optional) dayNamesShort string[7] - abbreviated names of the days from Sunday (optional) dayNames string[7] - names of the days from Sunday (optional) monthNamesShort string[12] - abbreviated names of the months (optional) monthNames string[12] - names of the months (optional) @return Date - the extracted date value or null if value is blank */ parseDate: function (format, value, settings) { if (format == null || value == null) throw 'Invalid arguments'; value = (typeof value == 'object' ? value.toString() : value + ''); if (value == '') return null; var shortYearCutoff = (settings ? settings.shortYearCutoff : null) || this._defaults.shortYearCutoff; shortYearCutoff = (typeof shortYearCutoff != 'string' ? shortYearCutoff : new Date().getFullYear() % 100 + parseInt(shortYearCutoff, 10)); var dayNamesShort = (settings ? settings.dayNamesShort : null) || this._defaults.dayNamesShort; var dayNames = (settings ? settings.dayNames : null) || this._defaults.dayNames; var monthNamesShort = (settings ? settings.monthNamesShort : null) || this._defaults.monthNamesShort; var monthNames = (settings ? settings.monthNames : null) || this._defaults.monthNames; var year = -1; var month = -1; var day = -1; var doy = -1; var literal = false; // Check whether a format character is doubled var lookAhead = function(match) { var matches = (iFormat + 1 < format.length && format.charAt(iFormat + 1) == match); if (matches) iFormat++; return matches; }; // Extract a number from the string value var getNumber = function(match) { var isDoubled = lookAhead(match); var size = (match == '@' ? 14 : (match == '!' ? 20 : (match == 'y' && isDoubled ? 4 : (match == 'o' ? 3 : 2)))); var digits = new RegExp('^\\d{1,' + size + '}'); var num = value.substring(iValue).match(digits); if (!num) throw 'Missing number at position ' + iValue; iValue += num[0].length; return parseInt(num[0], 10); }; // Extract a name from the string value and convert to an index var getName = function(match, shortNames, longNames) { var names = $.map(lookAhead(match) ? longNames : shortNames, function (v, k) { return [ [k, v] ]; }).sort(function (a, b) { return -(a[1].length - b[1].length); }); var index = -1; $.each(names, function (i, pair) { var name = pair[1]; if (value.substr(iValue, name.length).toLowerCase() == name.toLowerCase()) { index = pair[0]; iValue += name.length; return false; } }); if (index != -1) return index + 1; else throw 'Unknown name at position ' + iValue; }; // Confirm that a literal character matches the string value var checkLiteral = function() { if (value.charAt(iValue) != format.charAt(iFormat)) throw 'Unexpected literal at position ' + iValue; iValue++; }; var iValue = 0; for (var iFormat = 0; iFormat < format.length; iFormat++) { if (literal) if (format.charAt(iFormat) == "'" && !lookAhead("'")) literal = false; else checkLiteral(); else switch (format.charAt(iFormat)) { case 'd': day = getNumber('d'); break; case 'D': getName('D', dayNamesShort, dayNames); break; case 'o': doy = getNumber('o'); break; case 'm': month = getNumber('m'); break; case 'M': month = getName('M', monthNamesShort, monthNames); break; case 'y': year = getNumber('y'); break; case '@': var date = new Date(getNumber('@')); year = date.getFullYear(); month = date.getMonth() + 1; day = date.getDate(); break; case '!': var date = new Date((getNumber('!') - this._ticksTo1970) / 10000); year = date.getFullYear(); month = date.getMonth() + 1; day = date.getDate(); break; case "'": if (lookAhead("'")) checkLiteral(); else literal = true; break; default: checkLiteral(); } } if (iValue < value.length){ throw "Extra/unparsed characters found in date: " + value.substring(iValue); } if (year == -1) year = new Date().getFullYear(); else if (year < 100) year += new Date().getFullYear() - new Date().getFullYear() % 100 + (year <= shortYearCutoff ? 0 : -100); if (doy > -1) { month = 1; day = doy; do { var dim = this._getDaysInMonth(year, month - 1); if (day <= dim) break; month++; day -= dim; } while (true); } var date = this._daylightSavingAdjust(new Date(year, month - 1, day)); if (date.getFullYear() != year || date.getMonth() + 1 != month || date.getDate() != day) throw 'Invalid date'; // E.g. 31/02/00 return date; }, /* Standard date formats. */ ATOM: 'yy-mm-dd', // RFC 3339 (ISO 8601) COOKIE: 'D, dd M yy', ISO_8601: 'yy-mm-dd', RFC_822: 'D, d M y', RFC_850: 'DD, dd-M-y', RFC_1036: 'D, d M y', RFC_1123: 'D, d M yy', RFC_2822: 'D, d M yy', RSS: 'D, d M y', // RFC 822 TICKS: '!', TIMESTAMP: '@', W3C: 'yy-mm-dd', // ISO 8601 _ticksTo1970: (((1970 - 1) * 365 + Math.floor(1970 / 4) - Math.floor(1970 / 100) + Math.floor(1970 / 400)) * 24 * 60 * 60 * 10000000), /* Format a date object into a string value. The format can be combinations of the following: d - day of month (no leading zero) dd - day of month (two digit) o - day of year (no leading zeros) oo - day of year (three digit) D - day name short DD - day name long m - month of year (no leading zero) mm - month of year (two digit) M - month name short MM - month name long y - year (two digit) yy - year (four digit) @ - Unix timestamp (ms since 01/01/1970) ! - Windows ticks (100ns since 01/01/0001) '...' - literal text '' - single quote @param format string - the desired format of the date @param date Date - the date value to format @param settings Object - attributes include: dayNamesShort string[7] - abbreviated names of the days from Sunday (optional) dayNames string[7] - names of the days from Sunday (optional) monthNamesShort string[12] - abbreviated names of the months (optional) monthNames string[12] - names of the months (optional) @return string - the date in the above format */ formatDate: function (format, date, settings) { if (!date) return ''; var dayNamesShort = (settings ? settings.dayNamesShort : null) || this._defaults.dayNamesShort; var dayNames = (settings ? settings.dayNames : null) || this._defaults.dayNames; var monthNamesShort = (settings ? settings.monthNamesShort : null) || this._defaults.monthNamesShort; var monthNames = (settings ? settings.monthNames : null) || this._defaults.monthNames; // Check whether a format character is doubled var lookAhead = function(match) { var matches = (iFormat + 1 < format.length && format.charAt(iFormat + 1) == match); if (matches) iFormat++; return matches; }; // Format a number, with leading zero if necessary var formatNumber = function(match, value, len) { var num = '' + value; if (lookAhead(match)) while (num.length < len) num = '0' + num; return num; }; // Format a name, short or long as requested var formatName = function(match, value, shortNames, longNames) { return (lookAhead(match) ? longNames[value] : shortNames[value]); }; var output = ''; var literal = false; if (date) for (var iFormat = 0; iFormat < format.length; iFormat++) { if (literal) if (format.charAt(iFormat) == "'" && !lookAhead("'")) literal = false; else output += format.charAt(iFormat); else switch (format.charAt(iFormat)) { case 'd': output += formatNumber('d', date.getDate(), 2); break; case 'D': output += formatName('D', date.getDay(), dayNamesShort, dayNames); break; case 'o': output += formatNumber('o', Math.round((new Date(date.getFullYear(), date.getMonth(), date.getDate()).getTime() - new Date(date.getFullYear(), 0, 0).getTime()) / 86400000), 3); break; case 'm': output += formatNumber('m', date.getMonth() + 1, 2); break; case 'M': output += formatName('M', date.getMonth(), monthNamesShort, monthNames); break; case 'y': output += (lookAhead('y') ? date.getFullYear() : (date.getYear() % 100 < 10 ? '0' : '') + date.getYear() % 100); break; case '@': output += date.getTime(); break; case '!': output += date.getTime() * 10000 + this._ticksTo1970; break; case "'": if (lookAhead("'")) output += "'"; else literal = true; break; default: output += format.charAt(iFormat); } } return output; }, /* Extract all possible characters from the date format. */ _possibleChars: function (format) { var chars = ''; var literal = false; // Check whether a format character is doubled var lookAhead = function(match) { var matches = (iFormat + 1 < format.length && format.charAt(iFormat + 1) == match); if (matches) iFormat++; return matches; }; for (var iFormat = 0; iFormat < format.length; iFormat++) if (literal) if (format.charAt(iFormat) == "'" && !lookAhead("'")) literal = false; else chars += format.charAt(iFormat); else switch (format.charAt(iFormat)) { case 'd': case 'm': case 'y': case '@': chars += '0123456789'; break; case 'D': case 'M': return null; // Accept anything case "'": if (lookAhead("'")) chars += "'"; else literal = true; break; default: chars += format.charAt(iFormat); } return chars; }, /* Get a setting value, defaulting if necessary. */ _get: function(inst, name) { return inst.settings[name] !== undefined ? inst.settings[name] : this._defaults[name]; }, /* Parse existing date and initialise date picker. */ _setDateFromField: function(inst, noDefault) { if (inst.input.val() == inst.lastVal) { return; } var dateFormat = this._get(inst, 'dateFormat'); var dates = inst.lastVal = inst.input ? inst.input.val() : null; var date, defaultDate; date = defaultDate = this._getDefaultDate(inst); var settings = this._getFormatConfig(inst); try { date = this.parseDate(dateFormat, dates, settings) || defaultDate; } catch (event) { this.log(event); dates = (noDefault ? '' : dates); } inst.selectedDay = date.getDate(); inst.drawMonth = inst.selectedMonth = date.getMonth(); inst.drawYear = inst.selectedYear = date.getFullYear(); inst.currentDay = (dates ? date.getDate() : 0); inst.currentMonth = (dates ? date.getMonth() : 0); inst.currentYear = (dates ? date.getFullYear() : 0); this._adjustInstDate(inst); }, /* Retrieve the default date shown on opening. */ _getDefaultDate: function(inst) { return this._restrictMinMax(inst, this._determineDate(inst, this._get(inst, 'defaultDate'), new Date())); }, /* A date may be specified as an exact value or a relative one. */ _determineDate: function(inst, date, defaultDate) { var offsetNumeric = function(offset) { var date = new Date(); date.setDate(date.getDate() + offset); return date; }; var offsetString = function(offset) { try { return $.datepicker.parseDate($.datepicker._get(inst, 'dateFormat'), offset, $.datepicker._getFormatConfig(inst)); } catch (e) { // Ignore } var date = (offset.toLowerCase().match(/^c/) ? $.datepicker._getDate(inst) : null) || new Date(); var year = date.getFullYear(); var month = date.getMonth(); var day = date.getDate(); var pattern = /([+-]?[0-9]+)\s*(d|D|w|W|m|M|y|Y)?/g; var matches = pattern.exec(offset); while (matches) { switch (matches[2] || 'd') { case 'd' : case 'D' : day += parseInt(matches[1],10); break; case 'w' : case 'W' : day += parseInt(matches[1],10) * 7; break; case 'm' : case 'M' : month += parseInt(matches[1],10); day = Math.min(day, $.datepicker._getDaysInMonth(year, month)); break; case 'y': case 'Y' : year += parseInt(matches[1],10); day = Math.min(day, $.datepicker._getDaysInMonth(year, month)); break; } matches = pattern.exec(offset); } return new Date(year, month, day); }; var newDate = (date == null || date === '' ? defaultDate : (typeof date == 'string' ? offsetString(date) : (typeof date == 'number' ? (isNaN(date) ? defaultDate : offsetNumeric(date)) : new Date(date.getTime())))); newDate = (newDate && newDate.toString() == 'Invalid Date' ? defaultDate : newDate); if (newDate) { newDate.setHours(0); newDate.setMinutes(0); newDate.setSeconds(0); newDate.setMilliseconds(0); } return this._daylightSavingAdjust(newDate); }, /* Handle switch to/from daylight saving. Hours may be non-zero on daylight saving cut-over: > 12 when midnight changeover, but then cannot generate midnight datetime, so jump to 1AM, otherwise reset. @param date (Date) the date to check @return (Date) the corrected date */ _daylightSavingAdjust: function(date) { if (!date) return null; date.setHours(date.getHours() > 12 ? date.getHours() + 2 : 0); return date; }, /* Set the date(s) directly. */ _setDate: function(inst, date, noChange) { var clear = !date; var origMonth = inst.selectedMonth; var origYear = inst.selectedYear; var newDate = this._restrictMinMax(inst, this._determineDate(inst, date, new Date())); inst.selectedDay = inst.currentDay = newDate.getDate(); inst.drawMonth = inst.selectedMonth = inst.currentMonth = newDate.getMonth(); inst.drawYear = inst.selectedYear = inst.currentYear = newDate.getFullYear(); if ((origMonth != inst.selectedMonth || origYear != inst.selectedYear) && !noChange) this._notifyChange(inst); this._adjustInstDate(inst); if (inst.input) { inst.input.val(clear ? '' : this._formatDate(inst)); } }, /* Retrieve the date(s) directly. */ _getDate: function(inst) { var startDate = (!inst.currentYear || (inst.input && inst.input.val() == '') ? null : this._daylightSavingAdjust(new Date( inst.currentYear, inst.currentMonth, inst.currentDay))); return startDate; }, /* Attach the onxxx handlers. These are declared statically so * they work with static code transformers like Caja. */ _attachHandlers: function(inst) { var stepMonths = this._get(inst, 'stepMonths'); var id = '#' + inst.id.replace( /\\\\/g, "\\" ); inst.dpDiv.find('[data-handler]').map(function () { var handler = { prev: function () { window['DP_jQuery_' + dpuuid].datepicker._adjustDate(id, -stepMonths, 'M'); }, next: function () { window['DP_jQuery_' + dpuuid].datepicker._adjustDate(id, +stepMonths, 'M'); }, hide: function () { window['DP_jQuery_' + dpuuid].datepicker._hideDatepicker(); }, today: function () { window['DP_jQuery_' + dpuuid].datepicker._gotoToday(id); }, selectDay: function () { window['DP_jQuery_' + dpuuid].datepicker._selectDay(id, +this.getAttribute('data-month'), +this.getAttribute('data-year'), this); return false; }, selectMonth: function () { window['DP_jQuery_' + dpuuid].datepicker._selectMonthYear(id, this, 'M'); return false; }, selectYear: function () { window['DP_jQuery_' + dpuuid].datepicker._selectMonthYear(id, this, 'Y'); return false; } }; $(this).bind(this.getAttribute('data-event'), handler[this.getAttribute('data-handler')]); }); }, /* Generate the HTML for the current state of the date picker. */ _generateHTML: function(inst) { var today = new Date(); today = this._daylightSavingAdjust( new Date(today.getFullYear(), today.getMonth(), today.getDate())); // clear time var isRTL = this._get(inst, 'isRTL'); var showButtonPanel = this._get(inst, 'showButtonPanel'); var hideIfNoPrevNext = this._get(inst, 'hideIfNoPrevNext'); var navigationAsDateFormat = this._get(inst, 'navigationAsDateFormat'); var numMonths = this._getNumberOfMonths(inst); var showCurrentAtPos = this._get(inst, 'showCurrentAtPos'); var stepMonths = this._get(inst, 'stepMonths'); var isMultiMonth = (numMonths[0] != 1 || numMonths[1] != 1); var currentDate = this._daylightSavingAdjust((!inst.currentDay ? new Date(9999, 9, 9) : new Date(inst.currentYear, inst.currentMonth, inst.currentDay))); var minDate = this._getMinMaxDate(inst, 'min'); var maxDate = this._getMinMaxDate(inst, 'max'); var drawMonth = inst.drawMonth - showCurrentAtPos; var drawYear = inst.drawYear; if (drawMonth < 0) { drawMonth += 12; drawYear--; } if (maxDate) { var maxDraw = this._daylightSavingAdjust(new Date(maxDate.getFullYear(), maxDate.getMonth() - (numMonths[0] * numMonths[1]) + 1, maxDate.getDate())); maxDraw = (minDate && maxDraw < minDate ? minDate : maxDraw); while (this._daylightSavingAdjust(new Date(drawYear, drawMonth, 1)) > maxDraw) { drawMonth--; if (drawMonth < 0) { drawMonth = 11; drawYear--; } } } inst.drawMonth = drawMonth; inst.drawYear = drawYear; var prevText = this._get(inst, 'prevText'); prevText = (!navigationAsDateFormat ? prevText : this.formatDate(prevText, this._daylightSavingAdjust(new Date(drawYear, drawMonth - stepMonths, 1)), this._getFormatConfig(inst))); var prev = (this._canAdjustMonth(inst, -1, drawYear, drawMonth) ? '<a class="ui-datepicker-prev ui-corner-all" data-handler="prev" data-event="click"' + ' title="' + prevText + '"><span class="ui-icon ui-icon-circle-triangle-' + ( isRTL ? 'e' : 'w') + '">' + prevText + '</span></a>' : (hideIfNoPrevNext ? '' : '<a class="ui-datepicker-prev ui-corner-all ui-state-disabled" title="'+ prevText +'"><span class="ui-icon ui-icon-circle-triangle-' + ( isRTL ? 'e' : 'w') + '">' + prevText + '</span></a>')); var nextText = this._get(inst, 'nextText'); nextText = (!navigationAsDateFormat ? nextText : this.formatDate(nextText, this._daylightSavingAdjust(new Date(drawYear, drawMonth + stepMonths, 1)), this._getFormatConfig(inst))); var next = (this._canAdjustMonth(inst, +1, drawYear, drawMonth) ? '<a class="ui-datepicker-next ui-corner-all" data-handler="next" data-event="click"' + ' title="' + nextText + '"><span class="ui-icon ui-icon-circle-triangle-' + ( isRTL ? 'w' : 'e') + '">' + nextText + '</span></a>' : (hideIfNoPrevNext ? '' : '<a class="ui-datepicker-next ui-corner-all ui-state-disabled" title="'+ nextText + '"><span class="ui-icon ui-icon-circle-triangle-' + ( isRTL ? 'w' : 'e') + '">' + nextText + '</span></a>')); var currentText = this._get(inst, 'currentText'); var gotoDate = (this._get(inst, 'gotoCurrent') && inst.currentDay ? currentDate : today); currentText = (!navigationAsDateFormat ? currentText : this.formatDate(currentText, gotoDate, this._getFormatConfig(inst))); var controls = (!inst.inline ? '<button type="button" class="ui-datepicker-close ui-state-default ui-priority-primary ui-corner-all" data-handler="hide" data-event="click">' + this._get(inst, 'closeText') + '</button>' : ''); var buttonPanel = (showButtonPanel) ? '<div class="ui-datepicker-buttonpane ui-widget-content">' + (isRTL ? controls : '') + (this._isInRange(inst, gotoDate) ? '<button type="button" class="ui-datepicker-current ui-state-default ui-priority-secondary ui-corner-all" data-handler="today" data-event="click"' + '>' + currentText + '</button>' : '') + (isRTL ? '' : controls) + '</div>' : ''; var firstDay = parseInt(this._get(inst, 'firstDay'),10); firstDay = (isNaN(firstDay) ? 0 : firstDay); var showWeek = this._get(inst, 'showWeek'); var dayNames = this._get(inst, 'dayNames'); var dayNamesShort = this._get(inst, 'dayNamesShort'); var dayNamesMin = this._get(inst, 'dayNamesMin'); var monthNames = this._get(inst, 'monthNames'); var monthNamesShort = this._get(inst, 'monthNamesShort'); var beforeShowDay = this._get(inst, 'beforeShowDay'); var showOtherMonths = this._get(inst, 'showOtherMonths'); var selectOtherMonths = this._get(inst, 'selectOtherMonths'); var calculateWeek = this._get(inst, 'calculateWeek') || this.iso8601Week; var defaultDate = this._getDefaultDate(inst); var html = ''; for (var row = 0; row < numMonths[0]; row++) { var group = ''; this.maxRows = 4; for (var col = 0; col < numMonths[1]; col++) { var selectedDate = this._daylightSavingAdjust(new Date(drawYear, drawMonth, inst.selectedDay)); var cornerClass = ' ui-corner-all'; var calender = ''; if (isMultiMonth) { calender += '<div class="ui-datepicker-group'; if (numMonths[1] > 1) switch (col) { case 0: calender += ' ui-datepicker-group-first'; cornerClass = ' ui-corner-' + (isRTL ? 'right' : 'left'); break; case numMonths[1]-1: calender += ' ui-datepicker-group-last'; cornerClass = ' ui-corner-' + (isRTL ? 'left' : 'right'); break; default: calender += ' ui-datepicker-group-middle'; cornerClass = ''; break; } calender += '">'; } calender += '<div class="ui-datepicker-header ui-widget-header ui-helper-clearfix' + cornerClass + '">' + (/all|left/.test(cornerClass) && row == 0 ? (isRTL ? next : prev) : '') + (/all|right/.test(cornerClass) && row == 0 ? (isRTL ? prev : next) : '') + this._generateMonthYearHeader(inst, drawMonth, drawYear, minDate, maxDate, row > 0 || col > 0, monthNames, monthNamesShort) + // draw month headers '</div><table class="ui-datepicker-calendar"><thead>' + '<tr>'; var thead = (showWeek ? '<th class="ui-datepicker-week-col">' + this._get(inst, 'weekHeader') + '</th>' : ''); for (var dow = 0; dow < 7; dow++) { // days of the week var day = (dow + firstDay) % 7; thead += '<th' + ((dow + firstDay + 6) % 7 >= 5 ? ' class="ui-datepicker-week-end"' : '') + '>' + '<span title="' + dayNames[day] + '">' + dayNamesMin[day] + '</span></th>'; } calender += thead + '</tr></thead><tbody>'; var daysInMonth = this._getDaysInMonth(drawYear, drawMonth); if (drawYear == inst.selectedYear && drawMonth == inst.selectedMonth) inst.selectedDay = Math.min(inst.selectedDay, daysInMonth); var leadDays = (this._getFirstDayOfMonth(drawYear, drawMonth) - firstDay + 7) % 7; var curRows = Math.ceil((leadDays + daysInMonth) / 7); // calculate the number of rows to generate var numRows = (isMultiMonth ? this.maxRows > curRows ? this.maxRows : curRows : curRows); //If multiple months, use the higher number of rows (see #7043) this.maxRows = numRows; var printDate = this._daylightSavingAdjust(new Date(drawYear, drawMonth, 1 - leadDays)); for (var dRow = 0; dRow < numRows; dRow++) { // create date picker rows calender += '<tr>'; var tbody = (!showWeek ? '' : '<td class="ui-datepicker-week-col">' + this._get(inst, 'calculateWeek')(printDate) + '</td>'); for (var dow = 0; dow < 7; dow++) { // create date picker days var daySettings = (beforeShowDay ? beforeShowDay.apply((inst.input ? inst.input[0] : null), [printDate]) : [true, '']); var otherMonth = (printDate.getMonth() != drawMonth); var unselectable = (otherMonth && !selectOtherMonths) || !daySettings[0] || (minDate && printDate < minDate) || (maxDate && printDate > maxDate); tbody += '<td class="' + ((dow + firstDay + 6) % 7 >= 5 ? ' ui-datepicker-week-end' : '') + // highlight weekends (otherMonth ? ' ui-datepicker-other-month' : '') + // highlight days from other months ((printDate.getTime() == selectedDate.getTime() && drawMonth == inst.selectedMonth && inst._keyEvent) || // user pressed key (defaultDate.getTime() == printDate.getTime() && defaultDate.getTime() == selectedDate.getTime()) ? // or defaultDate is current printedDate and defaultDate is selectedDate ' ' + this._dayOverClass : '') + // highlight selected day (unselectable ? ' ' + this._unselectableClass + ' ui-state-disabled': '') + // highlight unselectable days (otherMonth && !showOtherMonths ? '' : ' ' + daySettings[1] + // highlight custom dates (printDate.getTime() == currentDate.getTime() ? ' ' + this._currentClass : '') + // highlight selected day (printDate.getTime() == today.getTime() ? ' ui-datepicker-today' : '')) + '"' + // highlight today (if different) ((!otherMonth || showOtherMonths) && daySettings[2] ? ' title="' + daySettings[2] + '"' : '') + // cell title (unselectable ? '' : ' data-handler="selectDay" data-event="click" data-month="' + printDate.getMonth() + '" data-year="' + printDate.getFullYear() + '"') + '>' + // actions (otherMonth && !showOtherMonths ? '&#xa0;' : // display for other months (unselectable ? '<span class="ui-state-default">' + printDate.getDate() + '</span>' : '<a class="ui-state-default' + (printDate.getTime() == today.getTime() ? ' ui-state-highlight' : '') + (printDate.getTime() == currentDate.getTime() ? ' ui-state-active' : '') + // highlight selected day (otherMonth ? ' ui-priority-secondary' : '') + // distinguish dates from other months '" href="#">' + printDate.getDate() + '</a>')) + '</td>'; // display selectable date printDate.setDate(printDate.getDate() + 1); printDate = this._daylightSavingAdjust(printDate); } calender += tbody + '</tr>'; } drawMonth++; if (drawMonth > 11) { drawMonth = 0; drawYear++; } calender += '</tbody></table>' + (isMultiMonth ? '</div>' + ((numMonths[0] > 0 && col == numMonths[1]-1) ? '<div class="ui-datepicker-row-break"></div>' : '') : ''); group += calender; } html += group; } html += buttonPanel + ($.browser.msie && parseInt($.browser.version,10) < 7 && !inst.inline ? '<iframe src="javascript:false;" class="ui-datepicker-cover" frameborder="0"></iframe>' : ''); inst._keyEvent = false; return html; }, /* Generate the month and year header. */ _generateMonthYearHeader: function(inst, drawMonth, drawYear, minDate, maxDate, secondary, monthNames, monthNamesShort) { var changeMonth = this._get(inst, 'changeMonth'); var changeYear = this._get(inst, 'changeYear'); var showMonthAfterYear = this._get(inst, 'showMonthAfterYear'); var html = '<div class="ui-datepicker-title">'; var monthHtml = ''; // month selection if (secondary || !changeMonth) monthHtml += '<span class="ui-datepicker-month">' + monthNames[drawMonth] + '</span>'; else { var inMinYear = (minDate && minDate.getFullYear() == drawYear); var inMaxYear = (maxDate && maxDate.getFullYear() == drawYear); monthHtml += '<select class="ui-datepicker-month" data-handler="selectMonth" data-event="change">'; for (var month = 0; month < 12; month++) { if ((!inMinYear || month >= minDate.getMonth()) && (!inMaxYear || month <= maxDate.getMonth())) monthHtml += '<option value="' + month + '"' + (month == drawMonth ? ' selected="selected"' : '') + '>' + monthNamesShort[month] + '</option>'; } monthHtml += '</select>'; } if (!showMonthAfterYear) html += monthHtml + (secondary || !(changeMonth && changeYear) ? '&#xa0;' : ''); // year selection if ( !inst.yearshtml ) { inst.yearshtml = ''; if (secondary || !changeYear) html += '<span class="ui-datepicker-year">' + drawYear + '</span>'; else { // determine range of years to display var years = this._get(inst, 'yearRange').split(':'); var thisYear = new Date().getFullYear(); var determineYear = function(value) { var year = (value.match(/c[+-].*/) ? drawYear + parseInt(value.substring(1), 10) : (value.match(/[+-].*/) ? thisYear + parseInt(value, 10) : parseInt(value, 10))); return (isNaN(year) ? thisYear : year); }; var year = determineYear(years[0]); var endYear = Math.max(year, determineYear(years[1] || '')); year = (minDate ? Math.max(year, minDate.getFullYear()) : year); endYear = (maxDate ? Math.min(endYear, maxDate.getFullYear()) : endYear); inst.yearshtml += '<select class="ui-datepicker-year" data-handler="selectYear" data-event="change">'; for (; year <= endYear; year++) { inst.yearshtml += '<option value="' + year + '"' + (year == drawYear ? ' selected="selected"' : '') + '>' + year + '</option>'; } inst.yearshtml += '</select>'; html += inst.yearshtml; inst.yearshtml = null; } } html += this._get(inst, 'yearSuffix'); if (showMonthAfterYear) html += (secondary || !(changeMonth && changeYear) ? '&#xa0;' : '') + monthHtml; html += '</div>'; // Close datepicker_header return html; }, /* Adjust one of the date sub-fields. */ _adjustInstDate: function(inst, offset, period) { var year = inst.drawYear + (period == 'Y' ? offset : 0); var month = inst.drawMonth + (period == 'M' ? offset : 0); var day = Math.min(inst.selectedDay, this._getDaysInMonth(year, month)) + (period == 'D' ? offset : 0); var date = this._restrictMinMax(inst, this._daylightSavingAdjust(new Date(year, month, day))); inst.selectedDay = date.getDate(); inst.drawMonth = inst.selectedMonth = date.getMonth(); inst.drawYear = inst.selectedYear = date.getFullYear(); if (period == 'M' || period == 'Y') this._notifyChange(inst); }, /* Ensure a date is within any min/max bounds. */ _restrictMinMax: function(inst, date) { var minDate = this._getMinMaxDate(inst, 'min'); var maxDate = this._getMinMaxDate(inst, 'max'); var newDate = (minDate && date < minDate ? minDate : date); newDate = (maxDate && newDate > maxDate ? maxDate : newDate); return newDate; }, /* Notify change of month/year. */ _notifyChange: function(inst) { var onChange = this._get(inst, 'onChangeMonthYear'); if (onChange) onChange.apply((inst.input ? inst.input[0] : null), [inst.selectedYear, inst.selectedMonth + 1, inst]); }, /* Determine the number of months to show. */ _getNumberOfMonths: function(inst) { var numMonths = this._get(inst, 'numberOfMonths'); return (numMonths == null ? [1, 1] : (typeof numMonths == 'number' ? [1, numMonths] : numMonths)); }, /* Determine the current maximum date - ensure no time components are set. */ _getMinMaxDate: function(inst, minMax) { return this._determineDate(inst, this._get(inst, minMax + 'Date'), null); }, /* Find the number of days in a given month. */ _getDaysInMonth: function(year, month) { return 32 - this._daylightSavingAdjust(new Date(year, month, 32)).getDate(); }, /* Find the day of the week of the first of a month. */ _getFirstDayOfMonth: function(year, month) { return new Date(year, month, 1).getDay(); }, /* Determines if we should allow a "next/prev" month display change. */ _canAdjustMonth: function(inst, offset, curYear, curMonth) { var numMonths = this._getNumberOfMonths(inst); var date = this._daylightSavingAdjust(new Date(curYear, curMonth + (offset < 0 ? offset : numMonths[0] * numMonths[1]), 1)); if (offset < 0) date.setDate(this._getDaysInMonth(date.getFullYear(), date.getMonth())); return this._isInRange(inst, date); }, /* Is the given date in the accepted range? */ _isInRange: function(inst, date) { var minDate = this._getMinMaxDate(inst, 'min'); var maxDate = this._getMinMaxDate(inst, 'max'); return ((!minDate || date.getTime() >= minDate.getTime()) && (!maxDate || date.getTime() <= maxDate.getTime())); }, /* Provide the configuration settings for formatting/parsing. */ _getFormatConfig: function(inst) { var shortYearCutoff = this._get(inst, 'shortYearCutoff'); shortYearCutoff = (typeof shortYearCutoff != 'string' ? shortYearCutoff : new Date().getFullYear() % 100 + parseInt(shortYearCutoff, 10)); return {shortYearCutoff: shortYearCutoff, dayNamesShort: this._get(inst, 'dayNamesShort'), dayNames: this._get(inst, 'dayNames'), monthNamesShort: this._get(inst, 'monthNamesShort'), monthNames: this._get(inst, 'monthNames')}; }, /* Format the given date for display. */ _formatDate: function(inst, day, month, year) { if (!day) { inst.currentDay = inst.selectedDay; inst.currentMonth = inst.selectedMonth; inst.currentYear = inst.selectedYear; } var date = (day ? (typeof day == 'object' ? day : this._daylightSavingAdjust(new Date(year, month, day))) : this._daylightSavingAdjust(new Date(inst.currentYear, inst.currentMonth, inst.currentDay))); return this.formatDate(this._get(inst, 'dateFormat'), date, this._getFormatConfig(inst)); } }); /* * Bind hover events for datepicker elements. * Done via delegate so the binding only occurs once in the lifetime of the parent div. * Global instActive, set by _updateDatepicker allows the handlers to find their way back to the active picker. */ function bindHover(dpDiv) { var selector = 'button, .ui-datepicker-prev, .ui-datepicker-next, .ui-datepicker-calendar td a'; return dpDiv.bind('mouseout', function(event) { var elem = $( event.target ).closest( selector ); if ( !elem.length ) { return; } elem.removeClass( "ui-state-hover ui-datepicker-prev-hover ui-datepicker-next-hover" ); }) .bind('mouseover', function(event) { var elem = $( event.target ).closest( selector ); if ($.datepicker._isDisabledDatepicker( instActive.inline ? dpDiv.parent()[0] : instActive.input[0]) || !elem.length ) { return; } elem.parents('.ui-datepicker-calendar').find('a').removeClass('ui-state-hover'); elem.addClass('ui-state-hover'); if (elem.hasClass('ui-datepicker-prev')) elem.addClass('ui-datepicker-prev-hover'); if (elem.hasClass('ui-datepicker-next')) elem.addClass('ui-datepicker-next-hover'); }); } /* jQuery extend now ignores nulls! */ function extendRemove(target, props) { $.extend(target, props); for (var name in props) if (props[name] == null || props[name] == undefined) target[name] = props[name]; return target; }; /* Determine whether an object is an array. */ function isArray(a) { return (a && (($.browser.safari && typeof a == 'object' && a.length) || (a.constructor && a.constructor.toString().match(/\Array\(\)/)))); }; /* Invoke the datepicker functionality. @param options string - a command, optionally followed by additional parameters or Object - settings for attaching new datepicker functionality @return jQuery object */ $.fn.datepicker = function(options){ /* Verify an empty collection wasn't passed - Fixes #6976 */ if ( !this.length ) { return this; } /* Initialise the date picker. */ if (!$.datepicker.initialized) { $(document).mousedown($.datepicker._checkExternalClick). find('body').append($.datepicker.dpDiv); $.datepicker.initialized = true; } var otherArgs = Array.prototype.slice.call(arguments, 1); if (typeof options == 'string' && (options == 'isDisabled' || options == 'getDate' || options == 'widget')) return $.datepicker['_' + options + 'Datepicker']. apply($.datepicker, [this[0]].concat(otherArgs)); if (options == 'option' && arguments.length == 2 && typeof arguments[1] == 'string') return $.datepicker['_' + options + 'Datepicker']. apply($.datepicker, [this[0]].concat(otherArgs)); return this.each(function() { typeof options == 'string' ? $.datepicker['_' + options + 'Datepicker']. apply($.datepicker, [this].concat(otherArgs)) : $.datepicker._attachDatepicker(this, options); }); }; $.datepicker = new Datepicker(); // singleton instance $.datepicker.initialized = false; $.datepicker.uuid = new Date().getTime(); $.datepicker.version = "1.8.24"; // Workaround for #4055 // Add another global to avoid noConflict issues with inline event handlers window['DP_jQuery_' + dpuuid] = $; })(jQuery); return module.exports; }).call(this); // src/js/aui/date-picker.js (typeof window === 'undefined' ? global : window).__5c6cb0b8869ae16d5b8736e0515d6f1f = (function () { var module = { exports: {} }; var exports = module.exports; 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _jquery = __77629c8e853846530dfdc3ccd3393ab6; var _jquery2 = _interopRequireDefault(_jquery); __38fc196a0b1b19c55ba3d238f6ed4f0e; var _log = __bbcdfae479e60b56b982bbcdcc7a0191; var logger = _interopRequireWildcard(_log); var _browser = __f666f841af3a176efae42d305f1cf2f4; var _globalize = __77af00e80ac034b223816679459a4692; var _globalize2 = _interopRequireDefault(_globalize); var _inlineDialog = __06d3ad1f0d26ed0b52b9e335bb5a8831; var _inlineDialog2 = _interopRequireDefault(_inlineDialog); var _keyCode = __b925764b9e17cff61f648a86f18e6e25; var _keyCode2 = _interopRequireDefault(_keyCode); var _i18n = __be3e01199078cdf5ded88dda6a8fbec9; var _i18n2 = _interopRequireDefault(_i18n); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var datePickerCounter = 0; function DatePicker(field, options) { var datePicker; var initPolyfill; var $field; var datePickerUUID; var parentPopup; datePicker = {}; datePickerUUID = datePickerCounter++; // --------------------------------------------------------------------- // fix up arguments ---------------------------------------------------- // --------------------------------------------------------------------- $field = (0, _jquery2.default)(field); $field.attr('data-aui-dp-uuid', datePickerUUID); options = _jquery2.default.extend(undefined, DatePicker.prototype.defaultOptions, options); // --------------------------------------------------------------------- // expose arguments with getters --------------------------------------- // --------------------------------------------------------------------- datePicker.getField = function () { return $field; }; datePicker.getOptions = function () { return options; }; // --------------------------------------------------------------------- // exposed methods ----------------------------------------------------- // --------------------------------------------------------------------- initPolyfill = function initPolyfill() { var calendar; var handleDatePickerFocus; var handleFieldBlur; var handleFieldFocus; var handleFieldUpdate; var initCalendar; var isSuppressingShow; var isTrackingDatePickerFocus; var popup; var popupContents; // ----------------------------------------------------------------- // expose methods for controlling the popup ------------------------ // ----------------------------------------------------------------- datePicker.hide = function () { popup.hide(); }; datePicker.show = function () { popup.show(); }; datePicker.setDate = function (value) { if (typeof calendar !== 'undefined') { calendar.datepicker('setDate', value); } }; datePicker.getDate = function () { if (typeof calendar !== 'undefined') { return calendar.datepicker('getDate'); } }; // ----------------------------------------------------------------- // initialise the calendar ----------------------------------------- // ----------------------------------------------------------------- initCalendar = function initCalendar(i18nConfig) { popupContents.off(); if (options.hint) { var $hint = (0, _jquery2.default)('<div/>').addClass('aui-datepicker-hint'); $hint.append('<span/>').text(options.hint); popupContents.append($hint); } calendar = (0, _jquery2.default)('<div/>'); calendar.attr('data-aui-dp-popup-uuid', datePickerUUID); popupContents.append(calendar); var config = { 'dateFormat': options.dateFormat, 'defaultDate': $field.val(), 'maxDate': $field.attr('max'), 'minDate': $field.attr('min'), 'nextText': '>', 'onSelect': function onSelect(dateText) { $field.val(dateText); $field.change(); datePicker.hide(); isSuppressingShow = true; $field.focus(); options.onSelect && options.onSelect.call(this, dateText); }, onChangeMonthYear: function onChangeMonthYear() { // defer rehresh call until current stack has cleared (after month has rendered) setTimeout(popup.refresh, 0); }, 'prevText': '<' }; _jquery2.default.extend(config, i18nConfig); if (options.firstDay > -1) { config.firstDay = options.firstDay; } if (typeof $field.attr('step') !== 'undefined') { logger.log('WARNING: The date picker polyfill currently does not support the step attribute!'); } calendar.datepicker(config); // bind additional field processing events (0, _jquery2.default)('body').on('keydown', handleDatePickerFocus); $field.on('focusout keydown', handleFieldBlur); $field.on('propertychange keyup input paste', handleFieldUpdate); }; // ----------------------------------------------------------------- // event handler wrappers ------------------------------------------ // ----------------------------------------------------------------- handleDatePickerFocus = function handleDatePickerFocus(event) { var $eventTarget = (0, _jquery2.default)(event.target); var isTargetInput = $eventTarget.closest(popupContents).length || $eventTarget.is($field); var isTargetPopup = $eventTarget.closest('.ui-datepicker-header').length; // Hide if we're clicking anywhere else but the input or popup OR if esc is pressed. if (!isTargetInput && !isTargetPopup || event.keyCode === _keyCode2.default.ESCAPE) { datePicker.hide(); return; } if ($eventTarget[0] !== $field[0]) { event.preventDefault(); } }; handleFieldBlur = function handleFieldBlur() { // Trigger blur if event is keydown and esc OR is focusout. if (!isTrackingDatePickerFocus) { (0, _jquery2.default)('body').on('focus blur click mousedown', '*', handleDatePickerFocus); isTrackingDatePickerFocus = true; } }; handleFieldFocus = function handleFieldFocus() { if (!isSuppressingShow) { datePicker.show(); } else { isSuppressingShow = false; } }; handleFieldUpdate = function handleFieldUpdate() { var val = (0, _jquery2.default)(this).val(); // IE10/11 fire the 'input' event when internally showing and hiding // the placeholder of an input. This was cancelling the inital click // event and preventing the selection of the first date. The val check here // is a workaround to assure we have legitimate user input that should update // the calendar if (val) { calendar.datepicker('setDate', $field.val()); calendar.datepicker('option', { 'maxDate': $field.attr('max'), 'minDate': $field.attr('min') }); } }; // ----------------------------------------------------------------- // undo (almost) everything ---------------------------------------- // ----------------------------------------------------------------- datePicker.destroyPolyfill = function () { // goodbye, cruel world! datePicker.hide(); $field.attr('placeholder', null); $field.off('propertychange keyup input paste', handleFieldUpdate); $field.off('focus click', handleFieldFocus); $field.off('focusout keydown', handleFieldBlur); (0, _jquery2.default)('body').off('keydown', handleFieldBlur); if (DatePicker.prototype.browserSupportsDateField) { $field[0].type = 'date'; } if (typeof calendar !== 'undefined') { calendar.datepicker('destroy'); } // TODO: figure out a way to tear down the popup (if necessary) delete datePicker.destroyPolyfill; delete datePicker.show; delete datePicker.hide; }; // ----------------------------------------------------------------- // polyfill bootstrap ---------------------------------------------- // ----------------------------------------------------------------- isSuppressingShow = false; // used to stop the popover from showing when focus is restored to the field after a date has been selected isTrackingDatePickerFocus = false; // used to prevent multiple bindings of handleDatePickerFocus within handleFieldBlur if (!(options.languageCode in DatePicker.prototype.localisations)) { options.languageCode = ''; } var i18nConfig = DatePicker.prototype.localisations; var containerClass = ''; var width = 240; if (i18nConfig.size === 'large') { width = 325; containerClass = 'aui-datepicker-dialog-large'; } var dialogOptions = { 'hideCallback': function hideCallback() { (0, _jquery2.default)('body').off('focus blur click mousedown', '*', handleDatePickerFocus); isTrackingDatePickerFocus = false; if (parentPopup && parentPopup._datePickerPopup) { delete parentPopup._datePickerPopup; } }, 'hideDelay': null, 'noBind': true, 'persistent': true, 'closeOthers': false, 'width': width }; if (options.position) { dialogOptions.calculatePositions = function (popup, targetPosition) { // create a jQuery object from the internal var vanilla = (0, _jquery2.default)(popup[0]); return options.position.call(this, vanilla, targetPosition); }; } popup = (0, _inlineDialog2.default)($field, undefined, function (contents, trigger, showPopup) { if (typeof calendar === 'undefined') { popupContents = contents; initCalendar(i18nConfig); } parentPopup = (0, _jquery2.default)(trigger).closest('.aui-inline-dialog').get(0); if (parentPopup) { parentPopup._datePickerPopup = popup; // AUI-2696 - hackish coupling to control inline-dialog close behaviour. } showPopup(); }, dialogOptions); popup.addClass('aui-datepicker-dialog'); popup.addClass(containerClass); // bind what we need to start off with $field.on('focus click', handleFieldFocus); // the click is for fucking opera... Y U NO FIRE FOCUS EVENTS PROPERLY??? // give users a hint that this is a date field; note that placeholder isn't technically a valid attribute // according to the spec... $field.attr('placeholder', options.dateFormat); // override the browser's default date field implementation (if applicable) // since IE doesn't support date input fields, we should be fine... if (options.overrideBrowserDefault && DatePicker.prototype.browserSupportsDateField) { $field[0].type = 'text'; //workaround for this issue in Edge: https://connect.microsoft.com/IE/feedback/details/1603512/changing-an-input-type-to-text-does-not-set-the-value var value = $field[0].getAttribute('value'); //can't use jquery to get the attribute because it doesn't work in Edge if (value) { $field[0].value = value; } } }; datePicker.reset = function () { if (typeof datePicker.destroyPolyfill === 'function') { datePicker.destroyPolyfill(); } if (!DatePicker.prototype.browserSupportsDateField || options.overrideBrowserDefault) { initPolyfill(); } }; // --------------------------------------------------------------------- // bootstrap ----------------------------------------------------------- // --------------------------------------------------------------------- datePicker.reset(); return datePicker; }; // ------------------------------------------------------------------------- // things that should be common -------------------------------------------- // ------------------------------------------------------------------------- DatePicker.prototype.browserSupportsDateField = (0, _browser.supportsDateField)(); DatePicker.prototype.defaultOptions = { overrideBrowserDefault: false, firstDay: -1, languageCode: (0, _jquery2.default)('html').attr('lang') || 'en-AU', dateFormat: _jquery2.default.datepicker.W3C // same as $.datepicker.ISO_8601 }; // adapted from the jQuery UI Datepicker widget (v1.8.16), with the following changes: // - dayNamesShort -> dayNamesMin // - unnecessary attributes omitted /* CODE to extract codes out: var langCode, langs, out; langs = jQuery.datepicker.regional; out = {}; for (langCode in langs) { if (langs.hasOwnProperty(langCode)) { out[langCode] = { 'dayNames': langs[langCode].dayNames, 'dayNamesMin': langs[langCode].dayNamesShort, // this is deliberate 'firstDay': langs[langCode].firstDay, 'isRTL': langs[langCode].isRTL, 'monthNames': langs[langCode].monthNames, 'showMonthAfterYear': langs[langCode].showMonthAfterYear, 'yearSuffix': langs[langCode].yearSuffix }; } } */ DatePicker.prototype.localisations = { "dayNames": [_i18n2.default.getText('ajs.datepicker.localisations.day-names.sunday'), _i18n2.default.getText('ajs.datepicker.localisations.day-names.monday'), _i18n2.default.getText('ajs.datepicker.localisations.day-names.tuesday'), _i18n2.default.getText('ajs.datepicker.localisations.day-names.wednesday'), _i18n2.default.getText('ajs.datepicker.localisations.day-names.thursday'), _i18n2.default.getText('ajs.datepicker.localisations.day-names.friday'), _i18n2.default.getText('ajs.datepicker.localisations.day-names.saturday')], "dayNamesMin": [_i18n2.default.getText('ajs.datepicker.localisations.day-names-min.sunday'), _i18n2.default.getText('ajs.datepicker.localisations.day-names-min.monday'), _i18n2.default.getText('ajs.datepicker.localisations.day-names-min.tuesday'), _i18n2.default.getText('ajs.datepicker.localisations.day-names-min.wednesday'), _i18n2.default.getText('ajs.datepicker.localisations.day-names-min.thursday'), _i18n2.default.getText('ajs.datepicker.localisations.day-names-min.friday'), _i18n2.default.getText('ajs.datepicker.localisations.day-names-min.saturday')], "firstDay": _i18n2.default.getText('ajs.datepicker.localisations.first-day'), "isRTL": _i18n2.default.getText('ajs.datepicker.localisations.is-RTL') === "true" ? true : false, "monthNames": [_i18n2.default.getText('ajs.datepicker.localisations.month-names.january'), _i18n2.default.getText('ajs.datepicker.localisations.month-names.february'), _i18n2.default.getText('ajs.datepicker.localisations.month-names.march'), _i18n2.default.getText('ajs.datepicker.localisations.month-names.april'), _i18n2.default.getText('ajs.datepicker.localisations.month-names.may'), _i18n2.default.getText('ajs.datepicker.localisations.month-names.june'), _i18n2.default.getText('ajs.datepicker.localisations.month-names.july'), _i18n2.default.getText('ajs.datepicker.localisations.month-names.august'), _i18n2.default.getText('ajs.datepicker.localisations.month-names.september'), _i18n2.default.getText('ajs.datepicker.localisations.month-names.october'), _i18n2.default.getText('ajs.datepicker.localisations.month-names.november'), _i18n2.default.getText('ajs.datepicker.localisations.month-names.december')], "showMonthAfterYear": _i18n2.default.getText('ajs.datepicker.localisations.show-month-after-year') === "true" ? true : false, "yearSuffix": _i18n2.default.getText('ajs.datepicker.localisations.year-suffix') // ------------------------------------------------------------------------- // finally, integrate with jQuery for convenience -------------------------- // ------------------------------------------------------------------------- };_jquery2.default.fn.datePicker = function (options) { return new DatePicker(this, options); }; (0, _globalize2.default)('DatePicker', DatePicker); exports.default = DatePicker; module.exports = exports['default']; return module.exports; }).call(this); // src/js/aui-datepicker.js (typeof window === 'undefined' ? global : window).__813dcdf025c5936d08ca42ebe85245f1 = (function () { var module = { exports: {} }; var exports = module.exports; 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); __5c6cb0b8869ae16d5b8736e0515d6f1f; exports.default = window.AJS; module.exports = exports['default']; return module.exports; }).call(this);
'use strict'; const chai = require('chai'), expect = chai.expect, Support = require(__dirname + '/../support'), DataTypes = require(__dirname + '/../../../lib/data-types'), Sequelize = Support.Sequelize, dialect = Support.getTestDialect(), sinon = require('sinon'), Promise = require('bluebird'); describe(Support.getTestDialectTeaser('Hooks'), () => { beforeEach(function() { this.User = this.sequelize.define('User', { username: { type: DataTypes.STRING, allowNull: false }, mood: { type: DataTypes.ENUM, values: ['happy', 'sad', 'neutral'] } }); this.ParanoidUser = this.sequelize.define('ParanoidUser', { username: DataTypes.STRING, mood: { type: DataTypes.ENUM, values: ['happy', 'sad', 'neutral'] } }, { paranoid: true }); return this.sequelize.sync({ force: true }); }); describe('#define', () => { before(function() { this.sequelize.addHook('beforeDefine', (attributes, options) => { options.modelName = 'bar'; options.name.plural = 'barrs'; attributes.type = DataTypes.STRING; }); this.sequelize.addHook('afterDefine', factory => { factory.options.name.singular = 'barr'; }); this.model = this.sequelize.define('foo', {name: DataTypes.STRING}); }); it('beforeDefine hook can change model name', function() { expect(this.model.name).to.equal('bar'); }); it('beforeDefine hook can alter options', function() { expect(this.model.options.name.plural).to.equal('barrs'); }); it('beforeDefine hook can alter attributes', function() { expect(this.model.rawAttributes.type).to.be.ok; }); it('afterDefine hook can alter options', function() { expect(this.model.options.name.singular).to.equal('barr'); }); after(function() { this.sequelize.options.hooks = {}; this.sequelize.modelManager.removeModel(this.model); }); }); describe('#init', () => { before(function() { Sequelize.addHook('beforeInit', (config, options) => { config.database = 'db2'; options.host = 'server9'; }); Sequelize.addHook('afterInit', sequelize => { sequelize.options.protocol = 'udp'; }); this.seq = new Sequelize('db', 'user', 'pass', { dialect }); }); it('beforeInit hook can alter config', function() { expect(this.seq.config.database).to.equal('db2'); }); it('beforeInit hook can alter options', function() { expect(this.seq.options.host).to.equal('server9'); }); it('afterInit hook can alter options', function() { expect(this.seq.options.protocol).to.equal('udp'); }); after(() => { Sequelize.options.hooks = {}; }); }); describe('passing DAO instances', () => { describe('beforeValidate / afterValidate', () => { it('should pass a DAO instance to the hook', function() { let beforeHooked = false; let afterHooked = false; const User = this.sequelize.define('User', { username: DataTypes.STRING }, { hooks: { beforeValidate(user) { expect(user).to.be.instanceof(User); beforeHooked = true; return Promise.resolve(); }, afterValidate(user) { expect(user).to.be.instanceof(User); afterHooked = true; return Promise.resolve(); } } }); return User.sync({ force: true }).then(() => { return User.create({ username: 'bob' }).then(() => { expect(beforeHooked).to.be.true; expect(afterHooked).to.be.true; }); }); }); }); describe('beforeCreate / afterCreate', () => { it('should pass a DAO instance to the hook', function() { let beforeHooked = false; let afterHooked = false; const User = this.sequelize.define('User', { username: DataTypes.STRING }, { hooks: { beforeCreate(user) { expect(user).to.be.instanceof(User); beforeHooked = true; return Promise.resolve(); }, afterCreate(user) { expect(user).to.be.instanceof(User); afterHooked = true; return Promise.resolve(); } } }); return User.sync({ force: true }).then(() => { return User.create({ username: 'bob' }).then(() => { expect(beforeHooked).to.be.true; expect(afterHooked).to.be.true; }); }); }); }); describe('beforeDestroy / afterDestroy', () => { it('should pass a DAO instance to the hook', function() { let beforeHooked = false; let afterHooked = false; const User = this.sequelize.define('User', { username: DataTypes.STRING }, { hooks: { beforeDestroy(user) { expect(user).to.be.instanceof(User); beforeHooked = true; return Promise.resolve(); }, afterDestroy(user) { expect(user).to.be.instanceof(User); afterHooked = true; return Promise.resolve(); } } }); return User.sync({ force: true }).then(() => { return User.create({ username: 'bob' }).then(user => { return user.destroy().then(() => { expect(beforeHooked).to.be.true; expect(afterHooked).to.be.true; }); }); }); }); }); describe('beforeDelete / afterDelete', () => { it('should pass a DAO instance to the hook', function() { let beforeHooked = false; let afterHooked = false; const User = this.sequelize.define('User', { username: DataTypes.STRING }, { hooks: { beforeDelete(user) { expect(user).to.be.instanceof(User); beforeHooked = true; return Promise.resolve(); }, afterDelete(user) { expect(user).to.be.instanceof(User); afterHooked = true; return Promise.resolve(); } } }); return User.sync({ force: true }).then(() => { return User.create({ username: 'bob' }).then(user => { return user.destroy().then(() => { expect(beforeHooked).to.be.true; expect(afterHooked).to.be.true; }); }); }); }); }); describe('beforeUpdate / afterUpdate', () => { it('should pass a DAO instance to the hook', function() { let beforeHooked = false; let afterHooked = false; const User = this.sequelize.define('User', { username: DataTypes.STRING }, { hooks: { beforeUpdate(user) { expect(user).to.be.instanceof(User); beforeHooked = true; return Promise.resolve(); }, afterUpdate(user) { expect(user).to.be.instanceof(User); afterHooked = true; return Promise.resolve(); } } }); return User.sync({ force: true }).then(() => { return User.create({ username: 'bob' }).then(user => { user.username = 'bawb'; return user.save({ fields: ['username'] }).then(() => { expect(beforeHooked).to.be.true; expect(afterHooked).to.be.true; }); }); }); }); }); }); describe('Model#sync', () => { describe('on success', () => { it('should run hooks', function() { const beforeHook = sinon.spy(), afterHook = sinon.spy(); this.User.beforeSync(beforeHook); this.User.afterSync(afterHook); return this.User.sync().then(() => { expect(beforeHook).to.have.been.calledOnce; expect(afterHook).to.have.been.calledOnce; }); }); it('should not run hooks when "hooks = false" option passed', function() { const beforeHook = sinon.spy(), afterHook = sinon.spy(); this.User.beforeSync(beforeHook); this.User.afterSync(afterHook); return this.User.sync({ hooks: false }).then(() => { expect(beforeHook).to.not.have.been.called; expect(afterHook).to.not.have.been.called; }); }); }); describe('on error', () => { it('should return an error from before', function() { const beforeHook = sinon.spy(), afterHook = sinon.spy(); this.User.beforeSync(() => { beforeHook(); throw new Error('Whoops!'); }); this.User.afterSync(afterHook); return expect(this.User.sync()).to.be.rejected.then(() => { expect(beforeHook).to.have.been.calledOnce; expect(afterHook).not.to.have.been.called; }); }); it('should return an error from after', function() { const beforeHook = sinon.spy(), afterHook = sinon.spy(); this.User.beforeSync(beforeHook); this.User.afterSync(() => { afterHook(); throw new Error('Whoops!'); }); return expect(this.User.sync()).to.be.rejected.then(() => { expect(beforeHook).to.have.been.calledOnce; expect(afterHook).to.have.been.calledOnce; }); }); }); }); describe('sequelize#sync', () => { describe('on success', () => { it('should run hooks', function() { const beforeHook = sinon.spy(), afterHook = sinon.spy(), modelBeforeHook = sinon.spy(), modelAfterHook = sinon.spy(); this.sequelize.beforeBulkSync(beforeHook); this.User.beforeSync(modelBeforeHook); this.User.afterSync(modelAfterHook); this.sequelize.afterBulkSync(afterHook); return this.sequelize.sync().then(() => { expect(beforeHook).to.have.been.calledOnce; expect(modelBeforeHook).to.have.been.calledOnce; expect(modelAfterHook).to.have.been.calledOnce; expect(afterHook).to.have.been.calledOnce; }); }); it('should not run hooks if "hooks = false" option passed', function() { const beforeHook = sinon.spy(), afterHook = sinon.spy(), modelBeforeHook = sinon.spy(), modelAfterHook = sinon.spy(); this.sequelize.beforeBulkSync(beforeHook); this.User.beforeSync(modelBeforeHook); this.User.afterSync(modelAfterHook); this.sequelize.afterBulkSync(afterHook); return this.sequelize.sync({ hooks: false }).then(() => { expect(beforeHook).to.not.have.been.called; expect(modelBeforeHook).to.not.have.been.called; expect(modelAfterHook).to.not.have.been.called; expect(afterHook).to.not.have.been.called; }); }); afterEach(function() { this.sequelize.options.hooks = {}; }); }); describe('on error', () => { it('should return an error from before', function() { const beforeHook = sinon.spy(), afterHook = sinon.spy(); this.sequelize.beforeBulkSync(() => { beforeHook(); throw new Error('Whoops!'); }); this.sequelize.afterBulkSync(afterHook); return expect(this.sequelize.sync()).to.be.rejected.then(() => { expect(beforeHook).to.have.been.calledOnce; expect(afterHook).not.to.have.been.called; }); }); it('should return an error from after', function() { const beforeHook = sinon.spy(), afterHook = sinon.spy(); this.sequelize.beforeBulkSync(beforeHook); this.sequelize.afterBulkSync(() => { afterHook(); throw new Error('Whoops!'); }); return expect(this.sequelize.sync()).to.be.rejected.then(() => { expect(beforeHook).to.have.been.calledOnce; expect(afterHook).to.have.been.calledOnce; }); }); afterEach(function() { this.sequelize.options.hooks = {}; }); }); }); describe('#removal', () => { it('should be able to remove by name', function() { const sasukeHook = sinon.spy(), narutoHook = sinon.spy(); this.User.hook('beforeCreate', 'sasuke', sasukeHook); this.User.hook('beforeCreate', 'naruto', narutoHook); return this.User.create({ username: 'makunouchi'}).then(() => { expect(sasukeHook).to.have.been.calledOnce; expect(narutoHook).to.have.been.calledOnce; this.User.removeHook('beforeCreate', 'sasuke'); return this.User.create({ username: 'sendo'}); }).then(() => { expect(sasukeHook).to.have.been.calledOnce; expect(narutoHook).to.have.been.calledTwice; }); }); it('should be able to remove by reference', function() { const sasukeHook = sinon.spy(), narutoHook = sinon.spy(); this.User.hook('beforeCreate', sasukeHook); this.User.hook('beforeCreate', narutoHook); return this.User.create({ username: 'makunouchi'}).then(() => { expect(sasukeHook).to.have.been.calledOnce; expect(narutoHook).to.have.been.calledOnce; this.User.removeHook('beforeCreate', sasukeHook); return this.User.create({ username: 'sendo'}); }).then(() => { expect(sasukeHook).to.have.been.calledOnce; expect(narutoHook).to.have.been.calledTwice; }); }); it('should be able to remove proxies', function() { const sasukeHook = sinon.spy(), narutoHook = sinon.spy(); this.User.hook('beforeSave', sasukeHook); this.User.hook('beforeSave', narutoHook); return this.User.create({ username: 'makunouchi'}).then(user => { expect(sasukeHook).to.have.been.calledOnce; expect(narutoHook).to.have.been.calledOnce; this.User.removeHook('beforeSave', sasukeHook); return user.updateAttributes({ username: 'sendo'}); }).then(() => { expect(sasukeHook).to.have.been.calledOnce; expect(narutoHook).to.have.been.calledTwice; }); }); }); });
/* Highcharts JS v4.0.4 (2014-09-02) Solid angular gauge module (c) 2010-2014 Torstein Honsi License: www.highcharts.com/license */ (function(a){var k=a.getOptions().plotOptions,q=a.pInt,r=a.pick,l=a.each,n;k.solidgauge=a.merge(k.gauge,{colorByPoint:!0});n={initDataClasses:function(b){var h=this,e=this.chart,c,m=0,f=this.options;this.dataClasses=c=[];l(b.dataClasses,function(g,d){var i,g=a.merge(g);c.push(g);if(!g.color)f.dataClassColor==="category"?(i=e.options.colors,g.color=i[m++],m===i.length&&(m=0)):g.color=h.tweenColors(a.Color(f.minColor),a.Color(f.maxColor),d/(b.dataClasses.length-1))})},initStops:function(b){this.stops= b.stops||[[0,this.options.minColor],[1,this.options.maxColor]];l(this.stops,function(b){b.color=a.Color(b[1])})},toColor:function(b,h){var e,c=this.stops,a,f=this.dataClasses,g,d;if(f)for(d=f.length;d--;){if(g=f[d],a=g.from,c=g.to,(a===void 0||b>=a)&&(c===void 0||b<=c)){e=g.color;if(h)h.dataClass=d;break}}else{this.isLog&&(b=this.val2lin(b));e=1-(this.max-b)/(this.max-this.min);for(d=c.length;d--;)if(e>c[d][0])break;a=c[d]||c[d+1];c=c[d+1]||a;e=1-(c[0]-e)/(c[0]-a[0]||1);e=this.tweenColors(a.color, c.color,e)}return e},tweenColors:function(b,a,e){var c=a.rgba[3]!==1||b.rgba[3]!==1;return b.rgba.length===0||a.rgba.length===0?"none":(c?"rgba(":"rgb(")+Math.round(a.rgba[0]+(b.rgba[0]-a.rgba[0])*(1-e))+","+Math.round(a.rgba[1]+(b.rgba[1]-a.rgba[1])*(1-e))+","+Math.round(a.rgba[2]+(b.rgba[2]-a.rgba[2])*(1-e))+(c?","+(a.rgba[3]+(b.rgba[3]-a.rgba[3])*(1-e)):"")+")"}};a.seriesTypes.solidgauge=a.extendClass(a.seriesTypes.gauge,{type:"solidgauge",bindAxes:function(){var b;a.seriesTypes.gauge.prototype.bindAxes.call(this); b=this.yAxis;a.extend(b,n);b.options.dataClasses&&b.initDataClasses(b.options);b.initStops(b.options)},drawPoints:function(){var b=this,h=b.yAxis,e=h.center,c=b.options,m=b.chart.renderer;a.each(b.points,function(f){var g=f.graphic,d=h.startAngleRad+h.translate(f.y,null,null,null,!0),i=q(r(c.radius,100))*e[2]/200,o=q(r(c.innerRadius,60))*e[2]/200,p=h.toColor(f.y,f),k;if(p!=="none")k=f.color,f.color=p;c.wrap===!1&&(d=Math.max(h.startAngleRad,Math.min(h.endAngleRad,d)));var d=d*180/Math.PI,j=d/(180/ Math.PI),l=h.startAngleRad,d=Math.min(j,l),j=Math.max(j,l);j-d>2*Math.PI&&(j=d+2*Math.PI);i={x:e[0],y:e[1],r:i,innerR:o,start:d,end:j};g?(o=i.d,g.attr({fill:f.color}).animate(i,{step:function(b,c){g.attr("fill",n.tweenColors(a.Color(k),a.Color(p),c.pos))}}),i.d=o):f.graphic=m.arc(i).attr({stroke:c.borderColor||"none","stroke-width":c.borderWidth||0,fill:f.color,"sweep-flag":0}).add(b.group)})},animate:null})})(Highcharts);
'use strict'; /*jshint asi: true*/ var testLib = require('./utils/test-lib') , test = require('tap').test , baseUrl = 'https://raw.github.com/documentcloud/underscore/master/' // Not necessary to shim underscore, but serves as a good test case since it tries very hard to interface with commonJS test('underscore master', function (t) { var shimConfig = { exports: '_' } testLib(t, { name: 'underscore.js' , test: function (t, resolved) { t.equals(typeof resolved().each, 'function', 'shims underscore master') } , asserts: 1 , shimConfig: shimConfig , baseUrl: baseUrl }) });
'use strict'; var fs = require('fs'); var React = require('react'); var ReactBin = require('../ReactBin'); var Markdown = require('../utils').Markdown; var Doc = require('../utils').Doc; var examples = { default: fs.readFileSync(__dirname + '/01-default.js', 'utf-8'), defaultThumb: fs.readFileSync(__dirname + '/01-default-thumb.js', 'utf-8'), defaultTitle: fs.readFileSync(__dirname + '/01-default-title.js', 'utf-8'), a: fs.readFileSync(__dirname + '/02-a.js', 'utf-8'), b: fs.readFileSync(__dirname + '/03-b.js', 'utf-8'), c: fs.readFileSync(__dirname + '/04-c.js', 'utf-8'), d1: fs.readFileSync(__dirname + '/05-d1.js', 'utf-8'), d2: fs.readFileSync(__dirname + '/05-d2.js', 'utf-8'), d3: fs.readFileSync(__dirname + '/05-d3.js', 'utf-8') }; var SliderDoc = React.createClass({ render: function() { return ( <Doc> <h1>Slider</h1> <hr/> <h2>组件介绍</h2> <Markdown>{require('./01-intro.md')}</Markdown> <h2>组件演示</h2> <h3>默认主题</h3> <h4>常规模式</h4> <ReactBin code={examples.default} /> <h4>缩略图模式</h4> <ReactBin code={examples.defaultThumb} /> <h4>显示标题</h4> <ReactBin code={examples.defaultTitle} /> <h3>a 系列主题</h3> <ReactBin code={examples.a} /> <h3>b 系列主题</h3> <ReactBin code={examples.b} /> <h3>c 系列主题</h3> <ReactBin code={examples.c} /> <h3>d 系列主题</h3> <h4>d1 主题</h4> <ReactBin code={examples.d1} /> <h4>d2 主题</h4> <ReactBin code={examples.d2} /> <h4>d3 主题</h4> <ReactBin code={examples.d3} /> </Doc> ); } }); module.exports = SliderDoc;
// @flow import clamp from "clamp-js"; clamp(new HTMLInputElement()); clamp(new HTMLInputElement(), {}); clamp(new HTMLInputElement(), {useNativeClamp: true}); // $ExpectError clamp(new HTMLInputElement(), {useNativeClamp: "nope!"});
define("ace/ext/modelist",["require","exports","module"], function(require, exports, module) { "use strict"; var modes = []; function getModeForPath(path) { var mode = modesByName.text; var fileName = path.split(/[\/\\]/).pop(); for (var i = 0; i < modes.length; i++) { if (modes[i].supportsFile(fileName)) { mode = modes[i]; break; } } return mode; } var Mode = function(name, caption, extensions) { this.name = name; this.caption = caption; this.mode = "ace/mode/" + name; this.extensions = extensions; var re; if (/\^/.test(extensions)) { re = extensions.replace(/\|(\^)?/g, function(a, b){ return "$|" + (b ? "^" : "^.*\\."); }) + "$"; } else { re = "^.*\\.(" + extensions + ")$"; } this.extRe = new RegExp(re, "gi"); }; Mode.prototype.supportsFile = function(filename) { return filename.match(this.extRe); }; var supportedModes = { ABAP: ["abap"], ABC: ["abc"], ActionScript:["as"], ADA: ["ada|adb"], Apache_Conf: ["^htaccess|^htgroups|^htpasswd|^conf|htaccess|htgroups|htpasswd"], AsciiDoc: ["asciidoc|adoc"], Assembly_x86:["asm|a"], AutoHotKey: ["ahk"], BatchFile: ["bat|cmd"], Bro: ["bro"], C_Cpp: ["cpp|c|cc|cxx|h|hh|hpp|ino"], C9Search: ["c9search_results"], Cirru: ["cirru|cr"], Clojure: ["clj|cljs"], Cobol: ["CBL|COB"], coffee: ["coffee|cf|cson|^Cakefile"], ColdFusion: ["cfm"], CSharp: ["cs"], Csound_Document: ["csd"], Csound_Orchestra: ["orc"], Csound_Score: ["sco"], CSS: ["css"], Curly: ["curly"], D: ["d|di"], Dart: ["dart"], Diff: ["diff|patch"], Dockerfile: ["^Dockerfile"], Dot: ["dot"], Drools: ["drl"], Edifact: ["edi"], Eiffel: ["e|ge"], EJS: ["ejs"], Elixir: ["ex|exs"], Elm: ["elm"], Erlang: ["erl|hrl"], Forth: ["frt|fs|ldr|fth|4th"], Fortran: ["f|f90"], FTL: ["ftl"], Gcode: ["gcode"], Gherkin: ["feature"], Gitignore: ["^.gitignore"], Glsl: ["glsl|frag|vert"], Gobstones: ["gbs"], golang: ["go"], GraphQLSchema: ["gql"], Groovy: ["groovy"], HAML: ["haml"], Handlebars: ["hbs|handlebars|tpl|mustache"], Haskell: ["hs"], Haskell_Cabal: ["cabal"], haXe: ["hx"], Hjson: ["hjson"], HTML: ["html|htm|xhtml|vue|we|wpy"], HTML_Elixir: ["eex|html.eex"], HTML_Ruby: ["erb|rhtml|html.erb"], INI: ["ini|conf|cfg|prefs"], Io: ["io"], Jack: ["jack"], Jade: ["jade|pug"], Java: ["java"], JavaScript: ["js|jsm|jsx"], JSON: ["json"], JSONiq: ["jq"], JSP: ["jsp"], JSSM: ["jssm|jssm_state"], JSX: ["jsx"], Julia: ["jl"], Kotlin: ["kt|kts"], LaTeX: ["tex|latex|ltx|bib"], LESS: ["less"], Liquid: ["liquid"], Lisp: ["lisp"], LiveScript: ["ls"], LogiQL: ["logic|lql"], LSL: ["lsl"], Lua: ["lua"], LuaPage: ["lp"], Lucene: ["lucene"], Makefile: ["^Makefile|^GNUmakefile|^makefile|^OCamlMakefile|make"], Markdown: ["md|markdown"], Mask: ["mask"], MATLAB: ["matlab"], Maze: ["mz"], MEL: ["mel"], MIXAL: ["mixal"], MUSHCode: ["mc|mush"], MySQL: ["mysql"], Nix: ["nix"], NSIS: ["nsi|nsh"], ObjectiveC: ["m|mm"], OCaml: ["ml|mli"], Pascal: ["pas|p"], Perl: ["pl|pm"], pgSQL: ["pgsql"], PHP: ["php|phtml|shtml|php3|php4|php5|phps|phpt|aw|ctp|module"], Pig: ["pig"], Powershell: ["ps1"], Praat: ["praat|praatscript|psc|proc"], Prolog: ["plg|prolog"], Properties: ["properties"], Protobuf: ["proto"], Python: ["py"], R: ["r"], Razor: ["cshtml|asp"], RDoc: ["Rd"], Red: ["red|reds"], RHTML: ["Rhtml"], RST: ["rst"], Ruby: ["rb|ru|gemspec|rake|^Guardfile|^Rakefile|^Gemfile"], Rust: ["rs"], SASS: ["sass"], SCAD: ["scad"], Scala: ["scala"], Scheme: ["scm|sm|rkt|oak|scheme"], SCSS: ["scss"], SH: ["sh|bash|^.bashrc"], SJS: ["sjs"], Smarty: ["smarty|tpl"], snippets: ["snippets"], Soy_Template:["soy"], Space: ["space"], SQL: ["sql"], SQLServer: ["sqlserver"], Stylus: ["styl|stylus"], SVG: ["svg"], Swift: ["swift"], Tcl: ["tcl"], Tex: ["tex"], Text: ["txt"], Textile: ["textile"], Toml: ["toml"], TSX: ["tsx"], Twig: ["twig|swig"], Typescript: ["ts|typescript|str"], Vala: ["vala"], VBScript: ["vbs|vb"], Velocity: ["vm"], Verilog: ["v|vh|sv|svh"], VHDL: ["vhd|vhdl"], Wollok: ["wlk|wpgm|wtest"], XML: ["xml|rdf|rss|wsdl|xslt|atom|mathml|mml|xul|xbl|xaml"], XQuery: ["xq"], YAML: ["yaml|yml"], Django: ["html"] }; var nameOverrides = { ObjectiveC: "Objective-C", CSharp: "C#", golang: "Go", C_Cpp: "C and C++", Csound_Document: "Csound Document", Csound_Orchestra: "Csound", Csound_Score: "Csound Score", coffee: "CoffeeScript", HTML_Ruby: "HTML (Ruby)", HTML_Elixir: "HTML (Elixir)", FTL: "FreeMarker" }; var modesByName = {}; for (var name in supportedModes) { var data = supportedModes[name]; var displayName = (nameOverrides[name] || name).replace(/_/g, " "); var filename = name.toLowerCase(); var mode = new Mode(filename, displayName, data[0]); modesByName[filename] = mode; modes.push(mode); } module.exports = { getModeForPath: getModeForPath, modes: modes, modesByName: modesByName }; }); (function() { window.require(["ace/ext/modelist"], function() {}); })();
var assert = require("assert"); var file = require('../file-system'); var fs = require('fs'); var path = require('path'); function getPath(filepath) { return path.join(__dirname, filepath); } function checkPermission(filepath, mask) { var stat = fs.statSync(filepath); var mode = mask & parseInt((stat.mode & parseInt ("777", 8)).toString (8)[0]); return !!mode; } describe('mkdir', function() { it('one level Directory', function(done) { file.mkdir(getPath('var/mkdir'), function(err) { if (err) throw err; var exists = fs.existsSync(getPath('var/mkdir')); assert.equal(true, exists); done(); }); }); it('multiple level Directory', function(done) { file.mkdir(getPath('var/mkdir/1/2/3/4'), function(err) { if (err) throw err; var exists = fs.existsSync(getPath('var/mkdir/1/2/3/4')); assert.equal(true, exists); done(); }); }); it('file mode', function(done) { // 7 = 4+2+1 (read/write/execute) // 6 = 4+2 (read/write) // 5 = 4+1 (read/execute) // 4 = 4 (read) // 3 = 2+1 (write/execute) // 2 = 2 (write) // 1 = 1 (execute) fs.mkdir(getPath('var/mkdir/mode'), 511, function(err) { if (err) throw err; assert.equal(true, checkPermission(getPath('var/mkdir/mode'), 4)); done(); }); fs.mkdir(getPath('var/mkdir/mode2'), 111, function(err) { if (err) throw err; assert.equal(false, checkPermission(getPath('var/mkdir/mode2'), 4)); }); }); it('callback', function(done) { var a; fs.mkdir(getPath('var/mkdir/callback'), function(err) { a = 1; assert.equal(a, 1); done(); }); }); after(function() { file.chmodSync(getPath('var/mkdir/mode2'), 511); file.rmdirSync(getPath('var/mkdir')); }); });
module("Exhibit.Database._RangeIndex"); test("prototype", function() { //expect(); }); test("getCount", function() { //expect(); }); test("getMin", function() { //expect(); }); test("getMax", function() { //expect(); }); test("getRange", function() { //expect(); }); test("getSubjectsInRange", function() { //expect(); }); test("countRange", function() { //expect(); }); test("_indexOf", function() { //expect(); });
module.exports = { env: { es6: true }, parserOptions: { ecmaVersion: 6, sourceType: 'module' }, plugins: [ 'import' ], settings: { 'import/resolver': { node: { extensions: ['.js', '.json'] } }, 'import/extensions': [ '.js', '.jsx', ], 'import/core-modules': [ ], 'import/ignore': [ 'node_modules', '\\.(coffee|scss|css|less|hbs|svg|json)$', ], }, rules: { // Static analysis: // ensure imports point to files/modules that can be resolved // https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/no-unresolved.md 'import/no-unresolved': ['error', { commonjs: true, caseSensitive: true }], // ensure named imports coupled with named exports // https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/named.md#when-not-to-use-it 'import/named': 'off', // ensure default import coupled with default export // https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/default.md#when-not-to-use-it 'import/default': 'off', // https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/namespace.md 'import/namespace': 'off', // Helpful warnings: // disallow invalid exports, e.g. multiple defaults // https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/export.md 'import/export': 'error', // do not allow a default import name to match a named export // https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/no-named-as-default.md 'import/no-named-as-default': 'error', // warn on accessing default export property names that are also named exports // https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/no-named-as-default-member.md 'import/no-named-as-default-member': 'error', // disallow use of jsdoc-marked-deprecated imports // https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/no-deprecated.md 'import/no-deprecated': 'off', // Forbid the use of extraneous packages // https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/no-extraneous-dependencies.md // paths are treated both as absolute paths, and relative to process.cwd() 'import/no-extraneous-dependencies': ['error', { devDependencies: ['spec/**', 'test/**', 'tests/**', '**/__tests__/**'], optionalDependencies: false, }], // Forbid mutable exports // https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/no-mutable-exports.md 'import/no-mutable-exports': 'error', // Module systems: // disallow require() // https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/no-commonjs.md 'import/no-commonjs': 'off', // disallow AMD require/define // https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/no-amd.md 'import/no-amd': 'error', // No Node.js builtin modules // https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/no-nodejs-modules.md // TODO: enable? 'import/no-nodejs-modules': 'off', // Style guide: // disallow non-import statements appearing before import statements // https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/first.md 'import/first': ['error', 'absolute-first'], // disallow non-import statements appearing before import statements // https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/imports-first.md // deprecated: use `import/first` 'import/imports-first': 'off', // disallow duplicate imports // https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/no-duplicates.md 'import/no-duplicates': 'error', // disallow namespace imports // TODO: enable? // https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/no-namespace.md 'import/no-namespace': 'off', // Ensure consistent use of file extension within the import path // https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/extensions.md 'import/extensions': ['error', 'always', { js: 'never', jsx: 'never', }], // Enforce a convention in module import order // https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/order.md // TODO: enable? 'import/order': ['off', { groups: ['builtin', 'external', 'internal', 'parent', 'sibling', 'index'], 'newlines-between': 'never', }], // Require a newline after the last import/require in a group // https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/newline-after-import.md 'import/newline-after-import': 'error', // Require modules with a single export to use a default export // https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/prefer-default-export.md 'import/prefer-default-export': 'error', // Restrict which files can be imported in a given folder // https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/no-restricted-paths.md 'import/no-restricted-paths': 'off', // Forbid modules to have too many dependencies // https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/max-dependencies.md 'import/max-dependencies': ['off', { max: 10 }], // Forbid import of modules using absolute paths // https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/no-absolute-path.md 'import/no-absolute-path': 'error', // Forbid require() calls with expressions // https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/no-dynamic-require.md 'import/no-dynamic-require': 'error', // prevent importing the submodules of other modules // https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/no-internal-modules.md 'import/no-internal-modules': ['off', { allow: [], }], // Warn if a module could be mistakenly parsed as a script by a consumer // leveraging Unambiguous JavaScript Grammar // https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/unambiguous.md // this should not be enabled until this proposal has at least been *presented* to TC39. // At the moment, it's not a thing. 'import/unambiguous': 'off', // Forbid Webpack loader syntax in imports // https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/no-webpack-loader-syntax.md 'import/no-webpack-loader-syntax': 'error', // Prevent unassigned imports // https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/no-unassigned-import.md // importing for side effects is perfectly acceptable, if you need side effects. 'import/no-unassigned-import': 'off', // Prevent importing the default as if it were named // https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/no-named-default.md 'import/no-named-default': 'error', }, };
'use strict'; //basic configuration object used by gulp tasks module.exports = { port: 3000, uiPort: 3001, tmp: 'build/tmp', dist: 'build/dist', base: 'client', tpl: 'client/src/**/*.tpl.html', mainScss: 'client/src/scss/main.scss', scss: 'client/src/scss/**/*.scss', js: [ 'client/src/**/*.js', '!client/src/vendor/**/*.js', 'client/test/unit/**/*.js', 'client/test/e2e/**/*.js' ], index: 'client/index.html', assets: 'client/assets/**', images: 'client/assets/images/**/*', banner: ['/**', ' * <%= pkg.name %> - <%= pkg.description %>', ' * @version v<%= pkg.version %>', ' * @link <%= pkg.homepage %>', ' * @license <%= pkg.license %>', ' */', '' ].join('\n') };
"use strict"; /** * @license * Copyright 2017 Palantir Technologies, Inc. * * 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. */ Object.defineProperty(exports, "__esModule", { value: true }); var tslib_1 = require("tslib"); var tsutils_1 = require("tsutils"); var Lint = require("../index"); var Rule = /** @class */ (function (_super) { tslib_1.__extends(Rule, _super); function Rule() { return _super !== null && _super.apply(this, arguments) || this; } /* tslint:enable:object-literal-sort-keys */ Rule.FAILURE_STRING = function (moduleReference) { return "No need to reference \"" + moduleReference + "\", since it is imported."; }; Rule.prototype.apply = function (sourceFile) { return this.applyWithFunction(sourceFile, walk); }; /* tslint:disable:object-literal-sort-keys */ Rule.metadata = { ruleName: "no-reference-import", description: 'Don\'t `<reference types="foo" />` if you import `foo` anyway.', optionsDescription: "Not configurable.", options: null, type: "style", typescriptOnly: true, }; return Rule; }(Lint.Rules.AbstractRule)); exports.Rule = Rule; function walk(ctx) { if (ctx.sourceFile.typeReferenceDirectives.length === 0) { return; } var imports = new Set(tsutils_1.findImports(ctx.sourceFile, 3 /* AllStaticImports */).map(function (name) { return name.text; })); for (var _i = 0, _a = ctx.sourceFile.typeReferenceDirectives; _i < _a.length; _i++) { var ref = _a[_i]; if (imports.has(ref.fileName)) { ctx.addFailure(ref.pos, ref.end, Rule.FAILURE_STRING(ref.fileName)); } } }
(function ($) { // register namespace $.extend(true, window, { "Slick": { "CellSelectionModel": CellSelectionModel } }); function CellSelectionModel(options) { var _grid; var _canvas; var _ranges = []; var _self = this; var _selector = new Slick.CellRangeSelector({ "selectionCss": { "border": "2px solid black" } }); var _options; var _defaults = { selectActiveCell: true }; function init(grid) { _options = $.extend(true, {}, _defaults, options); _grid = grid; _canvas = _grid.getCanvasNode(); _grid.onActiveCellChanged.subscribe(handleActiveCellChange); _grid.onKeyDown.subscribe(handleKeyDown); grid.registerPlugin(_selector); _selector.onCellRangeSelected.subscribe(handleCellRangeSelected); _selector.onBeforeCellRangeSelected.subscribe(handleBeforeCellRangeSelected); } function destroy() { _grid.onActiveCellChanged.unsubscribe(handleActiveCellChange); _grid.onKeyDown.unsubscribe(handleKeyDown); _selector.onCellRangeSelected.unsubscribe(handleCellRangeSelected); _selector.onBeforeCellRangeSelected.unsubscribe(handleBeforeCellRangeSelected); _grid.unregisterPlugin(_selector); } function removeInvalidRanges(ranges) { var result = []; for (var i = 0; i < ranges.length; i++) { var r = ranges[i]; if (_grid.canCellBeSelected(r.fromRow, r.fromCell) && _grid.canCellBeSelected(r.toRow, r.toCell)) { result.push(r); } } return result; } function setSelectedRanges(ranges) { _ranges = removeInvalidRanges(ranges); _self.onSelectedRangesChanged.notify(_ranges); } function getSelectedRanges() { return _ranges; } function handleBeforeCellRangeSelected(e, args) { if (_grid.getEditorLock().isActive()) { e.stopPropagation(); return false; } } function handleCellRangeSelected(e, args) { setSelectedRanges([args.range]); } function handleActiveCellChange(e, args) { if (_options.selectActiveCell && args.row != null && args.cell != null) { setSelectedRanges([new Slick.Range(args.row, args.cell)]); } } function handleKeyDown(e) { /*** * Кey codes * 37 left * 38 up * 39 right * 40 down */ var ranges, last; var active = _grid.getActiveCell(); if ( active && e.shiftKey && !e.ctrlKey && !e.altKey && (e.which == 37 || e.which == 39 || e.which == 38 || e.which == 40) ) { ranges = getSelectedRanges(); if (!ranges.length) ranges.push(new Slick.Range(active.row, active.cell)); // keyboard can work with last range only last = ranges.pop(); // can't handle selection out of active cell if (!last.contains(active.row, active.cell)) last = new Slick.Range(active.row, active.cell); var dRow = last.toRow - last.fromRow, dCell = last.toCell - last.fromCell, // walking direction dirRow = active.row == last.fromRow ? 1 : -1, dirCell = active.cell == last.fromCell ? 1 : -1; if (e.which == 37) { dCell -= dirCell; } else if (e.which == 39) { dCell += dirCell ; } else if (e.which == 38) { dRow -= dirRow; } else if (e.which == 40) { dRow += dirRow; } // define new selection range var new_last = new Slick.Range(active.row, active.cell, active.row + dirRow*dRow, active.cell + dirCell*dCell); if (removeInvalidRanges([new_last]).length) { ranges.push(new_last); _grid.scrollRowIntoView(dirRow > 0 ? new_last.toRow : new_last.fromRow); _grid.scrollCellIntoView(new_last.fromRow, dirCell > 0 ? new_last.toCell : new_last.fromCell); } else ranges.push(last); setSelectedRanges(ranges); e.preventDefault(); e.stopPropagation(); } } $.extend(this, { "getSelectedRanges": getSelectedRanges, "setSelectedRanges": setSelectedRanges, "init": init, "destroy": destroy, "onSelectedRangesChanged": new Slick.Event() }); } })(jQuery);
var BASIC = [ { }, { "image": [ {"shape": "rect", "fill": "#333", "stroke": "#999", "x": 0.5, "y": 0.5, "width": 47, "height": 47} ], "jumpable": 3, "solid": { "1": [2,4], "2": [], "3": [2,6], "4": [], "5": [2,8,1,3,7,9,4,6], "6": [], "7": [4,8], "8": [], "9": [6,8] }, "corners": {"1": true,"3": true,"7": true,"9": true} }, { "image": [ {"shape": "polygon", "fill": "#248", "stroke": "#48f", "points": [[0.5,47.5],[47.5,47.5],[47.5,0.5]]} ], "solid": { "1": [2,4], "2": [1], "3": [2], "4": [], "5": [2,8,1,3,7,9,4,6], "6": [], "7": [4,8], "8": [], "9": [6,8] }, "corners": {"1": true,"3": true,"7": false,"9": true} }, { "image": [ {"shape": "polygon", "fill": "#248", "stroke": "#48f", "points": [[0.5,0.5],[47.5,47.5],[0.5,47.5]]} ], "solid": { "1": [2], "2": [3], "3": [2,6], "4": [], "5": [2,8,1,3,7,9,4,6], "6": [], "7": [4,8], "8": [], "9": [6,8] }, "corners": {"1": true,"3": true,"7": true,"9": false} }, { "image": [ {"shape": "polygon", "fill": "#333", "stroke": "#999", "points": [[0.5,0.5],[47.5,47.5],[47.5,0.5]]} ], "jumpable": 3, "solid": { "1": [2,4], "2": [], "3": [2,6], "4": [], "5": [2,8,1,3,7,9,4,6], "6": [3], "7": [4,8], "8": [7], "9": [6,8] }, "corners": {"1": false,"3": true,"7": true,"9": true} }, { "image": [ {"shape": "polygon", "fill": "#333", "stroke": "#999", "points": [[0.5,0.5],[0.5,47.5],[47.5,0.5]]} ], "jumpable": 3, "solid": { "1": [2,4], "2": [], "3": [2,6], "4": [1], "5": [2,8,1,3,7,9,4,6], "6": [], "7": [4,8], "8": [9], "9": [6,8] }, "corners": {"1": true,"3": false,"7": true,"9": true} }, { "image": [ {"shape": "polygon", "fill": "#482", "stroke": "#8f4", "points": [[0.5,47.5],[0.5,23.5],[24.5,23.5],[24.5,0.5],[47.5,0.5],[47.5,47.5]]} ], "jumpable": 3, "solid": { "1": [2,4], "2": [], "3": [6,2], "4": [], "5": [2,8,1,3,7,9,4,6], "6": [9], "7": [4,8], "8": [], "9": [6,8] }, "corners": {"1": true,"3": true,"7": false,"9": true} }, { "image": [ {"shape": "polygon", "fill": "#482", "stroke": "#8f4", "points": [[0.5,0.5],[23.5,0.5],[23.5,24.5],[47.5,24.5],[47.5,47.5],[0.5,47.5]]} ], "jumpable": 3, "solid": { "1": [4,2], "2": [], "3": [2,6], "4": [7], "5": [2,8,1,3,7,9,4,6], "6": [], "7": [4,8], "8": [], "9": [6,8] }, "corners": {"1": true,"3": true,"7": true,"9": false} }, { "image": [ {"shape": "circle", "fill": "#ff0", "stroke": "#ff8", "cx": 24, "cy": 24, "r": 18} ], "item": true }, { "image": [ {"shape": "polygon", "fill": "#842", "stroke": "#f84", "points": [[4.5,0.5],[14.5,0.5],[14.5,17.5],[34,17.5],[33.5,0.5],[43.5,0.5],[43.5,47.5],[33.5,47.5],[33.5,30.5],[14.5,30.5],[14.5,47.5],[4.5,47.5]]} ], "jumpable": 3 }, { "image": [ {"shape": "polygon", "fill": "#333", "stroke": "#999", "points": [[0.5,0.5],[47.5,0.5],[24,47.5]]} ], "jumpable": 3, "solid": { "1": [2,4], "2": [], "3": [2,6], "4": [1], "5": [2,8,1,3,7,9,4,6], "6": [3], "7": [4,8], "8": [], "9": [6,8] }, "corners": {"1": false,"3": false,"7": true,"9": true} }, { "image": [ {"shape": "rect", "fill": "#114acb", "x": 0.5, "y": 0.5, "width": 47, "height": 47}, {"shape": "polygon", "fill": "rgba(255,255,255,0.30)", "points": [[0.5,0.5],[47.5,0.5],[40,8],[8,8],[8,40],[0.5,47.5]]}, {"shape": "polygon", "fill": "rgba(0,0,0,0.30)", "points": [[47.5,0.5],[48,48],[0.5,47.5],[8,40],[40,40],[40,8]]}, {"shape": "polygon", "fill": "rgb(255,255,0)", "stroke": "rgba(255,255,0,0.5)", "points": [[24,9],[35,20],[26,29],[26,33],[22,33],[22,27],[29,20],[24,15],[16,23],[13,20]]}, {"shape": "rect", "fill": "rgb(255,255,0)", "stroke": "rgba(255,255,0,0.5)", "x": 22, "y":35, "width": 4, "height": 4} ], "item": true }, { "image": [ {"shape": "circle", "fill": "#80f", "stroke": "#88f", "cx": 24, "cy": 24, "r": 18} ], "item": true }, { "image": [ {"shape": "circle", "fill": "#4f4", "stroke": "#8f8", "cx": 24, "cy": 24, "r": 18} ], "item": true } ]
// resources(89): // [FunctionExpression] ../../src/basis/data/dataset/Merge.js -> 1m.js // [FunctionExpression] ../../src/basis/devpanel.js -> 0.js // [FunctionExpression] ../../src/basis/ui.js -> 2.js // [FunctionExpression] ../../src/basis/event.js -> 3.js // [FunctionExpression] ../../src/basis/template/html.js -> 4.js // [FunctionExpression] ../../src/basis/l10n.js -> 5.js // [FunctionExpression] ../../src/basis/utils/json-parser.js -> 12.js // [FunctionExpression] ../../src/basis/template/htmlfgen.js -> 6.js // [FunctionExpression] ../../src/basis/template/const.js -> 7.js // [FunctionExpression] ../../src/basis/template/namespace.js -> 8.js // [FunctionExpression] ../../src/basis/template.js -> 9.js // [FunctionExpression] ../../src/basis/template/declaration.js -> a.js // [FunctionExpression] ../../src/basis/template/tokenize.js -> 13.js // [FunctionExpression] ../../src/basis/template/isolateCss.js -> 14.js // [FunctionExpression] ../../src/basis/template/declaration/utils.js -> 15.js // [FunctionExpression] ../../src/basis/template/declaration/refs.js -> 16.js // [FunctionExpression] ../../src/basis/template/declaration/ast.js -> 17.js // [FunctionExpression] ../../src/basis/template/declaration/style.js -> 18.js // [FunctionExpression] ../../src/basis/template/declaration/attr.js -> 19.js // [FunctionExpression] ../../src/basis/template/declaration/element/b-content.js -> 1a.js // [FunctionExpression] ../../src/basis/template/declaration/element/b-define.js -> 1b.js // [FunctionExpression] ../../src/basis/template/declaration/element/b-include.js -> 1c.js // [FunctionExpression] ../../src/basis/template/declaration/element/b-isolate.js -> 1d.js // [FunctionExpression] ../../src/basis/template/declaration/element/b-l10n.js -> 1e.js // [FunctionExpression] ../../src/basis/template/declaration/element/b-style.js -> 1f.js // [FunctionExpression] ../../src/basis/template/declaration/element/b-svg.js -> 1g.js // [FunctionExpression] ../../src/basis/template/declaration/element/b-text.js -> 1h.js // [FunctionExpression] ../../src/basis/template/store.js -> b.js // [FunctionExpression] ../../src/basis/template/theme.js -> c.js // [FunctionExpression] ../../src/basis/template/buildDom.js -> d.js // [FunctionExpression] ../../src/basis/dom/event.js -> e.js // [FunctionExpression] ../../src/basis/dom/wrapper.js -> f.js // [FunctionExpression] ../../src/basis/data.js -> g.js // [FunctionExpression] ../../src/basis/data/state.js -> h.js // [FunctionExpression] ../../src/basis/data/subscription.js -> i.js // [FunctionExpression] ../../src/basis/data/resolve.js -> j.js // [FunctionExpression] ../../src/basis/data/AbstractData.js -> 1i.js // [FunctionExpression] ../../src/basis/dragdrop.js -> k.js // [FunctionExpression] ../../src/basis/dom/computedStyle.js -> l.js // [FunctionExpression] ../../src/basis/layout.js -> m.js // [FunctionExpression] ../../src/basis/data/dataset.js -> n.js // [FunctionExpression] ../../src/basis/data/dataset/getDelta.js -> 1j.js // [FunctionExpression] ../../src/basis/data/dataset/createRuleEvents.js -> 1k.js // [FunctionExpression] ../../src/basis/data/dataset/SourceDataset.js -> 1l.js // [FunctionExpression] library.js -> 1.js // [FunctionExpression] ../../src/basis/data/dataset/Subtract.js -> 1n.js // [FunctionExpression] ../../src/basis/data/dataset/MapFilter.js -> 1o.js // [FunctionExpression] ../../src/basis/data/dataset/Split.js -> 1p.js // [FunctionExpression] ../../src/basis/data/dataset/createKeyMap.js -> 1q.js // [FunctionExpression] ../../src/basis/data/dataset/Cloud.js -> 1r.js // [FunctionExpression] ../../src/basis/data/dataset/Extract.js -> 1s.js // [FunctionExpression] ../../src/basis/data/dataset/Filter.js -> 1t.js // [FunctionExpression] ../../src/basis/data/dataset/Slice.js -> 1u.js // [FunctionExpression] ../../src/basis/data/value.js -> o.js // [FunctionExpression] ../../src/basis/data/ObjectSet.js -> 1v.js // [FunctionExpression] ../../src/basis/data/Expression.js -> 1w.js // [FunctionExpression] ../../src/basis/data/index.js -> p.js // [FunctionExpression] ../../src/basis/data/index/Index.js -> 1x.js // [FunctionExpression] ../../src/basis/data/index/VectorIndex.js -> 1y.js // [FunctionExpression] ../../src/basis/data/index/IndexWrapper.js -> 1z.js // [FunctionExpression] ../../src/basis/data/index/IndexMap.js -> 20.js // [FunctionExpression] ../../src/basis/data/index/IndexedCalc.js -> 21.js // [FunctionExpression] ../../src/basis/data/index/constructor.js -> 22.js // [FunctionExpression] ../../src/basis/data/index/Count.js -> 23.js // [FunctionExpression] ../../src/basis/data/index/Sum.js -> 24.js // [FunctionExpression] ../../src/basis/data/index/Avg.js -> 25.js // [FunctionExpression] ../../src/basis/data/index/Min.js -> 26.js // [FunctionExpression] ../../src/basis/data/index/Max.js -> 27.js // [FunctionExpression] ../../src/basis/data/index/Distinct.js -> 28.js // [FunctionExpression] ../../src/basis/data/object.js -> q.js // [FunctionExpression] ../../src/basis/entity.js -> r.js // [FunctionExpression] ../../src/basis/type.js -> s.js // [FunctionExpression] ../../src/basis/type/string.js -> 29.js // [FunctionExpression] ../../src/basis/type/number.js -> 2a.js // [FunctionExpression] ../../src/basis/type/int.js -> 2b.js // [FunctionExpression] ../../src/basis/type/enum.js -> 2c.js // [FunctionExpression] ../../src/basis/type/array.js -> 2d.js // [FunctionExpression] ../../src/basis/type/object.js -> 2e.js // [FunctionExpression] ../../src/basis/type/date.js -> 2f.js // [FunctionExpression] ../../src/basis/net/jsonp.js -> t.js // [FunctionExpression] ../../src/basis/net.js -> u.js // [FunctionExpression] ../../src/basis/net/service.js -> v.js // [FunctionExpression] ../../src/basis/net/ajax.js -> w.js // [FunctionExpression] ../../src/basis/ua.js -> x.js // [FunctionExpression] ../../src/basis/net/action.js -> y.js // [FunctionExpression] ../../src/basis/promise.js -> z.js // [FunctionExpression] ../../src/basis/router.js -> 10.js // [FunctionExpression] ../../src/basis/router/ast.js -> 2g.js // [FunctionExpression] ../../src/basis/app.js -> 11.js // // filelist(1): // /scripts/release-configs/library.js // (function(){ "use strict"; var __namespace_map__ = {"0.js":"basis.devpanel","1.js":"library","2.js":"basis.ui","3.js":"basis.event","4.js":"basis.template.html","5.js":"basis.l10n","6.js":"basis.template.htmlfgen","7.js":"basis.template.const","8.js":"basis.template.namespace","9.js":"basis.template","a.js":"basis.template.declaration","b.js":"basis.template.store","c.js":"basis.template.theme","d.js":"basis.template.buildDom","e.js":"basis.dom.event","f.js":"basis.dom.wrapper","g.js":"basis.data","h.js":"basis.data.state","i.js":"basis.data.subscription","j.js":"basis.data.resolve","k.js":"basis.dragdrop","l.js":"basis.dom.computedStyle","m.js":"basis.layout","n.js":"basis.data.dataset","o.js":"basis.data.value","p.js":"basis.data.index","q.js":"basis.data.object","r.js":"basis.entity","s.js":"basis.type","t.js":"basis.net.jsonp","u.js":"basis.net","v.js":"basis.net.service","w.js":"basis.net.ajax","x.js":"basis.ua","y.js":"basis.net.action","z.js":"basis.promise","10.js":"basis.router","11.js":"basis.app"}; var library; var __resources__ = { "1m.js": function (exports, module, basis, global, __filename, __dirname, require, resource, asset) { var arrayAdd = basis.array.add; var arrayRemove = basis.array.remove; var createEvent = basis.require("./3.js").create; var Emitter = basis.require("./3.js").Emitter; var resolveDataset = basis.require("./g.js").resolveDataset; var ReadOnlyDataset = basis.require("./g.js").ReadOnlyDataset; var getDelta = basis.require("./1j.js"); var SUBSCRIPTION = basis.require("./i.js"); SUBSCRIPTION.add("SOURCES", { sourcesChanged: function (object, delta) { var array; if (array = delta.inserted) for (var i = 0, item; item = array[i]; i++) SUBSCRIPTION.link("source", object, item); if (array = delta.deleted) for (var i = 0, item; item = array[i]; i++) SUBSCRIPTION.unlink("source", object, item); } }, function (action, object) { var sources = object.sources; for (var i = 0, source; source = sources[i++];) action("source", object, source); }); var UNION = function (count) { return count > 0; }; var INTERSECTION = function (count, sourceCount) { return count == sourceCount; }; var DIFFERENCE = function (count) { return count == 1; }; var MORE_THAN_ONE_INCLUDE = function (count, sourceCount) { return sourceCount == 1 || count > 1; }; var AT_LEAST_ONE_EXCLUDE = function (count, sourceCount) { return sourceCount == 1 || count < sourceCount; }; var MERGE_DATASET_HANDLER = { itemsChanged: function (source, delta) { var memberMap = this.members_; var updated = {}; var object; var objectId; if (delta.inserted) { for (var i = 0; object = delta.inserted[i]; i++) { objectId = object.basisObjectId; if (memberMap[objectId]) { memberMap[objectId].count++; } else { memberMap[objectId] = { count: 1, isMember: false, object: object }; } updated[objectId] = memberMap[objectId]; } } if (delta.deleted) { for (var i = 0; object = delta.deleted[i]; i++) { objectId = object.basisObjectId; updated[objectId] = memberMap[objectId]; memberMap[objectId].count--; } } this.applyRule(updated); } }; var Merge = ReadOnlyDataset.subclass({ className: "basis.data.dataset.Merge", propertyDescriptors: { rule: "ruleChanged" }, active: basis.PROXY, subscribeTo: SUBSCRIPTION.SOURCES, emit_sourcesChanged: createEvent("sourcesChanged", "delta"), sources: null, sourceValues_: null, sourcesMap_: null, sourceDelta_: null, rule: UNION, emit_ruleChanged: createEvent("ruleChanged", "oldRule"), listen: { source: MERGE_DATASET_HANDLER, sourceValue: { destroy: function (sender) { this.removeSource(sender); } } }, init: function () { ReadOnlyDataset.prototype.init.call(this); var sources = this.sources; this.sources = []; this.sourcesMap_ = {}; this.sourceValues_ = []; if (sources) this.setSources(sources); }, setRule: function (rule) { rule = basis.getter(rule || UNION); if (this.rule !== rule) { var oldRule = this.rule; this.rule = rule; this.emit_ruleChanged(oldRule); return this.applyRule(); } }, applyRule: function (scope) { var memberMap = this.members_; var rule = this.rule; var sourceCount = this.sources.length; var inserted = []; var deleted = []; var memberCounter; var isMember; var delta; if (!scope) scope = memberMap; for (var objectId in scope) { memberCounter = memberMap[objectId]; isMember = sourceCount && memberCounter.count && rule(memberCounter.count, sourceCount); if (isMember != memberCounter.isMember) { if (isMember) { memberCounter.isMember = true; inserted.push(memberCounter.object); } else { memberCounter.isMember = false; deleted.push(memberCounter.object); } } if (memberCounter.count == 0) delete memberMap[objectId]; } if (delta = getDelta(inserted, deleted)) this.emit_itemsChanged(delta); return delta; }, addDataset_: function (dataset) { this.sources.push(dataset); if (this.listen.source) dataset.addHandler(this.listen.source, this); var memberMap = this.members_; for (var objectId in dataset.items_) { if (memberMap[objectId]) { memberMap[objectId].count++; } else { memberMap[objectId] = { count: 1, isMember: false, object: dataset.items_[objectId] }; } } return true; }, removeDataset_: function (dataset) { arrayRemove(this.sources, dataset); if (this.listen.source) dataset.removeHandler(this.listen.source, this); var memberMap = this.members_; for (var objectId in dataset.items_) memberMap[objectId].count--; }, updateDataset_: function (source) { var merge = this.owner; var sourcesMap_ = merge.sourcesMap_; var dataset = resolveDataset(this, merge.updateDataset_, source, "adapter", merge); var inserted; var deleted; var delta; if (this.dataset === dataset) return; if (dataset) { var count = (sourcesMap_[dataset.basisObjectId] || 0) + 1; sourcesMap_[dataset.basisObjectId] = count; if (count == 1) { merge.addDataset_(dataset); inserted = [dataset]; } } if (this.dataset) { var count = (sourcesMap_[this.dataset.basisObjectId] || 0) - 1; sourcesMap_[this.dataset.basisObjectId] = count; if (count == 0) { merge.removeDataset_(this.dataset); deleted = [this.dataset]; } } this.dataset = dataset; merge.applyRule(); if (delta = getDelta(inserted, deleted)) { var setSourcesTransaction = merge.sourceDelta_; if (setSourcesTransaction) { if (delta.inserted) delta.inserted.forEach(function (item) { if (!arrayRemove(this.deleted, item)) arrayAdd(this.inserted, item); }, setSourcesTransaction); if (delta.deleted) delta.deleted.forEach(function (item) { if (!arrayRemove(this.inserted, item)) arrayAdd(this.deleted, item); }, setSourcesTransaction); } else { merge.emit_sourcesChanged(delta); } } return delta; }, getSourceValues: function () { return this.sourceValues_.map(function (item) { return item.source; }); }, addSource: function (source) { if (!source || typeof source != "object" && typeof source != "function") { basis.dev.warn(this.constructor.className + ".addSource: value should be a dataset instance or to be able to resolve in dataset"); return; } if (this.hasSource(source)) { basis.dev.warn(this.constructor.className + ".addSource: value is already in source list"); return; } var sourceInfo = { owner: this, source: source, adapter: null, dataset: null }; this.sourceValues_.push(sourceInfo); this.updateDataset_.call(sourceInfo, source); if (this.listen.sourceValue && source instanceof Emitter) source.addHandler(this.listen.sourceValue, this); }, removeSource: function (source) { for (var i = 0, sourceInfo; sourceInfo = this.sourceValues_[i]; i++) if (sourceInfo.source === source) { if (this.listen.sourceValue && source instanceof Emitter) source.removeHandler(this.listen.sourceValue, this); this.updateDataset_.call(sourceInfo, null); this.sourceValues_.splice(i, 1); return; } basis.dev.warn(this.constructor.className + ".removeSource: source value isn't found in source list"); }, hasSource: function (source) { for (var i = 0, sourceInfo; sourceInfo = this.sourceValues_[i]; i++) if (sourceInfo.source === source) return true; return false; }, setSources: function (sources) { var exists = this.sourceValues_.map(function (sourceInfo) { return sourceInfo.source; }); var inserted = []; var deleted = []; var delta; if (!sources) sources = []; this.sourceDelta_ = { inserted: inserted, deleted: deleted }; for (var i = 0; i < sources.length; i++) { var source = sources[i]; if (!arrayRemove(exists, source)) this.addSource(source); } exists.forEach(this.removeSource, this); this.sourceDelta_ = null; if (delta = getDelta(inserted, deleted)) this.emit_sourcesChanged(delta); return delta; }, destroy: function () { this.setSources(); ReadOnlyDataset.prototype.destroy.call(this); this.sourceValues_ = null; this.sourcesMap_ = null; this.sourceDelta_ = null; this.sources = null; } }); Merge.UNION = UNION; Merge.INTERSECTION = INTERSECTION; Merge.DIFFERENCE = DIFFERENCE; Merge.MORE_THAN_ONE_INCLUDE = MORE_THAN_ONE_INCLUDE; Merge.AT_LEAST_ONE_EXCLUDE = AT_LEAST_ONE_EXCLUDE; module.exports = Merge; }, "0.js": function (exports, module, basis, global, __filename, __dirname, require, resource, asset) { if (basis.filename_) { basis.createSandbox({ inspect: basis, devInfoResolver: basis.config.devInfoResolver, modules: { api: { path: basis.path.resolve(__dirname, "../devpanel/api/index.js") }, type: { path: basis.path.resolve(__dirname, "../devpanel/type/"), filename: "index.js" }, devpanel: { autoload: true, path: basis.path.resolve(__dirname, "../devpanel/"), filename: "index.js" } } }); } }, "2.js": function (exports, module, basis, global, __filename, __dirname, require, resource, asset) { var namespace = "basis.ui"; var document = global.document; var Class = basis.Class; var createEvent = basis.require("./3.js").create; var HtmlTemplate = basis.require("./4.js").Template; var htmlTemplateIdMarker = basis.require("./7.js").MARKER; var TemplateSwitcher = basis.require("./9.js").TemplateSwitcher; var basisDomWrapper = basis.require("./f.js"); var DWNode = basisDomWrapper.Node; var DWPartitionNode = basisDomWrapper.PartitionNode; var DWGroupingNode = basisDomWrapper.GroupingNode; var instances = {}; var notifier = new basis.Token(); var notifyCreateSchedule = basis.asap.schedule(function (instance) { instances[instance.basisObjectId] = instance; notifier.set({ action: "create", instance: instance }); }); var notifyDestroySchedule = basis.asap.schedule(function (instance) { delete instances[instance.basisObjectId]; notifier.set({ action: "destroy", instance: instance }); }); var bindingSeed = 1; var unknownEventBindingCheck = {}; function extendBinding(binding, extension) { var info = basis.dev.getInfo(extension, "map"); binding.bindingId = bindingSeed++; for (var key in extension) { var def = null; var value = extension[key]; if (Node && value instanceof Node || basis.resource.isResource(value)) { def = { events: "satelliteChanged", getter: function (key, satellite) { var resource = typeof satellite == "function" ? satellite : null; var init = function (node) { init = false; if (resource) { satellite = resource(); if (satellite instanceof Node == false) return; resource = null; } node.setSatellite(key, satellite); if (node.satellite[key] !== satellite) basis.dev.warn("basis.ui.binding: implicit satellite `" + key + "` attach to owner failed"); }; return function (node) { if (init) init(node); return resource || (node.satellite[key] ? node.satellite[key].element : null); }; }(key, value) }; } else { if (value) { if (typeof value == "string") value = BINDING_PRESET.process(key, value); else if (value.bindingBridge) value = basis.fn.$const(value); if (typeof value != "object") { def = { getter: typeof value == "function" ? value : basis.getter(value) }; } else if (Array.isArray(value)) { def = { events: value[0], getter: basis.getter(value[1]) }; } else { def = { events: value.events, getter: basis.getter(value.getter) }; } } } if (def && info && info.hasOwnProperty(key)) def.loc = info[key]; binding[key] = def; } } var BINDING_PRESET = function () { var presets = {}; var prefixRegExp = /^([a-z_][a-z0-9_]*):(.*)/i; return { add: function (prefix, func) { if (!presets[prefix]) { presets[prefix] = func; } else { basis.dev.warn("Preset `" + prefix + "` already exists, new definition ignored"); } }, process: function (key, value) { var preset; var m = value.match(prefixRegExp); if (m) { preset = presets[m[1]]; value = m[2] || key; } return preset ? preset(value) : value; } }; }(); BINDING_PRESET.add("data", function (path) { return { events: "update", getter: "data." + path }; }); BINDING_PRESET.add("satellite", function (satelliteName) { return { events: "satelliteChanged", getter: function (node) { return node.satellite[satelliteName] ? node.satellite[satelliteName].element : null; } }; }); var TEMPLATE_BINDING = Class.customExtendProperty({ "$role": { events: "ownerSatelliteNameChanged", getter: function (node) { if (node.role) { var roleId = node.roleId && node.binding[node.roleId]; if (roleId && typeof roleId.getter == "function") { roleId = roleId.getter(node); if (roleId === undefined) return ""; } return node.role + (roleId !== undefined ? "(" + roleId + ")" : ""); } return node.ownerSatelliteName || ""; } }, active: { events: "activeChanged", getter: function (node) { return node.active; } }, state: { events: "stateChanged", getter: function (node) { return String(node.state); } }, childNodesState: { events: "childNodesStateChanged", getter: function (node) { return String(node.childNodesState); } }, childCount: { events: "childNodesModified", getter: function (node) { return node.childNodes ? node.childNodes.length : 0; } }, hasChildren: { events: "childNodesModified", getter: function (node) { return !!node.firstChild; } }, empty: { events: "childNodesModified", getter: function (node) { return !node.firstChild; } } }, extendBinding); var BINDING_TEMPLATE_INTERFACE = { attach: function (object, handler, context) { object.addHandler(handler, context); }, detach: function (object, handler, context) { object.removeHandler(handler, context); } }; var TEMPLATE_ACTION = Class.extensibleProperty({ select: function (event) { if (this.isDisabled()) return; if (this.selectedRA_) { basis.dev.warn("`selected` property is under bb-value and can't be changed by user action. Override `select` action to make your logic working."); return; } if (this.contextSelection && this.contextSelection.multiple) this.select(event.ctrlKey || event.metaKey); else this.select(); } }); var TEMPLATE_SWITCHER_HANDLER = { "*": function (event) { var switcher = this.templateSwitcher_; if (switcher && switcher.ruleEvents && switcher.ruleEvents[event.type]) this.setTemplate(switcher.resolve(this)); } }; var TEMPLATE = new HtmlTemplate("<div/>"); var fragments = []; function getDocumentFragment() { return fragments.pop() || document.createDocumentFragment(); } function reinsertPartitionNodes(partition) { var nodes = partition.nodes; if (nodes) for (var i = nodes.length - 1, child; child = nodes[i]; i--) child.parentNode.insertBefore(child, child.nextSibling); } var focusTimer; var TemplateMixin = function (super_) { return { propertyDescriptors: { action: false, binding: false, template: "templateChanged", tmpl: "templateChanged", element: false, childNodesElement: false }, template: TEMPLATE, emit_templateChanged: createEvent("templateChanged"), templateSwitcher_: null, binding: TEMPLATE_BINDING, action: TEMPLATE_ACTION, tmpl: null, element: null, childNodesElement: null, init: function () { this.element = this.childNodesElement = getDocumentFragment(); super_.init.call(this); }, postInit: function () { super_.postInit.call(this); var template = this.template; if (template) { var nodeDocumentFragment = this.childNodesElement; var bindingId = this.constructor.basisClassId_ + "_" + this.binding.bindingId; if (bindingId in unknownEventBindingCheck == false) { unknownEventBindingCheck[bindingId] = true; for (var bindName in this.binding) { var events = this.binding[bindName] && this.binding[bindName].events; if (events) { events = String(events).trim().split(/\s+|\s*,\s*/); for (var i = 0, eventName; eventName = events[i]; i++) if ("emit_" + eventName in this == false) basis.dev.warn("basis.ui: binding `" + bindName + "` has unknown event `" + eventName + "` for " + this.constructor.className); } } } this.template = null; this.setTemplate(template); fragments.push(nodeDocumentFragment); if (this.container) { this.container.appendChild(this.element); this.container = null; } } notifyCreateSchedule.add(this); }, templateSync: function () { var oldElement = this.element; var tmpl = this.template.createInstance(this, this.templateAction, this.templateSync, this.binding, BINDING_TEMPLATE_INTERFACE); var noChildNodesElement; if (tmpl.childNodesHere) { tmpl.childNodesElement = tmpl.childNodesHere.parentNode; tmpl.childNodesElement.insertPoint = tmpl.childNodesHere; } this.tmpl = tmpl; this.element = tmpl.element; this.childNodesElement = tmpl.childNodesElement || tmpl.element; noChildNodesElement = this.childNodesElement.nodeType != 1; if (noChildNodesElement) this.childNodesElement = document.createDocumentFragment(); if (noChildNodesElement) this.noChildNodesElement_ = true; else delete this.noChildNodesElement_; if (this.grouping) { this.grouping.syncDomRefs(); var cursor = this; while (cursor.grouping) cursor = cursor.grouping; var topGrouping = cursor; for (var groupNode = topGrouping.lastChild; groupNode; groupNode = groupNode.previousSibling) { if (groupNode instanceof PartitionNode) topGrouping.insertBefore(groupNode, groupNode.nextSibling); else reinsertPartitionNodes(groupNode); } reinsertPartitionNodes(topGrouping.nullGroup); } else { for (var child = this.lastChild; child; child = child.previousSibling) this.insertBefore(child, child.nextSibling); } if (this instanceof PartitionNode) reinsertPartitionNodes(this); if (oldElement && oldElement !== this.element && oldElement.nodeType != 11) { var parentNode = oldElement && oldElement.parentNode; if (parentNode) { if (this.owner && this.owner.tmpl) this.owner.tmpl.set(oldElement, this.element); if (this.element.parentNode !== parentNode) parentNode.replaceChild(this.element, oldElement); } } this.emit_templateChanged(); }, setTemplate: function (template) { var curSwitcher = this.templateSwitcher_; var switcher; if (template instanceof TemplateSwitcher) { switcher = template; template = switcher.resolve(this); } if (template instanceof HtmlTemplate == false) template = null; if (!template) { basis.dev.warn("basis.ui.Node#setTemplate: set null to template possible only on node destroy"); return; } if (switcher) { this.templateSwitcher_ = switcher; if (!curSwitcher) this.addHandler(TEMPLATE_SWITCHER_HANDLER, this); } if (curSwitcher && curSwitcher.resolve(this) !== template) { this.templateSwitcher_ = null; this.removeHandler(TEMPLATE_SWITCHER_HANDLER, this); } var oldTmpl = this.tmpl; var oldTemplate = this.template; if (oldTemplate !== template) { this.template = template; this.templateSync(); if (oldTemplate) oldTemplate.clearInstance(oldTmpl); } }, updateBind: function (bindName) { var binding = this.binding[bindName]; var getter = binding && binding.getter; if (getter && this.tmpl) this.tmpl.set(bindName, getter(this)); if (this.roleId == bindName) this.updateBind("$roleId"); }, templateAction: function (actionName, event) { var action = this.action[actionName]; if (action) action.call(this, event); if (!action) basis.dev.warn("template call `" + actionName + "` action, but it isn't defined in action list"); }, focus: function (select) { var focusElement = this.tmpl ? this.tmpl.focus || this.element : null; if (focusElement) { if (focusTimer) focusTimer = basis.clearImmediate(focusTimer); focusTimer = basis.setImmediate(function () { try { focusElement.focus(); if (select) focusElement.select(); } catch (e) { } }); } }, blur: function () { var focusElement = this.tmpl ? this.tmpl.focus || this.element : null; if (focusElement) try { focusElement.blur(); } catch (e) { } }, destroy: function () { if (instances[this.basisObjectId]) notifyDestroySchedule.add(this); else notifyCreateSchedule.remove(this); var template = this.template; var element = this.element; if (this.templateSwitcher_) { this.templateSwitcher_ = null; this.removeHandler(TEMPLATE_SWITCHER_HANDLER, this); } template.clearInstance(this.tmpl); super_.destroy.call(this); this.tmpl = null; this.element = null; this.childNodesElement = null; var parentNode = element && element.parentNode; if (parentNode && parentNode.nodeType == 1) parentNode.removeChild(element); } }; }; var ContainerTemplateMixin = function (super_) { return { insertBefore: function (newChild, refChild) { if (this.noChildNodesElement_) { delete this.noChildNodesElement_; basis.dev.warn("basis.ui: Template has no childNodesElement container, but insertBefore method called; probably it's a bug"); } newChild = super_.insertBefore.call(this, newChild, refChild); var target = newChild.groupNode || this; var container = target.childNodesElement || this.childNodesElement; var nextSibling = newChild.nextSibling; var insertPoint = nextSibling && nextSibling.element.parentNode == container ? nextSibling.element : null; var childElement = newChild.element; var refNode = insertPoint || container.insertPoint || null; if (childElement.parentNode !== container || childElement.nextSibling !== refNode) container.insertBefore(childElement, refNode); return newChild; }, removeChild: function (oldChild) { super_.removeChild.call(this, oldChild); var element = oldChild.element; var parent = element.parentNode; if (parent) parent.removeChild(element); return oldChild; }, clear: function (alive) { if (alive) { var node = this.firstChild; while (node) { var element = node.element; var parent = element.parentNode; if (parent) parent.removeChild(element); node = node.nextSibling; } } super_.clear.call(this, alive); }, setChildNodes: function (childNodes, keepAlive) { if (this.noChildNodesElement_) { delete this.noChildNodesElement_; basis.dev.warn("basis.ui: Template has no childNodesElement container, but setChildNodes method called; probably it's a bug"); } var domFragment = document.createDocumentFragment(); var target = this.grouping || this; var container = target.childNodesElement; target.childNodesElement = domFragment; super_.setChildNodes.call(this, childNodes, keepAlive); container.insertBefore(domFragment, container.insertPoint || null); target.childNodesElement = container; } }; }; var PartitionNode = Class(DWPartitionNode, TemplateMixin, { className: namespace + ".PartitionNode", binding: { title: "data:" } }); var GroupingNode = Class(DWGroupingNode, ContainerTemplateMixin, { className: namespace + ".GroupingNode", childClass: PartitionNode, groupingClass: Class.SELF, element: null, childNodesElement: null, emit_ownerChanged: function (oldOwner) { this.syncDomRefs(); DWGroupingNode.prototype.emit_ownerChanged.call(this, oldOwner); }, init: function () { this.element = this.childNodesElement = document.createDocumentFragment(); DWGroupingNode.prototype.init.call(this); instances[this.basisObjectId] = this; notifier.set({ action: "create", instance: this }); }, syncDomRefs: function () { var cursor = this; var owner = this.owner; var element = null; if (owner) element = owner.tmpl && owner.tmpl.groupsElement || owner.childNodesElement; do { cursor.element = cursor.childNodesElement = element; } while (cursor = cursor.grouping); }, destroy: function () { delete instances[this.basisObjectId]; notifier.set({ action: "destroy", instance: this }); DWGroupingNode.prototype.destroy.call(this); this.element = null; this.childNodesElement = null; } }); var Node = Class(DWNode, TemplateMixin, ContainerTemplateMixin, { className: namespace + ".Node", binding: { selected: { events: "select unselect", getter: function (node) { return node.selected; } }, unselected: { events: "select unselect", getter: function (node) { return !node.selected; } }, disabled: { events: "disable enable", getter: function (node) { return node.isDisabled(); } }, enabled: { events: "disable enable", getter: function (node) { return !node.isDisabled(); } }, tabindex: { events: "enable disable", getter: function (node) { return node.isDisabled() ? -1 : node.tabindex || 0; } } }, childClass: Class.SELF, childFactory: function (config) { return new this.childClass(config); }, groupingClass: GroupingNode }); var ShadowNodeList = Node.subclass({ className: namespace + ".ShadowNodeList", emit_ownerChanged: function (oldOwner) { Node.prototype.emit_ownerChanged.call(this, oldOwner); this.setDataSource(this.owner && this.owner.getChildNodesDataset()); }, getChildNodesElement: function (owner) { return owner.childNodesElement; }, listen: { owner: { templateChanged: function () { this.childNodes.forEach(function (child) { this.appendChild(child.element); }, this.getChildNodesElement(this.owner) || this.owner.element); } } }, childClass: { className: namespace + ".ShadowNode", getElement: function (node) { return node.element; }, templateSync: function () { Node.prototype.templateSync.call(this); var newElement = this.getElement(this.delegate); if (newElement) { newElement[htmlTemplateIdMarker] = this.delegate.element[htmlTemplateIdMarker]; this.element = newElement; } }, listen: { delegate: { templateChanged: function () { var oldElement = this.element; var oldElementParent = oldElement.parentNode; var newElement = this.getElement(this.delegate); if (newElement) newElement[htmlTemplateIdMarker] = this.delegate.element[htmlTemplateIdMarker]; this.element = newElement || this.tmpl.element; if (oldElementParent) oldElementParent.replaceChild(this.element, oldElement); } } } } }); module.exports = { debug_notifier: notifier, debug_getInstances: function () { return basis.object.values(instances); }, BINDING_PRESET: BINDING_PRESET, Node: Node, PartitionNode: PartitionNode, GroupingNode: GroupingNode, ShadowNodeList: ShadowNodeList, ShadowNode: ShadowNodeList.prototype.childClass }; }, "3.js": function (exports, module, basis, global, __filename, __dirname, require, resource, asset) { var namespace = "basis.event"; var Class = basis.Class; var NULL_HANDLER = {}; var events = {}; var warnOnDestroyWhileDestroing = function () { basis.dev.warn("Invoke `destroy` method is prohibited during object destroy."); }; var warnOnDestroy = function () { basis.dev.warn("Object had been destroyed before. Destroy method must not be called more than once."); }; function createDispatcher(eventName) { var eventFunction = events[eventName]; if (!eventFunction) { eventFunction = function () { var cursor = this; var args; var fn; while (cursor = cursor.handler) { fn = cursor.callbacks[eventName]; if (typeof fn == "function") { if (!args) { args = [this]; for (var i = 0; i < arguments.length; i++) args.push(arguments[i]); } fn.apply(cursor.context || this, args); } fn = cursor.callbacks["*"]; if (typeof fn == "function") { if (!args) { args = [this]; for (var i = 0; i < arguments.length; i++) args.push(arguments[i]); } fn.call(cursor.context || this, { sender: this, type: eventName, args: args }); } } if (this.debug_emit) { args = []; for (var i = 0; i < arguments.length; i++) args.push(arguments[i]); this.debug_emit({ sender: this, type: eventName, args: args }); } }; eventFunction = new Function("return {\"" + namespace + ".events." + eventName + "\":\n\n " + "function(" + basis.array(arguments, 1).join(", ") + "){" + eventFunction.toString().replace(/\beventName\b/g, "\"" + eventName + "\"").replace(/^function[^(]*\(\)[^{]*\{|\}$/g, "") + "}" + "\n\n}[\"" + namespace + ".events." + eventName + "\"];")(); events[eventName] = eventFunction; } return eventFunction; } function createHandler(events, eventCallback) { var handler = { events: [] }; if (events) { events = String(events).trim().split(/\s+|\s*,\s*/).sort(); handler = { events: events }; for (var i = 0, eventName; eventName = events[i]; i++) if (eventName != "destroy") handler[eventName] = eventCallback; } return handler; } var Emitter = Class(null, { className: namespace + ".Emitter", extendConstructor_: true, propertyDescriptors: Class.customExtendProperty({ basisObjectId: true, propertyDescriptors: false, handler: false, listen: false }, function (result, extension) { for (var property in extension) { var value = extension[property]; if (value === true || value == "<static>") value = { isStatic: true }; else if (value === false) value = { isPrivate: true }; else if (typeof value == "string") value = { events: value }; result[property] = value; } }), handler: null, emit_destroy: createDispatcher("destroy"), listen: Class.nestedExtendProperty(), debug_handlers: function () { var result = []; var cursor = this; while (cursor = cursor.handler) result.push([ cursor.callbacks, cursor.context ]); return result; }, debug_emit: null, init: function () { if (this.handler && !this.handler.callbacks) this.handler = { callbacks: this.handler, context: this, handler: null }; }, addHandler: function (callbacks, context) { if (!callbacks) basis.dev.warn(namespace + ".Emitter#addHandler: callbacks is not an object (", callbacks, ")"); context = context || this; var cursor = this; while (cursor = cursor.handler) { if (cursor.callbacks === callbacks && cursor.context === context) { basis.dev.warn(namespace + ".Emitter#addHandler: add duplicate event callbacks", callbacks, "to Emitter instance:", this); break; } } this.handler = { callbacks: callbacks, context: context, handler: this.handler }; }, removeHandler: function (callbacks, context) { if (this.destroy === warnOnDestroy) return; var cursor = this; var prev; context = context || this; while (prev = cursor, cursor = cursor.handler) if (cursor.callbacks === callbacks && cursor.context === context) { cursor.callbacks = NULL_HANDLER; prev.handler = cursor.handler; return; } basis.dev.warn(namespace + ".Emitter#removeHandler: no handler removed"); }, destroy: function () { this.destroy = warnOnDestroyWhileDestroing; this.emit_destroy(); this.handler = null; this.destroy = warnOnDestroy; } }); module.exports = { create: createDispatcher, createHandler: createHandler, events: events, Emitter: Emitter }; }, "4.js": function (exports, module, basis, global, __filename, __dirname, require, resource, asset) { var namespace = "basis.template.html"; var document = global.document; var Node = global.Node; var camelize = basis.string.camelize; var isMarkupToken = basis.require("./5.js").isMarkupToken; var isTokenHasPlaceholder = basis.require("./5.js").isTokenHasPlaceholder; var getL10nToken = basis.require("./5.js").token; var getFunctions = basis.require("./6.js").getFunctions; var basisTemplate = basis.require("./9.js"); var TemplateSwitchConfig = basisTemplate.TemplateSwitchConfig; var TemplateSwitcher = basisTemplate.TemplateSwitcher; var Template = basisTemplate.Template; var getSourceByPath = basisTemplate.get; var buildDOM = basis.require("./d.js"); var CLONE_NORMALIZATION_TEXT_BUG = basis.require("./7.js").CLONE_NORMALIZATION_TEXT_BUG; var IS_SET_STYLE_SAFE = !!function () { try { return document.documentElement.style.color = "x"; } catch (e) { } }(); var l10nTemplate = {}; var l10nTemplateSource = {}; function getSourceFromL10nToken(token) { var dict = token.getDictionary(); var name = token.getName(); var id = name + "@" + dict.id; var result = l10nTemplateSource[id]; var sourceWrapper; if (!result) { var sourceToken = dict.token(name); result = l10nTemplateSource[id] = sourceToken.as(function (value) { if (sourceToken.getType() == "markup") { if (typeof value == "string" && isTokenHasPlaceholder(sourceToken)) value = value.replace(/\{#\}/g, "{__templateContext}"); if (value != this.value) if (sourceWrapper) { sourceWrapper.detach(sourceToken, sourceToken.apply); sourceWrapper = null; } if (value && String(value).substr(0, 5) == "path:") { sourceWrapper = getSourceByPath(value.substr(5)); sourceWrapper.attach(sourceToken, sourceToken.apply); } return sourceWrapper ? sourceWrapper.bindingBridge.get(sourceWrapper) : value; } return this.value; }); result.id = "{l10n:" + id + "}"; result.url = dict.getValueSource(name) + ":" + name; } return result; } function getL10nHtmlTemplate(token) { if (typeof token == "string") token = getL10nToken(token); if (!token) return null; var templateSource = getSourceFromL10nToken(token); var id = templateSource.id; var htmlTemplate = l10nTemplate[id]; if (!htmlTemplate) htmlTemplate = l10nTemplate[id] = new HtmlTemplate(templateSource); return htmlTemplate; } var builder = function () { var WHITESPACE = /\s+/; var CLASSLIST_SUPPORTED = global.DOMTokenList && document && document.documentElement.classList instanceof global.DOMTokenList; var W3C_DOM_NODE_SUPPORTED = function () { try { return document instanceof Node; } catch (e) { } }() || false; function collapseDomFragment(fragment) { var startMarker = fragment.startMarker; var endMarker = fragment.endMarker; var cursor = startMarker.nextSibling; while (cursor && cursor !== endMarker) { var tmp = cursor; cursor = cursor.nextSibling; fragment.appendChild(tmp); } endMarker.parentNode.removeChild(endMarker); fragment.startMarker = null; fragment.endMarker = null; return startMarker; } var bind_node = W3C_DOM_NODE_SUPPORTED ? function (domRef, oldNode, newValue, domNodeBindingProhibited) { var newNode = !domNodeBindingProhibited && newValue && newValue instanceof Node ? newValue : domRef; if (newNode !== oldNode) { if (newNode.nodeType === 11 && !newNode.startMarker) { newNode.startMarker = document.createTextNode(""); newNode.endMarker = document.createTextNode(""); newNode.insertBefore(newNode.startMarker, newNode.firstChild); newNode.appendChild(newNode.endMarker); } if (oldNode.nodeType === 11 && oldNode.startMarker) oldNode = collapseDomFragment(oldNode); oldNode.parentNode.replaceChild(newNode, oldNode); } return newNode; } : function (domRef, oldNode, newValue, domNodeBindingProhibited) { var newNode = !domNodeBindingProhibited && newValue && typeof newValue == "object" ? newValue : domRef; if (newNode !== oldNode) { try { oldNode.parentNode.replaceChild(newNode, oldNode); } catch (e) { newNode = domRef; if (oldNode !== newNode) oldNode.parentNode.replaceChild(newNode, oldNode); } } return newNode; }; var bind_element = function (domRef, oldNode, newValue, domNodeBindingProhibited) { var newNode = bind_node(domRef, oldNode, newValue, domNodeBindingProhibited); if (newNode === domRef && typeof newValue == "string") domRef.innerHTML = newValue; return newNode; }; var bind_comment = bind_node; var bind_textNode = function (domRef, oldNode, newValue, domNodeBindingProhibited) { var newNode = bind_node(domRef, oldNode, newValue, domNodeBindingProhibited); if (newNode === domRef) domRef.nodeValue = String(newValue); return newNode; }; var bind_attrClass = CLASSLIST_SUPPORTED ? normalAttrClass : legacyAttrClass; function normalAttrClass(domRef, oldClass, newValue, anim) { var classList = domRef.classList; if (!classList) return legacyAttrClass(domRef, oldClass, newValue, anim); var newClass = newValue || ""; if (newClass != oldClass) { if (oldClass) domRef.classList.remove(oldClass); if (newClass) { domRef.classList.add(newClass); if (anim) { domRef.classList.add(newClass + "-anim"); basis.nextTick(function () { domRef.classList.remove(newClass + "-anim"); }); } } } return newClass; } function legacyAttrClass(domRef, oldClass, newValue, anim) { var newClass = newValue || ""; if (newClass != oldClass) { var className = domRef.className; var classNameIsObject = typeof className != "string"; var classList; if (classNameIsObject) className = className.baseVal; classList = className.split(WHITESPACE); if (oldClass) basis.array.remove(classList, oldClass); if (newClass) { classList.push(newClass); if (anim) { basis.array.add(classList, newClass + "-anim"); basis.nextTick(function () { var classList = (classNameIsObject ? domRef.className.baseVal : domRef.className).split(WHITESPACE); basis.array.remove(classList, newClass + "-anim"); if (classNameIsObject) domRef.className.baseVal = classList.join(" "); else domRef.className = classList.join(" "); }); } } if (classNameIsObject) domRef.className.baseVal = classList.join(" "); else domRef.className = classList.join(" "); } return newClass; } var bind_attrStyle = IS_SET_STYLE_SAFE ? function (domRef, propertyName, oldValue, newValue) { if (oldValue !== newValue) domRef.style[camelize(propertyName)] = newValue; return newValue; } : function (domRef, propertyName, oldValue, newValue) { if (oldValue !== newValue) { try { domRef.style[camelize(propertyName)] = newValue; } catch (e) { } } return newValue; }; var bind_attr = function (domRef, attrName, oldValue, newValue) { if (oldValue !== newValue) { if (newValue) domRef.setAttribute(attrName, newValue); else domRef.removeAttribute(attrName); } return newValue; }; var bind_attrNS = function (domRef, namespace, attrName, oldValue, newValue) { if (oldValue !== newValue) { if (newValue) domRef.setAttributeNS(namespace, attrName, newValue); else domRef.removeAttributeNS(namespace, attrName); } return newValue; }; function updateAttach() { this.set(this.name, this.value); } function resolveValue(bindingName, value, Attaches) { var bridge = value && value.bindingBridge; var oldAttach = this.attaches && this.attaches[bindingName]; var tmpl = null; if (bridge || oldAttach) { if (bridge) { var isMarkup = isMarkupToken(value); var template; if (isMarkup) template = getL10nHtmlTemplate(value); if (!oldAttach || oldAttach.value !== value || oldAttach.template !== template) { if (oldAttach) { if (oldAttach.tmpl) oldAttach.template.clearInstance(oldAttach.tmpl); oldAttach.value.bindingBridge.detach(oldAttach.value, updateAttach, oldAttach); } if (template) { var context = this.context; var bindings = this.bindings; var onAction = this.action; var bindingInterface = this.bindingInterface; tmpl = template.createInstance(context, onAction, function onRebuild() { tmpl = newAttach.tmpl = template.createInstance(context, onAction, onRebuild, bindings, bindingInterface); tmpl.parent = tmpl.element.parentNode || tmpl.element; updateAttach.call(newAttach); }, bindings, bindingInterface); tmpl.parent = tmpl.element.parentNode || tmpl.element; } if (!this.attaches) this.attaches = new Attaches(); var newAttach = this.attaches[bindingName] = { name: bindingName, value: value, template: template, tmpl: tmpl, set: this.tmpl.set }; bridge.attach(value, updateAttach, newAttach); } else tmpl = value && isMarkupToken(value) ? oldAttach.tmpl : null; if (tmpl) { tmpl.set("__templateContext", value.value); return tmpl.parent; } value = bridge.get(value); } else { if (oldAttach) { if (oldAttach.tmpl) oldAttach.template.clearInstance(oldAttach.tmpl); oldAttach.value.bindingBridge.detach(oldAttach.value, updateAttach, oldAttach); this.attaches[bindingName] = null; } } } return value; } function createBindingUpdater(names, getters) { var name1 = names[0]; var name2 = names[1]; var getter1 = getters[name1]; var getter2 = getters[name2]; switch (names.length) { case 1: return function bindingUpdater1(object) { this(name1, getter1(object)); }; case 2: return function bindingUpdater2(object) { this(name1, getter1(object)); this(name2, getter2(object)); }; default: var getters_ = names.map(function (name) { return getters[name]; }); return function bindingUpdaterN(object) { for (var i = 0; i < names.length; i++) this(names[i], getters_[i](object)); }; } ; } function makeHandler(events, getters) { for (var name in events) events[name] = createBindingUpdater(events[name], getters); return name ? events : null; } function createBindingFunction(keys) { var bindingCache = {}; return function getBinding(instance, set) { var bindings = instance.bindings; if (!bindings) return {}; var cacheId = "bindingId" in bindings ? bindings.bindingId : null; if (!cacheId) basis.dev.warn("basis.template.Template.getBinding: bindings has no bindingId property, cache is not used"); var result = bindingCache[cacheId]; if (!result) { var names = []; var getters = {}; var events = {}; for (var i = 0, bindingName; bindingName = keys[i]; i++) { var binding = bindings[bindingName]; var getter = binding && binding.getter; if (getter) { getters[bindingName] = getter; names.push(bindingName); if (binding.events) { var eventList = String(binding.events).trim().split(/\s+|\s*,\s*/); for (var j = 0, eventName; eventName = eventList[j]; j++) { if (events[eventName]) events[eventName].push(bindingName); else events[eventName] = [bindingName]; } } } } result = { names: names, sync: createBindingUpdater(names, getters), handler: makeHandler(events, getters) }; if (cacheId) bindingCache[cacheId] = result; } if (set) result.sync.call(set, instance.context); if (!instance.bindingInterface) return; if (result.handler) instance.bindingInterface.attach(instance.context, result.handler, set); return result.handler; }; } var tools = { bind_textNode: bind_textNode, bind_node: bind_node, bind_element: bind_element, bind_comment: bind_comment, bind_attr: bind_attr, bind_attrNS: bind_attrNS, bind_attrClass: bind_attrClass, bind_attrStyle: bind_attrStyle, resolve: resolveValue, l10nToken: getL10nToken }; return function (tokens, instances) { var fn = getFunctions(tokens, true, this.source.url, tokens.source_, !CLONE_NORMALIZATION_TEXT_BUG); var hasL10n = fn.createL10nSync; var initInstance; var l10nProtoSync; var l10nMap = {}; var l10nLinks = []; var l10nMarkupTokens = []; var seed = 0; var proto = { cloneNode: function () { if (seed == 1) return buildDOM(tokens); proto = buildDOM(tokens); if (hasL10n) { l10nProtoSync = fn.createL10nSync(proto, l10nMap, bind_attr, CLONE_NORMALIZATION_TEXT_BUG); for (var i = 0, l10nToken; l10nToken = l10nLinks[i]; i++) l10nProtoSync(l10nToken.path, l10nMap[l10nToken.path]); } return proto.cloneNode(true); } }; var createDOM = function () { return proto.cloneNode(true); }; if (hasL10n) { var initL10n = function (set) { for (var i = 0, token; token = l10nLinks[i]; i++) set(token.path, l10nMap[token.path]); }; var linkHandler = function (value) { var isMarkup = isMarkupToken(this.token); if (isMarkup) basis.array.add(l10nMarkupTokens, this); else basis.array.remove(l10nMarkupTokens, this); l10nMap[this.path] = isMarkup ? undefined : value == null ? "{" + this.path + "}" : value; if (l10nProtoSync) l10nProtoSync(this.path, l10nMap[this.path]); for (var key in instances) instances[key].tmpl.set(this.path, isMarkup ? this.token : value); }; l10nLinks = fn.l10nKeys.map(function (key) { var token = getL10nToken(key); var link = { path: key, token: token, handler: linkHandler }; token.attach(linkHandler, link); if (isMarkupToken(token)) l10nMarkupTokens.push(link); else l10nMap[key] = token.value == null ? "{" + key + "}" : token.value; return link; }); } initInstance = fn.createInstanceFactory(this.templateId, createDOM, tools, l10nMap, l10nMarkupTokens, createBindingFunction(fn.keys), CLONE_NORMALIZATION_TEXT_BUG); return { createInstance: function (obj, onAction, onRebuild, bindings, bindingInterface) { var instanceId = seed++; var instance = { context: obj, action: onAction, rebuild: onRebuild, handler: null, bindings: bindings, bindingInterface: bindingInterface, attaches: null, compute: null, tmpl: null }; initInstance(instanceId, instance, !instanceId ? initL10n : null); instances[instanceId] = instance; return instance.tmpl; }, destroyInstance: function (tmpl) { var instanceId = tmpl.templateId_; var instance = instances[instanceId]; if (instance) { if (instance.handler) instance.bindingInterface.detach(instance.context, instance.handler, instance.tmpl.set); if (instance.compute) { for (var i = 0; i < instance.compute.length; i++) instance.compute[i].destroy(); instance.compute = null; } for (var key in instance.attaches) resolveValue.call(instance, key, null); delete instances[instanceId]; } }, destroy: function (rebuild) { for (var i = 0, link; link = l10nLinks[i]; i++) link.token.detach(link.handler, link); for (var key in instances) { var instance = instances[key]; if (rebuild && instance.rebuild) instance.rebuild.call(instance.context); if (!rebuild || key in instances) { if (instance.handler) instance.bindingInterface.detach(instance.context, instance.handler, instance.tmpl.set); for (var key in instance.attaches) resolveValue.call(key, null); } } fn = null; proto = null; l10nMap = null; l10nLinks = null; l10nProtoSync = null; instances = null; } }; }; }(); var HtmlTemplate = Template.subclass({ className: namespace + ".Template", __extend__: function (value) { if (value instanceof HtmlTemplate) return value; if (value instanceof TemplateSwitchConfig) return new HtmlTemplateSwitcher(value); return new HtmlTemplate(value); }, builder: builder }); var HtmlTemplateSwitcher = TemplateSwitcher.subclass({ className: namespace + ".TemplateSwitcher", templateClass: HtmlTemplate }); module.exports = { Template: HtmlTemplate, TemplateSwitcher: HtmlTemplateSwitcher }; }, "5.js": function (exports, module, basis, global, __filename, __dirname, require, resource, asset) { var namespace = "basis.l10n"; var extend = basis.object.extend; var complete = basis.object.complete; var Class = basis.Class; var Emitter = basis.require("./3.js").Emitter; var extensionJSON = basis.resource.extensions[".json"]; var hasOwnProperty = Object.prototype.hasOwnProperty; var basisTokenPrototypeSet = basis.Token.prototype.set; var buildJsonMap = basis.require("./12.js").buildMap; basis.resource.extensions[".l10n"] = processDictionaryContent; var patches = function () { var config = basis.config.l10n || {}; var patches = config && config.patch; var result = {}; var baseURI; config.patch = {}; if (patches) { if (typeof patches == "string") { try { baseURI = basis.path.dirname(basis.resource.resolveURI(patches)); patches = basis.resource(patches).fetch(); } catch (e) { basis.dev.error("basis.l10n: dictionary patch file load failed:", patches); } } for (var path in patches) { var dictUrl = basis.resource.resolveURI(path, baseURI); var patchUrl = basis.resource.resolveURI(patches[path], baseURI); result[dictUrl] = createDictionaryMerge(dictUrl, patchUrl); config.patch[dictUrl] = patchUrl; } } return result; }(); function processJSON(content, url) { var locationMap; if (typeof content == "string") locationMap = buildJsonMap(content, url); content = extensionJSON(content, url); if (content) content._locationMap = locationMap; return content; } function getJSON(url) { return processJSON(resource(url).get(true), url) || {}; } function createDictionaryMerge(dictUrl, patchUrl) { function sync() { dictionaryByUrl[dictUrl].update(mergeDictionaries(getJSON(dictUrl), patchUrl)); } return { url: patchUrl, activate: function () { resource(patchUrl).attach(sync); }, deactivate: function () { resource(patchUrl).detach(sync); } }; } function mergeDictionaries(dest, patchSource) { function isObject(value) { return value && Object.prototype.toString.call(value) == "[object Object]"; } function deepMerge(dest, patch, path, sourceMap) { if (path) path += "."; for (var key in patch) if (!isObject(patch[key])) { sourceMap[path + key] = patchSource; dest[key] = patch[key]; } else { dest[key] = deepMerge(isObject(dest[key]) ? dest[key] : {}, patch[key], path + key, sourceMap); } return dest; } var patch = getJSON(patchSource); var sources; for (var key in patch) { if (key == "_meta" || key == "_locationMap") { if (!isObject(dest[key])) dest[key] = {}; deepMerge(dest[key], patch[key], "", {}); continue; } if (!hasOwnProperty.call(dest, key)) { dest[key] = { _meta: { source: {} } }; } else { if (!dest[key]._meta) dest[key]._meta = {}; } sources = {}; dest[key]._meta.source = {}; deepMerge(dest[key], patch[key], "", sources); dest[key]._meta.source = sources; } if (!Array.isArray(dest._patches)) dest._patches = []; basis.array.add(dest._patches, patchSource); return dest; } function processDictionaryContent(content, url) { content = processJSON(content, url); if (patches[url]) mergeDictionaries(content, patches[url].url); return internalResolveDictionary(url, true).update(content); } var tokenIndex = []; var tokenComputeFn = {}; var NULL_DESCRIPTOR = { placeholder: false, processName: basis.fn.$self, value: undefined, types: {} }; var TOKEN_TYPES = { "default": true, "plural": true, "markup": true, "plural-markup": true, "enum-markup": true }; var PLURAL_TYPES = { "plural": true, "plural-markup": true }; var NESTED_TYPE = { "default": "default", "plural": "default", "markup": "default", "plural-markup": "markup", "enum-markup": "markup" }; var pluralName = function (value) { return this.culture.plural(value); }; var ComputeToken = Class(basis.Token, { className: namespace + ".ComputeToken", token: null, init: function (value) { this.token.computeTokens[this.basisObjectId] = this; basis.Token.prototype.init.call(this, value); }, toString: function () { return this.get(); }, get: function () { var value = this.token.dictionary.getValue(this.getName()); if (this.token.descriptor.placeholder) value = String(value).replace(/\{#\}/g, this.value); return value; }, getName: function () { return this.token.name + "." + this.token.descriptor.processName(this.value); }, getType: function () { return this.token.descriptor.types[this.getName()] || "default"; }, getDictionary: function () { return this.token.getDictionary(); }, destroy: function () { delete this.token.computeTokens[this.basisObjectId]; basis.Token.prototype.destroy.call(this); } }); var Token = Class(basis.Token, { className: namespace + ".Token", index: NaN, dictionary: null, name: "", type: "default", computeTokens: null, computeTokenClass: null, init: function (dictionary, tokenName, descriptor) { basis.Token.prototype.init.call(this, descriptor.value); this.index = tokenIndex.push(this) - 1; this.name = tokenName; this.dictionary = dictionary; this.descriptor = descriptor; this.computeTokens = {}; }, toString: function () { return this.get(); }, apply: function () { for (var key in this.computeTokens) this.computeTokens[key].apply(); basis.Token.prototype.apply.call(this); }, set: function () { basis.dev.warn("basis.l10n: Value for l10n token can't be set directly, but through dictionary update only"); }, getName: function () { return this.name; }, getType: function () { return this.descriptor.types[this.name] || "default"; }, setType: function () { basis.dev.warn("basis.l10n: Token#setType() is deprecated"); }, compute: function (events, getter) { if (arguments.length == 1) { getter = events; events = ""; } getter = basis.getter(getter); events = String(events).trim().split(/\s+|\s*,\s*/).sort(); var tokenId = this.basisObjectId; var enumId = events.concat(tokenId, getter[basis.getter.ID]).join("_"); if (tokenComputeFn[enumId]) return tokenComputeFn[enumId]; var token = this; var objectTokenMap = {}; var updateValue = function (object) { basisTokenPrototypeSet.call(this, getter(object)); }; var handler = { destroy: function (object) { delete objectTokenMap[object.basisObjectId]; this.destroy(); } }; for (var i = 0, eventName; eventName = events[i]; i++) if (eventName != "destroy") handler[eventName] = updateValue; return tokenComputeFn[enumId] = function (object) { if (object instanceof Emitter == false) throw "basis.l10n.Token#compute: object must be an instanceof Emitter"; var objectId = object.basisObjectId; var computeToken = objectTokenMap[objectId]; if (!computeToken) { computeToken = objectTokenMap[objectId] = token.computeToken(getter(object)); object.addHandler(handler, computeToken); } return computeToken; }; }, computeToken: function (value) { var ComputeTokenClass = this.computeTokenClass; if (!ComputeTokenClass) ComputeTokenClass = this.computeTokenClass = ComputeToken.subclass({ token: this }); return new ComputeTokenClass(value); }, token: function (name) { if (this.getType() in PLURAL_TYPES) return this.computeToken(name); if (this.dictionary) return this.dictionary.token(this.name + "." + name); }, getDictionary: function () { return this.dictionary; }, destroy: function () { for (var key in this.computeTokens) this.computeTokens[key].destroy(); this.descriptor = null; this.computeTokenClass = null; this.computeTokens = null; this.value = null; this.dictionary = null; tokenIndex[this.index] = null; basis.Token.prototype.destroy.call(this); } }); function resolveToken(path) { if (path.charAt(0) == "#") { return tokenIndex[parseInt(path.substr(1), 36)]; } else { var parts = path.match(/^(.+?)@(.+)$/); if (parts) return resolveDictionary(basis.path.resolve(parts[2])).token(parts[1]); basis.dev.warn("basis.l10n.token accepts token references in format `token.path@path/to/dict.l10n` only"); } } function isToken(value) { return value ? value instanceof Token || value instanceof ComputeToken : false; } function isPluralToken(value) { return isToken(value) && value.getType() in PLURAL_TYPES; } function isTokenHasPlaceholder(value) { return isToken(value) && value.descriptor.placeholder; } function isMarkupToken(value) { return isToken(value) && value.getType() == "markup"; } var dictionaries = []; var dictionaryByUrl = {}; var createDictionaryNotifier = new basis.Token(); function walkTokens(tokens, parentName, context) { var path = parentName ? parentName + "." : ""; var parentType = context.types[parentName] || "default"; for (var name in tokens) { if (parentName == "" && name == "_meta") continue; if (name.indexOf(".") != -1) { basis.dev.warn(context.name + ": wrong token name `" + name + "`, token ignored."); continue; } if (hasOwnProperty.call(tokens, name)) { var tokenName = path + name; var tokenType = context.types[tokenName] || NESTED_TYPE[parentType] || "default"; var tokenValue = tokens[name]; var isPlural = tokenType in PLURAL_TYPES || parentType in PLURAL_TYPES; context.values[tokenName] = { _sourceBranch: tokens, _sourceKey: name, loc: context.locationMap ? context.locationMap[context.culture.name + "." + tokenName] || null : null, placeholder: isPlural, processName: isPlural ? pluralName : basis.fn.$self, source: context.source[tokenName] || context.dictionary.id, culture: context.culture, name: tokenName, types: context.types, value: tokenValue }; if (tokenName in context.types == false) context.types[tokenName] = tokenType; if (tokenValue && (typeof tokenValue == "object" || Array.isArray(tokenValue))) walkTokens(tokenValue, tokenName, context); } } return context.values; } function fetchTypes(data) { var dirtyTypes = data._meta && data._meta.type || {}; var types = {}; for (var path in dirtyTypes) if (dirtyTypes[path] in TOKEN_TYPES) types[path] = dirtyTypes[path]; return types; } function fetchSource(data) { return data._meta && data._meta.source || {}; } var Dictionary = Class(null, { className: namespace + ".Dictionary", cultureValues: null, tokens: null, index: NaN, resource: null, id: null, init: function (content, noResourceFetch) { this.tokens = {}; this.cultureValues = {}; this.index = dictionaries.push(this) - 1; if (basis.resource.isResource(content)) { var resource = content; var resourceUrl = resource.url; this.id = resourceUrl; this.resource = resource; if (!dictionaryByUrl[resourceUrl]) { dictionaryByUrl[resourceUrl] = this; createDictionaryNotifier.set(resourceUrl); if (patches[resourceUrl]) patches[resourceUrl].activate(); } if (!noResourceFetch) resource.fetch(); } else { this.id = "dictionary" + this.index; this.update(content || {}); } }, update: function (data) { if (!data) data = {}; this.cultureValues = {}; var types = fetchTypes(data); for (var culture in data) if (!/^_|_$/.test(culture)) this.cultureValues[culture] = walkTokens(data[culture], "", { name: this.resource ? this.resource.url : "[anonymous dictionary]", locationMap: data._locationMap, dictionary: this, culture: resolveCulture(culture), source: fetchSource(data[culture]), types: complete(fetchTypes(data[culture]), types), values: {} }); delete data._locationMap; this._data = data; this.syncValues(); return this; }, syncValues: function () { for (var tokenName in this.tokens) { var token = this.tokens[tokenName]; var descriptor = this.getDescriptor(tokenName) || NULL_DESCRIPTOR; var savedType = token.getType(); token.descriptor = descriptor; if (token.value !== descriptor.value) { basisTokenPrototypeSet.call(token, descriptor.value); } else { if (token.getType() != savedType) token.apply(); } } }, getCultureDescriptor: function (culture, tokenName) { return this.cultureValues[culture] && this.cultureValues[culture][tokenName]; }, getDescriptor: function (tokenName) { var fallback = cultureFallback[currentCulture] || []; for (var i = 0, cultureName; cultureName = fallback[i]; i++) { var descriptor = this.getCultureDescriptor(cultureName, tokenName); if (descriptor) return descriptor; } }, getCultureValue: function (culture, tokenName) { var descriptor = this.getCultureDescriptor(culture, tokenName); if (descriptor) return descriptor.value; }, getValue: function (tokenName) { var descriptor = this.getDescriptor(tokenName); if (descriptor) return descriptor.value; }, getValueSource: function (tokenName) { var descriptor = this.getDescriptor(tokenName); if (descriptor) return descriptor.source; return this.id; }, token: function (tokenName) { var token = this.tokens[tokenName]; if (!token) { var descriptor = this.getDescriptor(tokenName) || NULL_DESCRIPTOR; token = this.tokens[tokenName] = new Token(this, tokenName, descriptor); } return token; }, destroy: function () { this.tokens = null; this.cultureValues = null; basis.array.remove(dictionaries, this); if (this.resource) { var resourceUrl = this.resource.url; if (patches[resourceUrl]) patches[resourceUrl].deactivate(); delete dictionaryByUrl[resourceUrl]; this.resource = null; } } }); function internalResolveDictionary(source, noFetch) { var dictionary; if (typeof source == "string") { var location = source; var extname = basis.path.extname(location); if (extname != ".l10n") location = location.replace(new RegExp(extname + "([#?]|$)"), ".l10n$1"); source = basis.resource(location); } if (basis.resource.isResource(source)) dictionary = dictionaryByUrl[source.url]; return dictionary || new Dictionary(source, noFetch); } function resolveDictionary(source) { return internalResolveDictionary(source); } function getDictionaries() { return dictionaries.slice(0); } var cultureList = []; var currentCulture = null; var cultures = {}; var cultureFallback = {}; var pluralFormsMap = {}; var pluralForms = [ [ 1, function () { return 0; } ], [ 2, function (n) { return n == 1 || n % 10 == 1 ? 0 : 1; } ], [ 2, function (n) { return n == 0 ? 0 : 1; } ], [ 2, function (n) { return n == 1 ? 0 : 1; } ], [ 2, function (n) { return n == 0 || n == 1 ? 0 : 1; } ], [ 2, function (n) { return n % 10 != 1 || n % 100 == 11 ? 1 : 0; } ], [ 3, function (n) { return n == 1 ? 0 : n % 10 >= 2 && n % 10 <= 4 && (n % 100 < 10 || n % 100 >= 20) ? 1 : 2; } ], [ 3, function (n) { return n % 10 == 1 && n % 100 != 11 ? 0 : n != 0 ? 1 : 2; } ], [ 3, function (n) { return n % 10 == 1 && n % 100 != 11 ? 0 : n % 10 >= 2 && (n % 100 < 10 || n % 100 >= 20) ? 1 : 2; } ], [ 3, function (n) { return n % 10 == 1 && n % 100 != 11 ? 0 : n % 10 >= 2 && n % 10 <= 4 && (n % 100 < 10 || n % 100 >= 20) ? 1 : 2; } ], [ 3, function (n) { return n == 0 ? 0 : n == 1 ? 1 : 2; } ], [ 3, function (n) { return n == 1 ? 0 : n == 0 || n % 100 > 0 && n % 100 < 20 ? 1 : 2; } ], [ 3, function (n) { return n == 1 ? 0 : n % 10 >= 2 && n % 10 <= 4 && (n % 100 < 10 || n % 100 >= 20) ? 1 : 2; } ], [ 3, function (n) { return n == 1 ? 0 : n >= 2 && n <= 4 ? 1 : 2; } ], [ 4, function (n) { return n == 1 ? 0 : n == 2 ? 1 : n != 8 && n != 11 ? 2 : 3; } ], [ 4, function (n) { return n == 1 ? 0 : n == 2 ? 1 : n == 3 ? 2 : 3; } ], [ 4, function (n) { return n % 100 == 1 ? 1 : n % 100 == 2 ? 2 : n % 100 == 3 || n % 100 == 4 ? 3 : 0; } ], [ 4, function (n) { return n == 1 ? 0 : n == 0 || n % 100 > 1 && n % 100 < 11 ? 1 : n % 100 > 10 && n % 100 < 20 ? 2 : 3; } ], [ 4, function (n) { return n == 1 || n == 11 ? 0 : n == 2 || n == 12 ? 1 : n > 2 && n < 20 ? 2 : 3; } ], [ 5, function (n) { return n == 1 ? 0 : n == 2 ? 1 : n < 7 ? 2 : n < 11 ? 3 : 4; } ], [ 6, function (n) { return n == 0 ? 0 : n == 1 ? 1 : n == 2 ? 2 : n % 100 >= 3 && n % 100 <= 10 ? 3 : n % 100 >= 11 ? 4 : 5; } ] ]; [ "ay bo cgg dz fa id ja jbo ka kk km ko ky lo ms my sah su th tt ug vi wo zh", "mk", "jv", "af an ast az bg bn brx ca da de doi el en eo es es-AR et eu ff fi fo fur fy gl gu ha he hi hne hu hy ia it kn ku lb mai ml mn mni mr nah nap nb ne nl nn no nso or pa pap pms ps pt rm rw sat sco sd se si so son sq sv sw ta te tk ur yo", "ach ak am arn br fil fr gun ln mfe mg mi oc pt-BR tg ti tr uz wa zh", "is", "csb", "lv", "lt", "be bs hr ru sr uk", "mnk", "ro", "pl", "cs sk", "cy", "kw", "sl", "mt", "gd", "ga", "ar" ].forEach(function (langs, idx) { langs.split(" ").forEach(function (lang) { pluralFormsMap[lang] = this; }, pluralForms[idx]); }); var Culture = basis.Class(null, { className: namespace + ".Culture", name: "", pluralForm: null, init: function (name, pluralForm) { this.name = name; if (!cultures[name]) cultures[name] = this; this.pluralForm = pluralForm || pluralFormsMap[name] || pluralFormsMap[name.split("-")[0]] || pluralForms[0]; }, plural: function (value) { return Number(this.pluralForm[1](Math.abs(parseInt(value, 10)))); } }); function resolveCulture(name, pluralForm) { if (name && !cultures[name]) cultures[name] = new Culture(name, pluralForm); return cultures[name || currentCulture]; } extend(resolveCulture, new basis.Token()); resolveCulture.set = setCulture; function getCulture() { return currentCulture; } function setCulture(culture) { if (!culture) return; if (currentCulture != culture) { if (cultureList.indexOf(culture) == -1) { basis.dev.warn("basis.l10n.setCulture: culture `" + culture + "` not in the list, the culture doesn't changed"); return; } currentCulture = culture; for (var i = 0, dictionary; dictionary = dictionaries[i]; i++) dictionary.syncValues(); basisTokenPrototypeSet.call(resolveCulture, culture); } } function getCultureList() { return cultureList.slice(0); } function setCultureList(list) { if (typeof list == "string") list = list.trim().split(" "); if (!list.length) { basis.dev.warn("basis.l10n.setCultureList: culture list can't be empty, the culture list isn't changed"); return; } var cultures = {}; var cultureRow; var baseCulture; cultureFallback = {}; for (var i = 0, culture, cultureName; culture = list[i]; i++) { cultureRow = culture.split("/"); if (cultureRow.length > 2) { basis.dev.warn("basis.l10n.setCultureList: only one fallback culture can be set for certain culture, try to set `" + culture + "`; other cultures except first one was ignored"); cultureRow = [ cultureRow[0], cultureRow[1] ]; } cultureName = cultureRow[0]; if (!baseCulture) baseCulture = cultureName; cultures[cultureName] = resolveCulture(cultureName); cultureFallback[cultureName] = cultureRow; } for (var cultureName in cultureFallback) cultureFallback[cultureName] = basis.array.flatten(cultureFallback[cultureName].map(function (name) { return cultureFallback[name]; })).concat(baseCulture).filter(function (item, idx, array) { return !idx || array.lastIndexOf(item, idx - 1) == -1; }); cultureList = basis.object.keys(cultures); if (currentCulture in cultures == false) setCulture(baseCulture); } function onCultureChange(fn, context, fire) { resolveCulture.attach(fn, context); if (fire) fn.call(context, currentCulture); } setCultureList("en-US"); setCulture("en-US"); module.exports = { ComputeToken: ComputeToken, Token: Token, token: resolveToken, isToken: isToken, isPluralToken: isPluralToken, isMarkupToken: isMarkupToken, isTokenHasPlaceholder: isTokenHasPlaceholder, Dictionary: Dictionary, dictionary: resolveDictionary, getDictionaries: getDictionaries, addCreateDictionaryHandler: createDictionaryNotifier.attach.bind(createDictionaryNotifier), removeCreateDictionaryHandler: createDictionaryNotifier.detach.bind(createDictionaryNotifier), Culture: Culture, culture: resolveCulture, getCulture: getCulture, setCulture: setCulture, getCultureList: getCultureList, setCultureList: setCultureList, pluralForms: pluralForms, onCultureChange: onCultureChange }; (function () { var value = false; try { Object.defineProperty(module.exports, "enableMarkup", { get: function () { return value; }, set: function (newValue) { basis.dev.warn("basis.l10n: enableMarkup option is deprecated, just remove it from your source code as markup l10n tokens enabled by default now"); value = newValue; } }); } catch (e) { } }()); }, "12.js": function (exports, module, basis, global, __filename, __dirname, require, resource, asset) { "use strict"; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var JsonParser = function () { "use strict"; if (!Object.assign) { Object.defineProperty(Object, "assign", { enumerable: false, configurable: true, writable: true, value: function value(target) { "use strict"; if (target === undefined || target === null) { throw new TypeError("Cannot convert first argument to object"); } var to = Object(target); for (var i = 1; i < arguments.length; i++) { var nextSource = arguments[i]; if (nextSource === undefined || nextSource === null) { continue; } var keysArray = Object.keys(Object(nextSource)); for (var nextIndex = 0, len = keysArray.length; nextIndex < len; nextIndex++) { var nextKey = keysArray[nextIndex]; var desc = Object.getOwnPropertyDescriptor(nextSource, nextKey); if (desc !== undefined && desc.enumerable) { to[nextKey] = nextSource[nextKey]; } } } return to; } }); } var exceptionsDict = { tokenizeSymbolError: "Cannot tokenize symbol <{char}> at {line}:{column}", emptyString: "JSON is empty" }; function position(startLine, startColumn, startChar, endLine, endColumn, endChar) { return { start: { line: startLine, column: startColumn, char: startChar }, end: { line: endLine, column: endColumn, char: endChar }, human: startLine + ":" + startColumn + " - " + endLine + ":" + endColumn + " [" + startChar + ":" + endChar + "]" }; } var tokenTypes = { LEFT_BRACE: "LEFT_BRACE", RIGHT_BRACE: "RIGHT_BRACE", LEFT_BRACKET: "LEFT_BRACKET", RIGHT_BRACKET: "RIGHT_BRACKET", COLON: "COLON", COMMA: "COMMA", STRING: "STRING", NUMBER: "NUMBER", TRUE: "TRUE", FALSE: "FALSE", NULL: "NULL" }; var charTokens = { "{": tokenTypes.LEFT_BRACE, "}": tokenTypes.RIGHT_BRACE, "[": tokenTypes.LEFT_BRACKET, "]": tokenTypes.RIGHT_BRACKET, ":": tokenTypes.COLON, ",": tokenTypes.COMMA }; var keywordsTokens = { "true": tokenTypes.TRUE, "false": tokenTypes.FALSE, "null": tokenTypes.NULL }; var stringStates = { _START_: 0, START_QUOTE_OR_CHAR: 1, ESCAPE: 2 }; var escapes = { "\"": 0, "\\": 1, "/": 2, "b": 3, "f": 4, "n": 5, "r": 6, "t": 7, "u": 8 }; var numberStates = { _START_: 0, MINUS: 1, ZERO: 2, DIGIT_1TO9: 3, DIGIT_CEIL: 4, POINT: 5, DIGIT_FRACTION: 6, EXP: 7, EXP_PLUS: 8, EXP_MINUS: 9, EXP_DIGIT: 10 }; var isDigit1to9 = function isDigit1to9(char) { return char >= "1" && char <= "9"; }; var isDigit = function isDigit(char) { return char >= "0" && char <= "9"; }; var isHex = function isHex(char) { return char >= "0" && char <= "9" || char >= "a" && char <= "f" || char >= "A" && char <= "F"; }; var isExp = function isExp(char) { return char === "e" || char === "E"; }; var isUnicode = function isUnicode(char) { return char === "u" || char === "U"; }; var Tokenizer = function () { function Tokenizer(source) { _classCallCheck(this, Tokenizer); this.source = source; this.line = 1; this.column = 1; this.index = 0; this.currentToken = null; this.currentValue = null; var tokens = []; while (this.index < this.source.length) { var line = this.line; var column = this.column; var index = this.index; if (this._testWhitespace()) { continue; } var matched = this._testChar() || this._testKeyword() || this._testString() || this._testNumber(); if (matched) { tokens.push({ type: this.currentToken, value: this.currentValue, position: position(line, column, index, this.line, this.column, this.index) }); this.currentValue = null; } else { throw new SyntaxError(exceptionsDict.tokenizeSymbolError.replace("{char}", this.source.charAt(this.index)).replace("{line}", this.line.toString()).replace("{column}", this.column.toString())); } } return tokens; } _createClass(Tokenizer, [ { key: "_testWhitespace", value: function _testWhitespace() { var char = this.source.charAt(this.index); if (this.source.charAt(this.index) === "\r" && this.source.charAt(this.index + 1) === "\n") { this.index += 2; this.line++; this.column = 1; return true; } else if (char === "\r" || char === "\n") { this.index++; this.line++; this.column = 1; return true; } else if (char === "\t" || char === " ") { this.index++; this.column++; return true; } else { return false; } } }, { key: "_testChar", value: function _testChar() { var char = this.source.charAt(this.index); if (char in charTokens) { this.index++; this.column++; this.currentToken = charTokens[char]; return true; } else { return false; } } }, { key: "_testKeyword", value: function _testKeyword() { var _this = this; var matched = Object.keys(keywordsTokens).filter(function (name) { return name === _this.source.substr(_this.index, name.length); }); if (matched.length) { var _length = matched.length; this.index += _length; this.column += _length; this.currentToken = keywordsTokens[matched[0]]; return true; } else { return false; } } }, { key: "_testString", value: function _testString() { var index = this.index; var buffer = ""; var state = stringStates._START_; while (true) { var char = this.source.charAt(this.index); switch (state) { case stringStates._START_: if (char === "\"") { state = stringStates.START_QUOTE_OR_CHAR; this.index++; } else { return false; } break; case stringStates.START_QUOTE_OR_CHAR: if (char === "\\") { state = stringStates.ESCAPE; buffer += char; this.index++; } else if (char === "\"") { this.index++; this.column += this.index - index; this.currentToken = tokenTypes.STRING; this.currentValue = buffer; return true; } else { buffer += char; this.index++; } break; case stringStates.ESCAPE: if (char in escapes) { buffer += char; this.index++; if (isUnicode(char)) { for (var i = 0; i < 4; i++) { var curChar = this.source.charAt(this.index); if (curChar && isHex(curChar)) { buffer += curChar; this.index++; } else { return false; } } } state = stringStates.START_QUOTE_OR_CHAR; } else { return false; } break; } } } }, { key: "_testNumber", value: function _testNumber() { var index = this.index; var buffer = ""; var passedValue = undefined; var state = numberStates._START_; iterator: while (true) { var char = this.source.charAt(index); switch (state) { case numberStates._START_: if (char === "-") { state = numberStates.MINUS; buffer += char; index++; } else if (char === "0") { state = numberStates.ZERO; buffer += char; index++; passedValue = buffer; } else if (isDigit1to9(char)) { state = numberStates.DIGIT_1TO9; buffer += char; index++; passedValue = buffer; } else { break iterator; } break; case numberStates.MINUS: if (char === "0") { state = numberStates.ZERO; buffer += char; index++; passedValue = buffer; } else if (isDigit1to9(char)) { state = numberStates.DIGIT_1TO9; buffer += char; index++; passedValue = buffer; } else { break iterator; } break; case numberStates.ZERO: if (char === ".") { state = numberStates.POINT; buffer += char; index++; } else if (isExp(char)) { state = numberStates.EXP; buffer += char; index++; } else { break iterator; } break; case numberStates.DIGIT_1TO9: case numberStates.DIGIT_CEIL: if (isDigit(char)) { state = numberStates.DIGIT_CEIL; buffer += char; index++; passedValue = buffer; } else if (char === ".") { state = numberStates.POINT; buffer += char; index++; } else if (isExp(char)) { state = numberStates.EXP; buffer += char; index++; } else { break iterator; } break; case numberStates.POINT: if (isDigit(char)) { state = numberStates.DIGIT_FRACTION; buffer += char; index++; passedValue = buffer; } else { break iterator; } break; case numberStates.DIGIT_FRACTION: if (isDigit(char)) { buffer += char; index++; passedValue = buffer; } else if (isExp(char)) { state = numberStates.EXP; buffer += char; index++; } else { break iterator; } break; case numberStates.EXP: if (char === "+") { state = numberStates.EXP_PLUS; buffer += char; index++; } else if (char === "-") { state = numberStates.EXP_MINUS; buffer += char; index++; } else if (isDigit(char)) { state = numberStates.EXP_DIGIT; buffer += char; index++; passedValue = buffer; } else { break iterator; } break; case numberStates.EXP_PLUS: case numberStates.EXP_MINUS: case numberStates.EXP_DIGIT: if (isDigit(char)) { state = numberStates.EXP_DIGIT; buffer += char; index++; passedValue = buffer; } else { break iterator; } break; } } if (passedValue) { this.index += passedValue.length; this.column += passedValue.length; this.currentToken = tokenTypes.NUMBER; this.currentValue = passedValue; return true; } else { return false; } } } ]); return Tokenizer; }(); Tokenizer.LEFT_BRACE = tokenTypes.LEFT_BRACE; Tokenizer.RIGHT_BRACE = tokenTypes.RIGHT_BRACE; Tokenizer.LEFT_BRACKET = tokenTypes.LEFT_BRACKET; Tokenizer.RIGHT_BRACKET = tokenTypes.RIGHT_BRACKET; Tokenizer.COLON = tokenTypes.COLON; Tokenizer.COMMA = tokenTypes.COMMA; Tokenizer.STRING = tokenTypes.STRING; Tokenizer.NUMBER = tokenTypes.NUMBER; Tokenizer.TRUE = tokenTypes.TRUE; Tokenizer.FALSE = tokenTypes.FALSE; Tokenizer.NULL = tokenTypes.NULL; var objectStates = { _START_: 0, OPEN_OBJECT: 1, KEY: 2, COLON: 3, VALUE: 4, COMMA: 5, CLOSE_OBJECT: 6 }; var arrayStates = { _START_: 0, OPEN_ARRAY: 1, VALUE: 2, COMMA: 3, CLOSE_ARRAY: 4 }; var defaultSettings = { verbose: true }; var JsonParser = function () { function JsonParser(source, settings) { _classCallCheck(this, JsonParser); this.settings = Object.assign(defaultSettings, settings); this.tokenList = new Tokenizer(source); this.index = 0; var json = this._parseValue(); if (json) { return json; } else { throw new SyntaxError(exceptionsDict.emptyString); } } _createClass(JsonParser, [ { key: "_parseObject", value: function _parseObject() { var startToken = undefined; var property = undefined; var object = { type: "object", properties: [] }; var state = objectStates._START_; while (true) { var token = this.tokenList[this.index]; switch (state) { case objectStates._START_: if (token.type === Tokenizer.LEFT_BRACE) { startToken = token; state = objectStates.OPEN_OBJECT; this.index++; } else { return null; } break; case objectStates.OPEN_OBJECT: if (token.type === Tokenizer.STRING) { property = { type: "property" }; if (this.settings.verbose) { property.key = { type: "key", position: token.position, value: token.value }; } else { property.key = { type: "key", value: token.value }; } state = objectStates.KEY; this.index++; } else if (token.type === Tokenizer.RIGHT_BRACE) { if (this.settings.verbose) { object.position = position(startToken.position.start.line, startToken.position.start.column, startToken.position.start.char, token.position.end.line, token.position.end.column, token.position.end.char); } this.index++; return object; } else { return null; } break; case objectStates.KEY: if (token.type == Tokenizer.COLON) { state = objectStates.COLON; this.index++; } else { return null; } break; case objectStates.COLON: var value = this._parseValue(); if (value !== null) { property.value = value; object.properties.push(property); state = objectStates.VALUE; } else { return null; } break; case objectStates.VALUE: if (token.type === Tokenizer.RIGHT_BRACE) { if (this.settings.verbose) { object.position = position(startToken.position.start.line, startToken.position.start.column, startToken.position.start.char, token.position.end.line, token.position.end.column, token.position.end.char); } this.index++; return object; } else if (token.type === Tokenizer.COMMA) { state = objectStates.COMMA; this.index++; } else { return null; } break; case objectStates.COMMA: if (token.type === Tokenizer.STRING) { property = { type: "property" }; if (this.settings.verbose) { property.key = { type: "key", position: token.position, value: token.value }; } else { property.key = { type: "key", value: token.value }; } state = objectStates.KEY; this.index++; } else { return null; } } } } }, { key: "_parseArray", value: function _parseArray() { var startToken = undefined; var value = undefined; var array = { type: "array", items: [] }; var state = arrayStates._START_; while (true) { var token = this.tokenList[this.index]; switch (state) { case arrayStates._START_: if (token.type === Tokenizer.LEFT_BRACKET) { startToken = token; state = arrayStates.OPEN_ARRAY; this.index++; } else { return null; } break; case arrayStates.OPEN_ARRAY: value = this._parseValue(); if (value !== null) { array.items.push(value); state = arrayStates.VALUE; } else if (token.type === Tokenizer.RIGHT_BRACKET) { if (this.settings.verbose) { array.position = position(startToken.position.start.line, startToken.position.start.column, startToken.position.start.char, token.position.end.line, token.position.end.column, token.position.end.char); } this.index++; return array; } else { return null; } break; case arrayStates.VALUE: if (token.type === Tokenizer.RIGHT_BRACKET) { if (this.settings.verbose) { array.position = position(startToken.position.start.line, startToken.position.start.column, startToken.position.start.char, token.position.end.line, token.position.end.column, token.position.end.char); } this.index++; return array; } else if (token.type === Tokenizer.COMMA) { state = arrayStates.COMMA; this.index++; } else { return null; } break; case arrayStates.COMMA: value = this._parseValue(); if (value !== null) { array.items.push(value); state = arrayStates.VALUE; } else { return null; } break; } } } }, { key: "_parseValue", value: function _parseValue() { var token = this.tokenList[this.index]; var tokenType = undefined; switch (token.type) { case Tokenizer.STRING: tokenType = "string"; break; case Tokenizer.NUMBER: tokenType = "number"; break; case Tokenizer.TRUE: tokenType = "true"; break; case Tokenizer.FALSE: tokenType = "false"; break; case Tokenizer.NULL: tokenType = "null"; } var objectOrArray = this._parseObject() || this._parseArray(); if (tokenType !== undefined) { this.index++; if (this.settings.verbose) { return { type: tokenType, value: token.value, position: token.position }; } else { return { type: tokenType, value: token.value }; } } else if (objectOrArray !== null) { return objectOrArray; } else { throw new Error("!!!!!"); } } } ]); return JsonParser; }(); return JsonParser; }(); module.exports = JsonParser; module.exports.buildMap = function (str, filename) { function loc(node) { return [ filename, node.position.start.line, node.position.start.column ].join(":"); } function walk(node, map, path) { path = path ? path + "." : ""; switch (node.type) { case "object": node.properties.forEach(function (property) { map[path + property.key.value] = loc(property.value); walk(property.value, map, path + property.key.value); }); break; case "array": node.items.forEach(function (item, idx) { map[path + idx] = loc(item); walk(item, map, path + idx); }); break; } return map; } ; var result = {}; try { result = walk(new JsonParser(str), {}); } catch (e) { console.error("JSON parse error:", e); } return result; }; }, "6.js": function (exports, module, basis, global, __filename, __dirname, require, resource, asset) { var hasOwnProperty = Object.prototype.hasOwnProperty; var consts = basis.require("./7.js"); var namespaces = basis.require("./8.js"); var MARKER = consts.MARKER; var TYPE_ELEMENT = consts.TYPE_ELEMENT; var TYPE_ATTRIBUTE = consts.TYPE_ATTRIBUTE; var TYPE_ATTRIBUTE_CLASS = consts.TYPE_ATTRIBUTE_CLASS; var TYPE_ATTRIBUTE_STYLE = consts.TYPE_ATTRIBUTE_STYLE; var TYPE_ATTRIBUTE_EVENT = consts.TYPE_ATTRIBUTE_EVENT; var TYPE_TEXT = consts.TYPE_TEXT; var TYPE_COMMENT = consts.TYPE_COMMENT; var TYPE_CONTENT = consts.TYPE_CONTENT; var TOKEN_TYPE = consts.TOKEN_TYPE; var TOKEN_BINDINGS = consts.TOKEN_BINDINGS; var TOKEN_REFS = consts.TOKEN_REFS; var ATTR_NAME = consts.ATTR_NAME; var ATTR_NAME_BY_TYPE = consts.ATTR_NAME_BY_TYPE; var ELEMENT_NAME = consts.ELEMENT_NAME; var ELEMENT_ATTRIBUTES_AND_CHILDREN = consts.ELEMENT_ATTRIBUTES_AND_CHILDREN; var CONTENT_CHILDREN = consts.CONTENT_CHILDREN; var CLASS_BINDING_ENUM = consts.CLASS_BINDING_ENUM; var CLASS_BINDING_BOOL = consts.CLASS_BINDING_BOOL; var CLASS_BINDING_INVERT = consts.CLASS_BINDING_INVERT; var inlineSeed = 1; var tmplFunctions = {}; var SET_NONELEMENT_PROPERTY_SUPPORT = function () { try { global.document.createTextNode("").x = 1; return true; } catch (e) { return false; } }(); function cleanSpecial(tokens, offset) { var result = []; for (var i = 0; i < tokens.length; i++) { if (i < offset) { result.push(tokens[i]); continue; } var token = tokens[i]; switch (token[TOKEN_TYPE]) { case TYPE_ELEMENT: result.push(cleanSpecial(token, ELEMENT_ATTRIBUTES_AND_CHILDREN)); break; case TYPE_CONTENT: result.push.apply(result, cleanSpecial(token, CONTENT_CHILDREN).slice(CONTENT_CHILDREN)); break; default: result.push(token); } } return result; } var buildPathes = function () { var PATH_REF_NAME = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".split(""); var pathList; var refList; var bindingList; var markedElementList; var rootPath; var attrExprId; function putRefs(refs, pathIdx) { for (var i = 0, refName; refName = refs[i]; i++) if (refName.indexOf(":") == -1) refList.push(refName + ":" + pathIdx); } function putPath(path) { var len = pathList.length; var pathRef = PATH_REF_NAME[len] || "r" + len; pathList.push(pathRef + "=" + path); return pathRef; } function putBinding(binding) { bindingList.push(binding); } function processTokens(tokens, path, noTextBug) { var localPath; var refs; var myRef; var explicitRef; var bindings; for (var i = 0, cp = 0, closeText = 0, token; token = tokens[i]; i++, cp++, explicitRef = false) { if (!i) localPath = path + ".firstChild"; else { if (!tokens[i + 1]) localPath = path + ".lastChild"; else { if (token[TOKEN_TYPE] == tokens[i - 1][TOKEN_TYPE] && token[TOKEN_TYPE] == TYPE_TEXT) closeText++; localPath = path + ".childNodes[" + (noTextBug ? cp : cp + (closeText ? " + " + closeText + " * TEXT_BUG" : "")) + "]"; } } if (refs = token[TOKEN_REFS]) { explicitRef = true; localPath = putPath(localPath); putRefs(refs, localPath); } if (token[TOKEN_BINDINGS]) { if (token[TOKEN_BINDINGS] && typeof token[TOKEN_BINDINGS] == "number") token[TOKEN_BINDINGS] = token[TOKEN_REFS][token[TOKEN_BINDINGS] - 1]; if (!explicitRef) { explicitRef = true; localPath = putPath(localPath); } putBinding([ token[TOKEN_TYPE], localPath, token[TOKEN_BINDINGS], refs ? refs.indexOf("element") != -1 : false ]); } if (path == rootPath && (SET_NONELEMENT_PROPERTY_SUPPORT || token[TOKEN_TYPE] == TYPE_ELEMENT)) markedElementList.push(localPath + "." + MARKER); if (token[TOKEN_TYPE] == TYPE_ELEMENT) { myRef = -1; if (!explicitRef) { localPath = putPath(localPath); myRef = pathList.length; } var attrs = []; var children = []; for (var j = ELEMENT_ATTRIBUTES_AND_CHILDREN, t; t = token[j]; j++) if (t[TOKEN_TYPE] == TYPE_ELEMENT || t[TOKEN_TYPE] == TYPE_TEXT || t[TOKEN_TYPE] == TYPE_COMMENT) children.push(t); else attrs.push(t); for (var j = 0, attr; attr = attrs[j]; j++) { var attrTokenType = attr[TOKEN_TYPE]; if (attrTokenType == TYPE_ATTRIBUTE_EVENT) continue; var attrName = ATTR_NAME_BY_TYPE[attrTokenType] || attr[ATTR_NAME]; if (refs = attr[TOKEN_REFS]) { explicitRef = true; putRefs(refs, putPath(localPath + ".getAttributeNode(\"" + attrName + "\")")); } if (bindings = attr[TOKEN_BINDINGS]) { explicitRef = true; switch (attrTokenType) { case TYPE_ATTRIBUTE_CLASS: for (var k = 0, binding; binding = bindings[k]; k++) putBinding([ 2, localPath, binding[1], attrName, binding[0] ].concat(binding[2] == -1 ? [] : binding.slice(2))); break; case TYPE_ATTRIBUTE_STYLE: for (var k = 0, property; property = bindings[k]; k++) { attrExprId++; for (var m = 0, bindName; bindName = property[0][m]; m++) putBinding([ 2, localPath, bindName, attrName, property[0], property[1], property[2], property[3], attrExprId ]); } break; default: attrExprId++; for (var k = 0, bindName; bindName = bindings[0][k]; k++) putBinding([ 2, localPath, bindName, attrName, bindings[0], bindings[1], token[ELEMENT_NAME], attrExprId ]); } } } if (children.length) processTokens(children, localPath, noTextBug); if (!explicitRef && myRef == pathList.length) pathList.pop(); } } } return function (tokens, path, noTextBug) { pathList = []; refList = []; bindingList = []; markedElementList = []; rootPath = path || "_"; attrExprId = 0; processTokens(tokens, rootPath, noTextBug); return { path: pathList, ref: refList, binding: bindingList, markedElementList: markedElementList }; }; }(); var buildBindings = function () { var L10N_BINDING = /\.\{([a-zA-Z_][a-zA-Z0-9_\-]*)\}/; var SPECIAL_ATTR_MAP = { disabled: "*", checked: ["input"], indeterminate: ["input"], value: [ "input", "textarea", "select" ], minlength: ["input"], maxlength: ["input"], readonly: ["input"], selected: ["option"], multiple: ["select"] }; var SPECIAL_ATTR_SINGLE = { disabled: true, checked: true, selected: true, readonly: true, multiple: true, indeterminate: true }; var STYLE_EXPR_VALUE = { "show": "\"none\"", "visible": "\"hidden\"" }; var STYLE_EXPR_TOGGLE = { "hide": "?\"none\":\"\"", "show": "?\"\":\"none\"", "hidden": "?\"hidden\":\"\"", "visible": "?\"\":\"hidden\"" }; var bindFunctions = { 1: "bind_element", 3: "bind_textNode", 8: "bind_comment" }; function quoteString(value) { return "\"" + value.replace(/"/g, "\\\"").replace(/\n/g, "\\n").replace(/\r/g, "\\r") + "\""; } function simpleStringify(val) { return typeof val == "string" ? quoteString(val) : val; } function stringifyBindingNames(val) { if (val.indexOf("l10n:") == 0) val = this[val.substr(5)] || val; return quoteString(val); } function buildAttrExpression(binding, special, l10n) { var expression = []; var cond = []; var symbols = binding[5]; var dictionary = binding[4]; var exprVar; var colonPos; for (var j = 0; j < symbols.length; j++) { if (typeof symbols[j] == "string") expression.push(quoteString(symbols[j])); else { exprVar = dictionary[symbols[j]]; colonPos = exprVar.indexOf(":"); if (colonPos == -1) { expression.push(special == "l10n" ? "\"{" + exprVar + "}\"" : special == "bool" ? "(__" + exprVar + "||\"\")" : "__" + exprVar); if (!special) cond.push("__" + exprVar + "!==UNSET&&__" + exprVar + "!==undefined"); } else { var bindingName = null; var l10nPath = exprVar.substr(colonPos + 1).replace(L10N_BINDING, function (m, name) { bindingName = name; return ""; }); if (bindingName) { if (l10n === false) return false; expression.push(l10n[exprVar.substr(colonPos + 1)]); if (!special) cond.push(l10n[exprVar.substr(colonPos + 1)] + "!==undefined"); } else expression.push("l10n[\"" + l10nPath + "\"]"); } } } if (expression.length == 1) expression.push("\"\""); expression = expression.join("+"); if (!special && cond.length) expression = cond.join("&&") + "?(" + expression + "):\"\""; return expression; } return function (bindings) { function putBindCode(type) { toolsUsed[type] = true; bindCode.push(bindVar + "=" + type + "(" + basis.array(arguments, 1) + ");"); } var bindMap = {}; var bindCode; var bindVar; var bindVarSeed = 0; var varList = []; var bindingsWoL10nCompute = []; var l10nComputeBindings = []; var varName; var l10nMap; var l10nCompute = []; var l10nBindings = {}; var l10nBindSeed = 0; var attrExprId; var attrExprMap = {}; var debugList = []; var toolsUsed = {}; for (var i = 0, binding; binding = bindings[i]; i++) { var bindName = binding[2]; var namePart = bindName.split(":"); if (namePart[0] == "l10n" && namePart[1]) { var l10nFullPath = namePart[1]; var l10nBinding = null; var l10nName = l10nFullPath.replace(L10N_BINDING, function (m, name) { l10nBinding = name; return ""; }); if (l10nBinding) { l10nComputeBindings.push(binding); if (l10nFullPath in l10nBindings == false) { varName = "$l10n_" + l10nBindSeed++; l10nBindings[l10nFullPath] = varName; l10nCompute.push(varName); varList.push(varName + "=tools.l10nToken(\"" + l10nName + "\").computeToken()"); bindCode = bindMap[l10nBinding]; if (!bindCode) { bindCode = bindMap[l10nBinding] = []; varList.push("__" + l10nBinding + "=UNSET"); } bindCode.push(varName + ".set(__" + l10nBinding + ");"); } continue; } } bindingsWoL10nCompute.push(binding); } for (var i = 0, binding; binding = l10nComputeBindings[i]; i++) { var bindType = binding[0]; var domRef = binding[1]; var bindName = binding[2]; var nodeBindingProhibited = binding[3]; var l10nFullPath = bindName.split(":")[1]; bindName = l10nBindings[l10nFullPath]; bindVar = "_" + bindVarSeed++; varName = "__" + bindName; bindCode = bindMap[bindName]; if (!bindCode) { bindCode = bindMap[bindName] = []; varList.push(varName); } if (bindType == TYPE_TEXT) { debugList.push("{" + [ "binding:\"" + bindName + "\"", "dom:" + domRef, "val:" + bindVar, "l10n:true", "attachment:" + bindName ] + "}"); varList.push(bindVar + "=" + domRef); putBindCode(bindFunctions[bindType], domRef, bindVar, "value", nodeBindingProhibited); } else { var expr = buildAttrExpression(binding, false, l10nBindings); attrExprId = binding[7]; if (!attrExprMap[attrExprId]) { varList.push(bindVar); attrExprMap[attrExprId] = bindVar; } bindVar = attrExprMap[attrExprId]; attrName = "\"" + binding[ATTR_NAME] + "\""; debugList.push("{" + [ "binding:\"" + bindName + "\"", "raw:" + bindName + ".get()", "l10n:true", "type:\"l10n\"", "expr:[[" + binding[5].map(simpleStringify) + "],[" + binding[4].map(simpleStringify) + "],[" + binding[4].map(stringifyBindingNames, l10nBindings) + "]]", "dom:" + domRef, "attr:" + attrName, "val:" + bindVar, "attachment:" + bindName ] + "}"); putBindCode("bind_attr", domRef, attrName, bindVar, expr); } } for (var i = 0, binding; binding = bindingsWoL10nCompute[i]; i++) { var bindType = binding[0]; var domRef = binding[1]; var bindName = binding[2]; var nodeBindingProhibited = binding[3]; if ([ "get", "set", "templateId_" ].indexOf(bindName) != -1) { basis.dev.warn("binding name `" + bindName + "` is prohibited, binding ignored"); continue; } var namePart = bindName.split(":"); var anim = namePart[0] == "anim"; var l10n = namePart[0] == "l10n"; if (anim) bindName = namePart[1]; bindCode = hasOwnProperty.call(bindMap, bindName) ? bindMap[bindName] : null; bindVar = "_" + bindVarSeed++; varName = "__" + bindName; if (l10n && namePart[1]) { var l10nFullPath = namePart[1]; var l10nBinding = null; var l10nName = l10nFullPath; if (!l10nMap) l10nMap = {}; if (!bindMap[l10nName]) { bindMap[l10nName] = []; bindMap[l10nName].l10n = "$l10n_" + l10nBindSeed++; varList.push("__" + bindMap[l10nName].l10n + "=l10n[\"" + l10nName + "\"]"); l10nMap[l10nName] = []; } bindCode = bindMap[l10nName]; if (bindType == TYPE_TEXT) { debugList.push("{" + [ "binding:\"" + l10nFullPath + "\"", "dom:" + domRef, "val:l10n[\"" + l10nName + "\"]", "l10n:true", "attachment:l10nToken(\"" + l10nName + "\")" ] + "}"); toolsUsed.l10nToken = true; l10nMap[l10nName].push(domRef + ".nodeValue=value;"); if (!bindCode.nodeBind) { varList.push(bindVar + "=" + domRef); putBindCode(bindFunctions[bindType], domRef, bindVar, "value", nodeBindingProhibited); bindCode.nodeBind = bindVar; } else { bindCode.push(domRef + ".nodeValue=value;"); } continue; } else { var expr = buildAttrExpression(binding, "l10n", false); if (expr !== false) { l10nMap[l10nName].push("bind_attr(" + [ domRef, "\"" + binding[ATTR_NAME] + "\"", "NaN", expr ] + ");"); } } } if (!bindCode) { bindCode = bindMap[bindName] = []; varList.push(varName + "=UNSET"); } if (bindType != TYPE_ATTRIBUTE) { debugList.push("{" + [ "binding:\"" + bindName + "\"", "dom:" + domRef, "val:" + (bindCode.nodeBind ? varName : bindVar), "updates:$$" + bindName, "attachment:instance.attaches&&instance.attaches[\"" + bindName + "\"]&&instance.attaches[\"" + bindName + "\"].value" ] + "}"); if (!bindCode.nodeBind) { varList.push(bindVar + "=" + domRef); putBindCode(bindFunctions[bindType], domRef, bindVar, "value", nodeBindingProhibited); bindCode.nodeBind = bindVar; } else { switch (bindType) { case TYPE_ELEMENT: putBindCode(bindFunctions[bindType], domRef, domRef, "value!==null?String(value):null"); break; case TYPE_TEXT: bindCode.push(domRef + ".nodeValue=value;"); break; } } } else { var attrName = binding[ATTR_NAME]; switch (attrName) { case "role-marker": varList.push(bindVar + "=\"\""); putBindCode("bind_attr", domRef, "\"" + attrName + "\"", bindVar, "value?value" + (binding[5][1] ? "+" + quoteString(binding[5][1]) : "") + ":\"\""); break; case "class": var defaultExpr = ""; var valueExpr = "value"; var bindingType = binding[5]; var defaultValue = binding[7]; switch (bindingType) { case CLASS_BINDING_BOOL: case CLASS_BINDING_INVERT: var values = [binding[6]]; var prefix = binding[4]; var classes = Array.isArray(prefix) ? prefix : values.map(function (val) { return prefix + val; }); valueExpr = (bindingType == CLASS_BINDING_INVERT ? "!" : "") + "value?\"" + classes[0] + "\":\"\""; if (defaultValue) defaultExpr = classes[defaultValue - 1]; break; case CLASS_BINDING_ENUM: var values = binding[8]; var prefix = binding[4]; var classes = Array.isArray(prefix) ? prefix : values.map(function (val) { return prefix + val; }); valueExpr = values.map(function (val, idx) { return "value==\"" + val + "\"?\"" + classes[idx] + "\""; }).join(":") + ":\"\""; if (defaultValue) defaultExpr = classes[defaultValue - 1]; break; default: var prefix = binding[4]; valueExpr = "typeof value==\"string\"||typeof value==\"number\"?\"" + prefix + "\"+value:(value?\"" + prefix + bindName + "\":\"\")"; } varList.push(bindVar + "=\"" + defaultExpr + "\""); putBindCode("bind_attrClass", domRef, bindVar, valueExpr, anim); debugList.push("{" + [ "binding:\"" + bindName + "\"", "raw:__" + bindName, "prefix:\"" + prefix + "\"", "anim:" + anim, "dom:" + domRef, "attr:\"" + attrName + "\"", "val:" + bindVar, "attachment:instance.attaches&&instance.attaches[\"" + bindName + "\"]&&instance.attaches[\"" + bindName + "\"].value" ] + "}"); break; case "style": var expr = buildAttrExpression(binding, "style", l10nBindings); attrExprId = binding[8]; if (!attrExprMap[attrExprId]) { attrExprMap[attrExprId] = bindVar; varList.push(bindVar + "=" + (STYLE_EXPR_VALUE[binding[7]] || "\"\"")); } if (binding[7]) expr = expr.replace(/\+""$/, "") + (STYLE_EXPR_TOGGLE[binding[7]] || ""); bindVar = attrExprMap[attrExprId]; putBindCode("bind_attrStyle", domRef, "\"" + binding[6] + "\"", bindVar, expr); debugList.push("{" + [ "binding:\"" + bindName + "\"", "raw:__" + bindName, "property:\"" + binding[6] + "\"", "expr:[[" + binding[5].map(simpleStringify) + "],[" + binding[4].map(simpleStringify) + "]]", "dom:" + domRef, "attr:\"" + attrName + "\"", "val:" + bindVar, "attachment:instance.attaches&&instance.attaches[\"" + bindName + "\"]&&instance.attaches[\"" + bindName + "\"].value" ] + "}"); break; default: var specialAttr = SPECIAL_ATTR_MAP[attrName]; var tagName = binding[6].toLowerCase(); var expr = specialAttr && SPECIAL_ATTR_SINGLE[attrName] ? buildAttrExpression(binding, "bool", l10nBindings) + "?\"" + attrName + "\":\"\"" : buildAttrExpression(binding, false, l10nBindings); attrExprId = binding[7]; if (!attrExprMap[attrExprId]) { varList.push(bindVar + "=UNSET"); attrExprMap[attrExprId] = bindVar; } bindVar = attrExprMap[attrExprId]; if (attrName == "tabindex") putBindCode("bind_attr", domRef, "\"" + attrName + "\"", bindVar, expr + "==-1?" + ([ "input", "button", "textarea" ].indexOf(tagName) == -1 ? "\"\"" : "-1") + ":" + expr); else { var namespace = namespaces.getNamespace(attrName); if (namespace) putBindCode("bind_attrNS", domRef, "\"" + namespace + "\"", "\"" + attrName + "\"", bindVar, expr); else putBindCode("bind_attr", domRef, "\"" + attrName + "\"", bindVar, expr); } if (specialAttr && (specialAttr == "*" || specialAttr.indexOf(tagName) != -1)) bindCode.push("if(" + domRef + "." + attrName + "!=" + bindVar + ")" + domRef + "." + attrName + "=" + (SPECIAL_ATTR_SINGLE[attrName] ? "!!" + bindVar : bindVar) + ";"); debugList.push("{" + [ "binding:\"" + bindName + "\"", "raw:" + (l10n ? "l10n[\"" + l10nFullPath + "\"]" : "__" + bindName), "type:\"" + (specialAttr && SPECIAL_ATTR_SINGLE[attrName] ? "bool" : "string") + "\"", "expr:[[" + binding[5].map(simpleStringify) + "],[" + binding[4].map(simpleStringify) + "],[" + binding[4].map(stringifyBindingNames, l10nBindings) + "]]", "dom:" + domRef, "attr:\"" + attrName + "\"", "val:" + bindVar, "attachment:instance.attaches&&instance.attaches[\"" + bindName + "\"]&&instance.attaches[\"" + bindName + "\"].value" ] + "}"); } } } var bindMapKeys = basis.object.keys(bindMap); var setFunction = ""; if (bindMapKeys.length) { toolsUsed.resolve = true; setFunction = [ ";function set(bindName,value){", "if(typeof bindName!=\"string\")" ]; for (var bindName in bindMap) if (bindMap[bindName].nodeBind) { setFunction.push("if(bindName===" + bindMap[bindName].nodeBind + ")" + "bindName=\"" + bindName + "\";" + "else "); } setFunction.push("return;", "rawValues[bindName]=value;", "value=resolve.call(instance,bindName,value,Attaches);", "switch(bindName){"); for (var bindName in bindMap) { var stateVar = bindMap[bindName].l10n || bindName; varList.push("$$" + stateVar + "=0"); setFunction.push("case\"" + bindName + "\":", "if(__" + stateVar + "!==value)", "{", "$$" + stateVar + "++;", "__" + stateVar + "=value;", bindMap[bindName].join(""), "}", "break;"); } setFunction = setFunction.join("") + "}}"; } var toolsVarList = []; for (var key in toolsUsed) toolsVarList.push(key + "=tools." + key); return { debugList: debugList, allKeys: bindMapKeys, keys: bindMapKeys.filter(function (key) { return key.indexOf("@") == -1; }), tools: toolsVarList, vars: varList, set: setFunction, l10n: l10nMap, l10nCompute: l10nCompute }; }; }(); function compileFunction(args, body) { try { return new Function(args, body); } catch (e) { basis.dev.error("Can't build template function: " + e + "\n", "function(" + args + "){\n" + body + "\n}"); } } var getFunctions = function (tokens, debug, uri, source, noTextBug) { var fn = tmplFunctions[uri && basis.path.relative(uri)]; if (fn) return fn; tokens = cleanSpecial(tokens, 0); var paths = buildPathes(tokens, "_", noTextBug); var bindings = buildBindings(paths.binding); var objectRefs = paths.markedElementList.join("="); var result = { keys: bindings.keys, l10nKeys: basis.object.keys(bindings.l10n) }; if (tokens.length == 1) paths.path[0] = "a=_"; if (!uri) uri = basis.path.baseURI + "inline_template" + inlineSeed++ + ".tmpl"; if (bindings.l10n) { var code = []; for (var key in bindings.l10n) code.push("case\"" + key + "\":" + bindings.l10n[key].join("") + "break;"); result.createL10nSync = compileFunction([ "_", "l10n", "bind_attr", "TEXT_BUG" ], (source ? "\n// " + source.split(/\r\n?|\n\r?/).join("\n// ") + "\n\n" : "") + "var " + paths.path + ";" + "return function(path, value){" + "switch(path){" + code.join("") + "}" + "}" + "\n\n//# sourceURL=" + basis.path.origin + uri + "_l10n"); } result.createInstanceFactory = compileFunction([ "tid", "createDOM", "tools", "l10nMap", "l10nMarkup", "getBindings", "TEXT_BUG" ], (source ? "\n// " + source.split(/\r\n?|\n\r?/).join("\n// ") + "\n\n" : "") + "var UNSET={valueOf:function(){}}," + (bindings.tools.length ? bindings.tools + "," : "") + (bindings.set ? "Attaches=function(){};" + "Attaches.prototype={" + bindings.keys.map(function (key) { return key + ":null"; }) + "};" : "set=function(){};") + "return function createTmpl_(id,instance,initL10n){" + "var _=createDOM()," + (bindings.l10n ? "l10n=initL10n?{}:l10nMap," : "") + paths.path.concat(bindings.vars) + ",rawValues={}" + (debug ? ";instance.debug=function debug(){" + "return {" + "bindings:[" + bindings.debugList + "]," + "values:{" + bindings.keys.map(function (key) { return "\"" + key + "\":__" + key; }) + "}," + "rawValues:rawValues," + (bindings.l10nCompute.length ? "compute:Array.prototype.slice.call(instance.compute)" : "compute:[]") + "}" + "}" : "") + (bindings.l10nCompute.length ? ";instance.compute=[" + bindings.l10nCompute + "]" : "") + ";instance.tmpl={" + [ paths.ref, "templateId_:id", "set:set" ] + "}" + (objectRefs ? ";if(instance.context||instance.onAction)" + objectRefs + "=(id<<12)|tid" : "") + bindings.set + (bindings.l10n ? ";if(initL10n){l10n=l10nMap;initL10n(set)}" + ";if(l10nMarkup.length)for(var idx=0,token;token=l10nMarkup[idx];idx++)set(token.path,token.token);" : "") + (bindings.set ? ";if(instance.bindings)instance.handler=getBindings(instance,set)" : "") + ";" + bindings.l10nCompute.map(function (varName) { return "set(\"" + varName + "\"," + varName + ")"; }) + "}" + "\n\n//# sourceURL=" + basis.path.origin + uri); return result; }; module.exports = { getFunctions: getFunctions }; }, "7.js": function (exports, module, basis, global, __filename, __dirname, require, resource, asset) { var MARKER = "basisTemplateId_" + basis.genUID(); var TYPE_ELEMENT = 1; var TYPE_ATTRIBUTE = 2; var TYPE_ATTRIBUTE_CLASS = 4; var TYPE_ATTRIBUTE_STYLE = 5; var TYPE_ATTRIBUTE_EVENT = 6; var TYPE_TEXT = 3; var TYPE_COMMENT = 8; var TYPE_CONTENT = 9; var TOKEN_TYPE = 0; var TOKEN_BINDINGS = 1; var TOKEN_REFS = 2; var ATTR_NAME = 3; var ATTR_VALUE = 4; var ATTR_NAME_BY_TYPE = { 4: "class", 5: "style" }; var ATTR_TYPE_BY_NAME = { "class": TYPE_ATTRIBUTE_CLASS, "style": TYPE_ATTRIBUTE_STYLE }; var ATTR_VALUE_INDEX = { 2: ATTR_VALUE, 4: ATTR_VALUE - 1, 5: ATTR_VALUE - 1, 6: 2 }; var CLASS_BINDING_ENUM = 1; var CLASS_BINDING_BOOL = 2; var CLASS_BINDING_INVERT = 3; var CLASS_BINDING_EQUAL = 4; var CLASS_BINDING_NOTEQUAL = 5; var ELEMENT_NAME = 3; var ELEMENT_ATTRIBUTES_AND_CHILDREN = 4; var TEXT_VALUE = 3; var COMMENT_VALUE = 3; var CONTENT_CHILDREN = 2; var CONTENT_PRIORITY = 1; var document = global.document; var CLONE_NORMALIZATION_TEXT_BUG = !document ? true : function () { var element = document.createElement("div"); element.appendChild(document.createTextNode("a")); element.appendChild(document.createTextNode("a")); return element.cloneNode(true).childNodes.length == 1; }(); module.exports = { MARKER: MARKER, TYPE_ELEMENT: TYPE_ELEMENT, TYPE_ATTRIBUTE: TYPE_ATTRIBUTE, TYPE_ATTRIBUTE_CLASS: TYPE_ATTRIBUTE_CLASS, TYPE_ATTRIBUTE_STYLE: TYPE_ATTRIBUTE_STYLE, TYPE_ATTRIBUTE_EVENT: TYPE_ATTRIBUTE_EVENT, TYPE_TEXT: TYPE_TEXT, TYPE_COMMENT: TYPE_COMMENT, TYPE_CONTENT: TYPE_CONTENT, TOKEN_TYPE: TOKEN_TYPE, TOKEN_BINDINGS: TOKEN_BINDINGS, TOKEN_REFS: TOKEN_REFS, ATTR_NAME: ATTR_NAME, ATTR_VALUE: ATTR_VALUE, ATTR_NAME_BY_TYPE: ATTR_NAME_BY_TYPE, ATTR_TYPE_BY_NAME: ATTR_TYPE_BY_NAME, ATTR_VALUE_INDEX: ATTR_VALUE_INDEX, ELEMENT_NAME: ELEMENT_NAME, ELEMENT_ATTRIBUTES_AND_CHILDREN: ELEMENT_ATTRIBUTES_AND_CHILDREN, TEXT_VALUE: TEXT_VALUE, COMMENT_VALUE: COMMENT_VALUE, CONTENT_CHILDREN: CONTENT_CHILDREN, CONTENT_PRIORITY: CONTENT_PRIORITY, CLASS_BINDING_ENUM: CLASS_BINDING_ENUM, CLASS_BINDING_BOOL: CLASS_BINDING_BOOL, CLASS_BINDING_INVERT: CLASS_BINDING_INVERT, CLASS_BINDING_EQUAL: CLASS_BINDING_EQUAL, CLASS_BINDING_NOTEQUAL: CLASS_BINDING_NOTEQUAL, CLONE_NORMALIZATION_TEXT_BUG: CLONE_NORMALIZATION_TEXT_BUG }; }, "8.js": function (exports, module, basis, global, __filename, __dirname, require, resource, asset) { var namespaceURI = { xlink: "http://www.w3.org/1999/xlink", svg: "http://www.w3.org/2000/svg" }; function getNamespace(name, node) { if (!name) return; var colonIndex = name.indexOf(":"); if (colonIndex != -1) { var prefix = name.substr(0, colonIndex); return namespaceURI[prefix] || node && node.lookupNamespaceURI(prefix); } } module.exports = { namespaceURI: namespaceURI, getNamespace: getNamespace }; }, "9.js": function (exports, module, basis, global, __filename, __dirname, require, resource, asset) { var namespace = "basis.template"; var document = global.document; var Class = basis.Class; var cleaner = basis.cleaner; var path = basis.path; var consts = basis.require("./7.js"); var DECLARATION_VERSION = basis.require("./a.js").VERSION; var getDeclFromSource = basis.require("./a.js").getDeclFromSource; var makeDeclaration = basis.require("./a.js").makeDeclaration; var setIsolatePrefixGenerator = basis.require("./a.js").setIsolatePrefixGenerator; var store = basis.require("./b.js"); var theme = basis.require("./c.js"); var getSourceByPath = theme.get; var templateList = []; var sourceByDocumentId = {}; function resolveSourceByDocumentId(sourceId) { var resource = sourceByDocumentId[sourceId]; if (!resource) { var host = document.getElementById(sourceId); var source = ""; if (host && host.tagName == "SCRIPT" && host.type == "text/basis-template") source = host.textContent || host.text; else if (!host) basis.dev.warn("Template script element with id `" + sourceId + "` not found"); else basis.dev.warn("Template should be declared in <script type=\"text/basis-template\"> element (id `" + sourceId + "`)"); resource = sourceByDocumentId[sourceId] = basis.resource.virtual("tmpl", source || ""); resource.id = sourceId; resource.url = "<script id=\"" + sourceId + "\"/>"; } return resource; } function resolveResource(ref, baseURI) { if (/^#\d+$/.test(ref)) return templateList[ref.substr(1)]; if (/^id:/.test(ref)) return resolveSourceByDocumentId(ref.substr(3)); if (/^[a-z0-9\.]+$/i.test(ref) && !/\.tmpl$/.test(ref)) return getSourceByPath(ref); return basis.resource(basis.resource.resolveURI(ref, baseURI, "<b:include src=\"{url}\"/>")); } function templateSourceUpdate() { if (this.destroyBuilder) buildTemplate.call(this); var cursor = this; while (cursor = cursor.attaches_) cursor.handler.call(cursor.context); } function buildTemplate() { var declaration = getDeclFromSource(this.source, this.baseURI, false, { isolate: this.getIsolatePrefix() }); var destroyBuilder = this.destroyBuilder; var instances = {}; var funcs = this.builder(declaration.tokens, instances); this.createInstance = funcs.createInstance; this.clearInstance = funcs.destroyInstance; this.destroyBuilder = funcs.destroy; store.add(this.templateId, this, instances); this.instances_ = instances; this.decl_ = declaration; var newDeps = declaration.deps; var oldDeps = this.deps_; this.deps_ = newDeps; if (oldDeps) for (var i = 0, dep; dep = oldDeps[i]; i++) dep.bindingBridge.detach(dep, templateSourceUpdate, this); if (newDeps) for (var i = 0, dep; dep = newDeps[i]; i++) dep.bindingBridge.attach(dep, templateSourceUpdate, this); var newResources = declaration.resources; var oldResources = this.resources; this.resources = newResources; if (newResources) for (var i = 0, item; item = newResources[i]; i++) { var resource = basis.resource(item.url).fetch(); if (typeof resource.startUse == "function") resource.startUse(); } if (oldResources) for (var i = 0, item; item = oldResources[i]; i++) { var resource = basis.resource(item.url).fetch(); if (typeof resource.stopUse == "function") resource.stopUse(); } if (destroyBuilder) destroyBuilder(true); } var Template = Class(null, { className: namespace + ".Template", __extend__: function (value) { if (value instanceof Template) return value; if (value instanceof TemplateSwitchConfig) return new TemplateSwitcher(value); return new Template(value); }, source: "", baseURI: "", url: "", attaches_: null, init: function (source) { if (templateList.length == 4096) throw "Too many templates (maximum 4096)"; this.setSource(source || ""); this.templateId = templateList.push(this) - 1; }, bindingBridge: { attach: function (template, handler, context) { var cursor = template; while (cursor = cursor.attaches_) if (cursor.handler === handler && cursor.context === context) basis.dev.warn("basis.template.Template#bindingBridge.attach: duplicate handler & context pair"); template.attaches_ = { handler: handler, context: context, attaches_: template.attaches_ }; }, detach: function (template, handler, context) { var cursor = template; var prev; while (prev = cursor, cursor = cursor.attaches_) if (cursor.handler === handler && cursor.context === context) { prev.attaches_ = cursor.attaches_; return; } basis.dev.warn("basis.template.Template#bindingBridge.detach: handler & context pair not found, nothing was removed"); }, get: function (template) { var source = template.source; return source && source.bindingBridge ? source.bindingBridge.get(source) : source; } }, createInstance: function (object, actionCallback, updateCallback, bindings, bindingInterface) { buildTemplate.call(this); return this.createInstance(object, actionCallback, updateCallback, bindings, bindingInterface); }, clearInstance: function () { }, getIsolatePrefix: function () { return "i" + this.templateId + "__"; }, setSource: function (source) { var oldSource = this.source; if (oldSource != source) { if (typeof source == "string") { var m = source.match(/^([a-z]+):/); if (m) { source = source.substr(m[0].length); switch (m[1]) { case "id": source = resolveSourceByDocumentId(source); break; case "path": source = getSourceByPath(source); break; default: basis.dev.warn(namespace + ".Template.setSource: Unknown prefix " + m[1] + " for template source was ingnored."); } } } if (oldSource && oldSource.bindingBridge) { this.url = ""; this.baseURI = ""; oldSource.bindingBridge.detach(oldSource, templateSourceUpdate, this); } if (source && source.bindingBridge) { if (source.url) { this.url = source.url; this.baseURI = path.dirname(source.url) + "/"; } source.bindingBridge.attach(source, templateSourceUpdate, this); } this.source = source; templateSourceUpdate.call(this); } }, destroy: function () { if (this.destroyBuilder) { store.remove(this.templateId); this.destroyBuilder(); } this.attaches_ = null; this.createInstance = null; this.resources = null; this.source = null; this.instances_ = null; this.decl_ = null; } }); var TemplateSwitchConfig = function (config) { basis.object.extend(this, config); }; var TemplateSwitcher = basis.Class(null, { className: namespace + ".TemplateSwitcher", ruleRet_: null, templates_: null, templateClass: Template, ruleEvents: null, rule: String, init: function (config) { this.ruleRet_ = []; this.templates_ = []; this.rule = config.rule; var events = config.events; if (events && events.length) { this.ruleEvents = {}; for (var i = 0, eventName; eventName = events[i]; i++) this.ruleEvents[eventName] = true; } cleaner.add(this); }, resolve: function (object) { var ret = this.rule(object); var idx = this.ruleRet_.indexOf(ret); if (idx == -1) { this.ruleRet_.push(ret); idx = this.templates_.push(new this.templateClass(ret)) - 1; } return this.templates_[idx]; }, destroy: function () { this.rule = null; this.templates_ = null; this.ruleRet_ = null; } }); function switcher(events, rule) { if (!rule) { rule = events; events = null; } if (typeof events == "string") events = events.split(/\s+/); return new TemplateSwitchConfig({ rule: rule, events: events }); } cleaner.add({ destroy: function () { for (var i = 0, template; template = templateList[i]; i++) template.destroy(); templateList = null; } }); module.exports = { DECLARATION_VERSION: DECLARATION_VERSION, TYPE_ELEMENT: consts.TYPE_ELEMENT, TYPE_ATTRIBUTE: consts.TYPE_ATTRIBUTE, TYPE_ATTRIBUTE_CLASS: consts.TYPE_ATTRIBUTE_CLASS, TYPE_ATTRIBUTE_STYLE: consts.TYPE_ATTRIBUTE_STYLE, TYPE_ATTRIBUTE_EVENT: consts.TYPE_ATTRIBUTE_EVENT, TYPE_TEXT: consts.TYPE_TEXT, TYPE_COMMENT: consts.TYPE_COMMENT, TYPE_CONTENT: consts.TYPE_CONTENT, TOKEN_TYPE: consts.TOKEN_TYPE, TOKEN_BINDINGS: consts.TOKEN_BINDINGS, TOKEN_REFS: consts.TOKEN_REFS, ATTR_NAME: consts.ATTR_NAME, ATTR_VALUE: consts.ATTR_VALUE, ATTR_NAME_BY_TYPE: consts.ATTR_NAME_BY_TYPE, CLASS_BINDING_ENUM: consts.CLASS_BINDING_ENUM, CLASS_BINDING_BOOL: consts.CLASS_BINDING_BOOL, CLASS_BINDING_INVERT: consts.CLASS_BINDING_INVERT, ELEMENT_NAME: consts.ELEMENT_NAME, ELEMENT_ATTRS: consts.ELEMENT_ATTRIBUTES_AND_CHILDREN, ELEMENT_ATTRIBUTES_AND_CHILDREN: consts.ELEMENT_ATTRIBUTES_AND_CHILDREN, TEXT_VALUE: consts.TEXT_VALUE, COMMENT_VALUE: consts.COMMENT_VALUE, CONTENT_CHILDREN: consts.CONTENT_CHILDREN, CONTENT_PRIORITY: consts.CONTENT_PRIORITY, TemplateSwitchConfig: TemplateSwitchConfig, TemplateSwitcher: TemplateSwitcher, Template: Template, switcher: switcher, getDeclFromSource: getDeclFromSource, makeDeclaration: makeDeclaration, resolveResource: resolveResource, setIsolatePrefixGenerator: setIsolatePrefixGenerator, getDebugInfoById: store.getDebugInfoById, getTemplateCount: function () { return templateList.length; }, resolveTemplateInfoByNode: function (node) { while (node) { if (node[consts.MARKER]) return store.resolveInfoById(node[consts.MARKER]); node = node.parentNode; } return null; }, resolveInfoById: store.resolveInfoById, resolveTemplateById: store.resolveTemplateById, resolveObjectById: store.resolveObjectById, resolveTmplById: store.resolveTmplById, SourceWrapper: theme.SourceWrapper, Theme: theme.Theme, theme: theme.theme, getThemeList: theme.getThemeList, currentTheme: theme.currentTheme, setTheme: theme.setTheme, onThemeChange: theme.onThemeChange, define: theme.define, get: theme.get, getPathList: theme.getPathList }; }, "a.js": function (exports, module, basis, global, __filename, __dirname, require, resource, asset) { var hasOwnProperty = Object.prototype.hasOwnProperty; var arraySearch = basis.array.search; var arrayAdd = basis.array.add; var tokenize = basis.require("./13.js"); var isolateCss = basis.require("./14.js"); var consts = basis.require("./7.js"); var utils = basis.require("./15.js"); var refUtils = basis.require("./16.js"); var styleUtils = basis.require("./18.js"); var attrUtils = basis.require("./19.js"); var walk = basis.require("./17.js").walk; var TYPE_ELEMENT = consts.TYPE_ELEMENT; var TYPE_ATTRIBUTE = consts.TYPE_ATTRIBUTE; var TYPE_ATTRIBUTE_CLASS = consts.TYPE_ATTRIBUTE_CLASS; var TYPE_TEXT = consts.TYPE_TEXT; var TYPE_COMMENT = consts.TYPE_COMMENT; var TYPE_CONTENT = consts.TYPE_CONTENT; var TOKEN_TYPE = consts.TOKEN_TYPE; var TOKEN_BINDINGS = consts.TOKEN_BINDINGS; var TOKEN_REFS = consts.TOKEN_REFS; var ATTR_VALUE_INDEX = consts.ATTR_VALUE_INDEX; var ELEMENT_ATTRIBUTES_AND_CHILDREN = consts.ELEMENT_ATTRIBUTES_AND_CHILDREN; var TEXT_VALUE = consts.TEXT_VALUE; var CONTENT_PRIORITY = consts.CONTENT_PRIORITY; var CONTENT_CHILDREN = consts.CONTENT_CHILDREN; var resourceHash = utils.resourceHash; var getTokenName = utils.getTokenName; var bindingList = utils.bindingList; var refList = refUtils.refList; var addTokenRef = refUtils.addTokenRef; var normalizeRefs = refUtils.normalizeRefs; var applyAttrs = attrUtils.applyAttrs; var styleNamespaceIsolate = styleUtils.styleNamespaceIsolate; var isolateTokens = styleUtils.isolateTokens; var topLevelInstructions = [ "define", "isolate", "l10n", "style" ]; var humanTopLevelInstrcutionList = topLevelInstructions.map(function (name) { return "<b:" + name + ">"; }).join(", ").replace(/, (<b:[a-z]+>)$/, " and $1"); var elementHandlers = { content: basis.require("./1a.js"), define: basis.require("./1b.js"), include: basis.require("./1c.js"), isolate: basis.require("./1d.js"), l10n: basis.require("./1e.js"), style: basis.require("./1f.js"), svg: basis.require("./1g.js"), text: basis.require("./1h.js") }; var Template = function () { }; var resolveResource = function () { }; var genIsolateMarker = function () { return basis.genUID() + "__"; }; var makeDeclaration = function () { var includeStack = []; var styleNamespaceResource = {}; function process(tokens, template, options) { var result = []; for (var i = 0, token, item; token = tokens[i]; i++) { var refs = refList(token); var bindings = bindingList(token); switch (token.type) { case TYPE_ELEMENT: if (token.prefix == "b") { if (topLevelInstructions.indexOf(token.name) === -1) options.allowTopInstruction = false; else if (!options.allowTopInstruction) utils.addTemplateWarn(template, options, "Instruction tag <b:" + token.name + "> should be placed in the beginning of template before any markup or instructions other than " + humanTopLevelInstrcutionList + ". Currently it may works but will be ignored in future.", token.loc); if (!elementHandlers.hasOwnProperty(token.name)) { utils.addTemplateWarn(template, options, "Unknown instruction tag: <b:" + token.name + ">", token.loc); continue; } elementHandlers[token.name](template, options, token, result); continue; } options.allowTopInstruction = false; item = [ 1, bindings, refs, getTokenName(token) ]; applyAttrs(template, options, item, token.attrs); item.push.apply(item, process(token.children, template, options)); break; case TYPE_TEXT: if (refs && refs.length == 2 && arraySearch(refs, "element")) bindings = refs[+!refs.lastSearchIndex]; item = [ 3, bindings, refs ]; if (!refs || token.value != "{" + refs.join("|") + "}") item.push(token.value); break; case TYPE_COMMENT: if (options.optimizeSize && !bindings && !refs) continue; item = [ 8, bindings, refs ]; if (!options.optimizeSize) if (!refs || token.value != "{" + refs.join("|") + "}") item.push(token.value); break; default: utils.addTemplateWarn(template, options, "Unknown token type: " + token.type, token); continue; } options.allowTopInstruction = false; utils.addTokenLocation(template, options, item, token); item.sourceToken = token; result.push(item); } return result; } function absl10n(value, dictURI, l10nMap) { if (typeof value == "string") { var parts = value.split(":"); var key = parts[1]; if (key && parts[0] == "l10n") { if (parts.length == 2 && key.indexOf("@") == -1) { if (!dictURI) return false; key = key + "@" + dictURI; value = "l10n:" + key; } arrayAdd(l10nMap, key); } } return value; } function applyDefines(ast, template, options) { walk(ast, function (nodeType, node) { var bindings = node[TOKEN_BINDINGS]; switch (nodeType) { case TYPE_ELEMENT: applyDefines(node, template, options, ELEMENT_ATTRIBUTES_AND_CHILDREN); break; case TYPE_TEXT: if (bindings) { var binding = absl10n(bindings, options.dictURI, template.l10n); node[TOKEN_BINDINGS] = binding || 0; if (binding === false) { utils.addTemplateWarn(template, options, "Dictionary for l10n binding on text node can't be resolved: {" + bindings + "}", node.loc); node[TEXT_VALUE] = "{" + bindings + "}"; } } break; case TYPE_ATTRIBUTE: if (bindings) { var array = bindings[0]; for (var j = array.length - 1; j >= 0; j--) { var binding = absl10n(array[j], options.dictURI, template.l10n); if (binding === false) { utils.addTemplateWarn(template, options, "Dictionary for l10n binding on attribute can't be resolved: {" + array[j] + "}", node.loc); var expr = bindings[1]; for (var k = 0; k < expr.length; k++) if (typeof expr[k] == "number") { if (expr[k] == j) expr[k] = "{" + array[j] + "}"; else if (expr[k] > j) expr[k] = expr[k] - 1; } array.splice(j, 1); if (!array.length) node[TOKEN_BINDINGS] = 0; } else array[j] = binding; } } break; case TYPE_ATTRIBUTE_CLASS: if (bindings) { for (var k = 0, bind; bind = bindings[k]; k++) { if (bind.length > 2) continue; utils.addTokenLocation(template, options, bind, bind.info_); var bindNameParts = bind[1].split(":"); var bindName = bindNameParts.pop(); var bindPrefix = bindNameParts.pop() || ""; if (hasOwnProperty.call(options.defines, bindName)) { var define = options.defines[bindName]; bind[1] = (bindPrefix ? bindPrefix + ":" : "") + define[0]; bind.push.apply(bind, define.slice(1)); define.used = true; } else { bind.push(0); utils.addTemplateWarn(template, options, "Unpredictable class binding: " + bind[0] + "{" + bind[1] + "}", bind.loc); } } if (options.optimizeSize) { var valueIdx = ATTR_VALUE_INDEX[nodeType]; if (!node[valueIdx]) node.length = valueIdx; } } break; } }); } function findElementCandidateNode(ast) { function find(node, offset) { for (var i = offset; i < node.length; i++) { var child = node[i]; var type = child[TOKEN_TYPE]; var result; if (type == TYPE_ELEMENT || type == TYPE_TEXT) return child; if (type == TYPE_COMMENT) if (child[TOKEN_REFS] || child[TOKEN_BINDINGS]) return child; if (type == TYPE_CONTENT) { result = find(child, CONTENT_CHILDREN); if (result) return result; } } return null; } return find(ast, 0); } return function makeDeclaration(source, baseURI, options, sourceUrl, sourceOrigin) { var source_ = source; options = basis.object.slice(options); options.Template = Template; options.genIsolateMarker = genIsolateMarker; options.resolveResource = resolveResource; options.getDeclFromSource = getDeclFromSource; options.makeDeclaration = makeDeclaration; options.process = process; options.includeStack = includeStack; options.includeOptions = options.includeOptions || {}; options.templates = {}; options.defines = {}; options.dictURI = sourceUrl ? basis.path.resolve(sourceUrl) : baseURI || ""; options.allowTopInstruction = true; options.styleNSIsolateMap = {}; options.loc = true; options.range = true; if (options.dictURI) { var extname = basis.path.extname(options.dictURI); if (extname && extname != ".l10n") options.dictURI = options.dictURI.substr(0, options.dictURI.length - extname.length) + ".l10n"; } var result = { sourceUrl: sourceUrl, baseURI: baseURI || "", tokens: null, includes: [], deps: [], templates: {}, isolate: false, styleNSPrefix: {}, resources: [], l10n: [], warns: [] }; result.removals = []; result.states = {}; if (!source) source = ""; if (!Array.isArray(source)) source = tokenize(String(source || ""), { loc: !!options.loc, range: !!options.range }); if (source.warns) source.warns.forEach(function (warn) { utils.addTemplateWarn(result, options, warn[0], warn[1].loc); }); includeStack.push(sourceOrigin !== true && sourceOrigin || {}); result.tokens = process(source, result, options); includeStack.pop(); result.tokens.source_ = source_ !== undefined ? source_ : source && source.source_; result.tokens.push([ TYPE_CONTENT, 0 ]); var tokenRefMap = normalizeRefs(result.tokens); var elementCandidateNode = findElementCandidateNode(result.tokens); var contentNodeRef = tokenRefMap[":content"]; if (contentNodeRef.node[CONTENT_PRIORITY] > 1) contentNodeRef.node[CONTENT_PRIORITY] = 1; contentNodeRef.overrided.forEach(function (overridedContentNodeRef) { var nodeIndex = overridedContentNodeRef.parent.indexOf(overridedContentNodeRef.node); if (nodeIndex != -1) overridedContentNodeRef.parent.splice.apply(overridedContentNodeRef.parent, [ nodeIndex, 1 ].concat(overridedContentNodeRef.node.slice(CONTENT_CHILDREN))); if (overridedContentNodeRef.node[consts.CONTENT_PRIORITY] > 0) result.removals.push({ reason: "<b:content/>", removeToken: contentNodeRef.node, includeToken: overridedContentNodeRef.node.includeToken, token: overridedContentNodeRef.node, node: overridedContentNodeRef.node }); }); if (!elementCandidateNode) { elementCandidateNode = [ TYPE_TEXT, 0, 0 ]; result.tokens.unshift(elementCandidateNode); } if (!tokenRefMap.element) addTokenRef(elementCandidateNode, "element"); applyDefines(result.tokens, result, options); if (/^[^a-z_-]/i.test(result.isolate)) basis.dev.error("basis.template: isolation prefix `" + result.isolate + "` should not starts with symbol other than letter, underscore or dash, otherwise it leads to incorrect css class names and broken styles"); if (includeStack.length == 0) { isolateTokens(result.tokens, result.isolate || "", result, options); if (result.removals) { var warns = result.warns; result.warns = []; result.removals.forEach(function (item) { isolateTokens([item.token], result.isolate || "", result, options); }); result.warns = warns; } for (var key in result.styleNSPrefix) { var styleNSPrefix = result.styleNSPrefix[key]; if (!styleNSPrefix.used) utils.addTemplateWarn(result, options, "Unused namespace: " + styleNSPrefix.name, styleNSPrefix.loc); } if (result.isolate) for (var i = 0, item; item = result.resources[i]; i++) if (item.type == "style" && item.isolate !== styleNamespaceIsolate) item.isolate = result.isolate + item.isolate; var originalResources = result.resources; result.resources = result.resources.filter(function (item, idx, array) { return item.url && !basis.array.search(array, resourceHash(item), resourceHash, idx + 1); }).map(function (item) { if (item.type != "style") { return { type: item.type, url: item.url }; } var url = item.url; var isolate = item.isolate; var namespaceIsolate = isolate === styleNamespaceIsolate; var cssMap; if (namespaceIsolate) { isolate = styleNamespaceIsolate[url]; if (url in styleNamespaceResource) { item.url = styleNamespaceResource[url].url; return { type: "style", url: styleNamespaceResource[url].url }; } } if (!isolate) { item.url = url; return { type: "style", url: url }; } var resource = basis.resource.virtual("css", "").ready(function (cssResource) { cssResource.url = url + "?isolate-prefix=" + isolate; cssResource.baseURI = basis.path.dirname(url) + "/"; cssResource.map = cssMap; sourceResource(); }); var sourceResource = basis.resource(url).ready(function (cssResource) { var isolated = isolateCss(cssResource && cssResource.cssText || "", isolate, true); if (typeof global.btoa == "function") isolated.css += "\n/*# sourceMappingURL=data:application/json;base64," + global.btoa("{\"version\":3,\"sources\":[\"" + basis.path.origin + url + "\"]," + "\"mappings\":\"AAAA" + basis.string.repeat(";AACA", isolated.css.split("\n").length) + "\"}") + " */"; cssMap = isolated.map; resource.update(isolated.css); }); if (namespaceIsolate) styleNamespaceResource[url] = resource; item.url = resource.url; return { type: "style", url: resource.url }; }); result.styles = originalResources.map(function (item) { var sourceUrl = item.url || utils.getTokenAttrValues(item.token).src; return { resource: item.url || false, sourceUrl: sourceUrl ? basis.resource.resolveURI(sourceUrl, baseURI) : null, isolate: item.isolate === styleNamespaceIsolate ? styleNamespaceIsolate[item.url] : item.isolate || false, namespace: item.namespace || false, inline: item.inline, styleToken: item.token, includeToken: item.includeToken }; }); } for (var key in options.defines) { var define = options.defines[key]; if (!define.used) utils.addTemplateWarn(result, options, "Unused define: " + key, define.loc); } if (!result.warns.length) result.warns = false; return result; }; }(); function cloneDecl(array) { var result = []; if (array.source_) result.source_ = array.source_; for (var i = 0; i < array.length; i++) result.push(Array.isArray(array[i]) ? cloneDecl(array[i]) : array[i]); return result; } function getDeclFromSource(source, baseURI, clone, options) { var result = source; var sourceUrl; if (source.bindingBridge) { baseURI = "baseURI" in source ? source.baseURI : "url" in source ? basis.path.dirname(source.url) : baseURI; sourceUrl = "url" in source ? source.url : sourceUrl; result = source.bindingBridge.get(source); } if (Array.isArray(result)) { if (clone) result = cloneDecl(result); result = { tokens: result }; } else { if (result && (typeof result != "object" || !Array.isArray(result.tokens))) result = String(result); } if (!result || typeof result == "string") result = makeDeclaration(result, baseURI, options, sourceUrl, source); return result; } basis.resource("./9.js").ready(function (exports) { resolveResource = exports.resolveResource; Template = exports.Template; }); module.exports = { VERSION: 3, makeDeclaration: makeDeclaration, walk: walk, getDeclFromSource: getDeclFromSource, setIsolatePrefixGenerator: function (fn) { genIsolateMarker = fn; } }; }, "13.js": function (exports, module, basis, global, __filename, __dirname, require, resource, asset) { var consts = basis.require("./7.js"); var TYPE_ELEMENT = consts.TYPE_ELEMENT; var TYPE_ATTRIBUTE = consts.TYPE_ATTRIBUTE; var TYPE_TEXT = consts.TYPE_TEXT; var TYPE_COMMENT = consts.TYPE_COMMENT; var ATTR_TYPE_BY_NAME = consts.ATTR_TYPE_BY_NAME; var SYNTAX_ERROR = "Invalid or unsupported syntax"; var TEXT = /((?:.|[\r\n])*?)(\{(?:l10n:([a-zA-Z_][a-zA-Z0-9_\-]*(?:\.[a-zA-Z_][a-zA-Z0-9_\-]*)*(?:\.\{[a-zA-Z_][a-zA-Z0-9_\-]*\})?)\})?|<(\/|!--(\s*\{)?)?|$)/g; var TAG_NAME = /([a-z_][a-z0-9\-_]*)(:|\{|\s*(\/?>)?)/ig; var ATTRIBUTE_NAME_OR_END = /([a-z_][a-z0-9_\-]*)(:|\{|=|\s*)|(\/?>)/ig; var COMMENT = /(.|[\r\n])*?-->/g; var CLOSE_TAG = /([a-z_][a-z0-9_\-]*(?::[a-z_][a-z0-9_\-]*)?)>/ig; var REFERENCE = /([a-z_][a-z0-9_]*)(\||\}\s*)/ig; var ATTRIBUTE_VALUE = /"((?:(\\")|[^"])*?)"\s*/g; var QUOTE_UNESCAPE = /\\"/g; var BREAK_TAG_PARSE = /^/g; var SINGLETON_TAG = /^(area|base|br|col|command|embed|hr|img|input|link|meta|param|source)$/i; var TAG_IGNORE_CONTENT = { text: /((?:.|[\r\n])*?)(?:<\/b:text>|$)/g, style: /((?:.|[\r\n])*?)(?:<\/b:style>|$)/g }; var ATTR_BINDING = /\{([a-z_][a-z0-9_]*|l10n:[a-z_][a-z0-9_]*(?:\.[a-z_][a-z0-9_]*)*(?:\.\{[a-z_][a-z0-9_]*\})?)\}/i; var CLASS_ATTR_BINDING = /^((?:[a-z_][a-z0-9_\-]*)?(?::(?:[a-z_][a-z0-9_\-]*)?)?)\{((anim:)?[a-z_][a-z0-9_\-]*)\}$/i; var STYLE_ATTR_PARTS = /\s*[^:]+?\s*:(?:\(.*?\)|".*?"|'.*?'|[^;]+?)+(?:;|$)/gi; var STYLE_PROPERTY = /\s*([^:]+?)\s*:((?:\(.*?\)|".*?"|'.*?'|[^;]+?)+);?$/i; var STYLE_ATTR_BINDING = /\{([a-z_][a-z0-9_]*)\}/i; var ATTRIBUTE_MODE = /^(?:|append-|set-|remove-)(class|attr)$/; var decodeHTMLTokens = function () { var tokenMap = {}; var tokenElement = !basis.NODE_ENV ? global.document.createElement("div") : null; var NAMED_CHARACTER_REF = /&([a-z]+\d*|#\d+|#x[0-9a-f]{1,4});?/gi; if (basis.NODE_ENV) tokenMap = __nodejsRequire("./htmlentity.json"); function namedCharReplace(m, token) { if (!tokenMap[token]) { if (token.charAt(0) == "#") { tokenMap[token] = String.fromCharCode(token.charAt(1) == "x" || token.charAt(1) == "X" ? parseInt(token.substr(2), 16) : token.substr(1)); } else { if (tokenElement) { tokenElement.innerHTML = m; tokenMap[token] = tokenElement.firstChild ? tokenElement.firstChild.nodeValue : m; } } } return tokenMap[token] || m; } return function decodeHTMLTokens(string) { return String(string).replace(NAMED_CHARACTER_REF, namedCharReplace); }; }(); function buildAttrExpression(parts) { var bindName; var names = []; var expression = []; var map = {}; for (var j = 0; j < parts.length; j++) if (j % 2) { bindName = parts[j]; if (!map[bindName]) { map[bindName] = names.length; names.push(bindName); } expression.push(map[bindName]); } else { if (parts[j]) expression.push(decodeHTMLTokens(parts[j])); } return [ names, expression ]; } function processAttr(token, mode, convertRange) { var value = token.value; var bindings = 0; var parts; var m; if (value) { switch (mode) { case "class": var pos = token.valueRange.start_; var rx = /(\s*)(\S+)/g; var newValue = []; var partMap = []; var binding; bindings = []; while (part = rx.exec(value)) { var val = part[2]; var valInfo = { value: val, binding: false, range: { start_: pos += part[1].length, end_: pos += val.length } }; convertRange(valInfo); if (m = val.match(CLASS_ATTR_BINDING)) { binding = [ m[1] || "", m[2] ]; binding.info_ = valInfo; valInfo.binding = true; bindings.push(binding); } else newValue.push(val); partMap.push(valInfo); } value = newValue.join(" "); token.map_ = partMap; break; case "style": var props = []; bindings = []; if (parts = value.match(STYLE_ATTR_PARTS)) { for (var j = 0, part; part = parts[j]; j++) { var m = part.match(STYLE_PROPERTY); var propertyName = m[1]; var value = m[2].trim(); var valueParts = value.split(STYLE_ATTR_BINDING); if (valueParts.length > 1) { var expr = buildAttrExpression(valueParts); expr.push(propertyName); bindings.push(expr); } else props.push(propertyName + ": " + decodeHTMLTokens(value)); } } else { if (/\S/.test(value)) basis.dev.warn("Bad value for style attribute (value ignored):", value); } value = props.join("; "); if (value) value += ";"; break; default: parts = value.split(ATTR_BINDING); if (parts.length > 1) bindings = buildAttrExpression(parts); else value = decodeHTMLTokens(value); } } if (bindings && !bindings.length) bindings = 0; token.binding = bindings; token.value = value; token.type = ATTR_TYPE_BY_NAME[mode] || TYPE_ATTRIBUTE; } function postProcessing(tokens, options, source) { function tokenName(token) { return (token.prefix ? token.prefix + ":" : "") + token.name; } function getTokenAttrs(token) { return token.attrs.reduce(function (res, attr) { res[tokenName(attr)] = attr.value; return res; }, {}); } function buildLocationIndex() { var line = 1; var column = 0; lineIdx = new Array(source.length); columnIdx = new Array(source.length); for (var i = 0; i < source.length + 1; i++) { lineIdx[i] = line; columnIdx[i] = column; if (source[i] === "\n") { line++; column = 0; } else column++; } } function findLocationByOffset(offset) { return { line: lineIdx[offset], column: columnIdx[offset] }; } function getLocationFromRange(range) { return { start: findLocationByOffset(range.start_), end: findLocationByOffset(range.end_) }; } function convertRange(token) { if (options.loc) { token.loc = getLocationFromRange(token.range); if (token.valueRange) token.valueLoc = getLocationFromRange(token.valueRange); } if (options.range) { token.range = [ token.range.start_, token.range.end_ ]; if (token.valueRange) token.valueRange = [ token.valueRange.start_, token.valueRange.end_ ]; } else { delete token.range; delete token.valueRange; } } function walk(tokens) { var token; var prev; for (var i = 0; token = tokens[i++]; prev = token) { if (token.type == TYPE_ELEMENT) { var attrs = getTokenAttrs(token); for (var j = 0, attr; attr = token.attrs[j++];) { var mode = attr.name; if (token.prefix == "b" && attr.name == "value") { var m = token.name.match(ATTRIBUTE_MODE); if (m) mode = m[1] == "class" ? "class" : attrs.name; } processAttr(attr, mode, convertRange); convertRange(attr); } walk(token.children); } if (token.type == TYPE_TEXT) { token.value = decodeHTMLTokens(token.value); if (!token.refs && prev && prev.type == TYPE_TEXT && !prev.refs) { prev.value += token.value; prev.end_ = token.end_; tokens.splice(--i, 1); } } if (token.type == TYPE_COMMENT) { token.value = decodeHTMLTokens(token.value); } convertRange(token); } } var lineIdx; var columnIdx; if (options.loc) buildLocationIndex(); walk(tokens); } function tokenize(source, options) { var result = []; var tagStack = []; var lastTag = { children: result }; var parseTag = false; var token; var state = TEXT; var pos = 0; var textStateEndPos = 0; var textEndPos; var bufferPos; var startPos; var m; var attrMap; result.source_ = source; result.warns = []; if (!options || options.trim !== false) { pos = textStateEndPos = source.match(/^\s*/)[0].length; source = source.trimRight(); } while (pos < source.length || state != TEXT) { state.lastIndex = pos; startPos = pos; m = state.exec(source); if (!m || m.index !== pos) { if (state == REFERENCE && token && token.type == TYPE_COMMENT) { state = COMMENT; continue; } if (parseTag) lastTag = tagStack.pop(); if (token) lastTag.children.pop(); if (token = lastTag.children.pop()) { if (token.type == TYPE_TEXT && !token.refs) textStateEndPos -= token.value.length; else lastTag.children.push(token); } parseTag = false; state = TEXT; continue; } pos = state.lastIndex; switch (state) { case TEXT: textEndPos = startPos + m[1].length; if (textStateEndPos != textEndPos) { var sourceText = textStateEndPos == startPos ? m[1] : source.substring(textStateEndPos, textEndPos); sourceText = sourceText.replace(/\s*(\r\n?|\n\r?)\s*/g, ""); if (sourceText) lastTag.children.push({ type: TYPE_TEXT, value: sourceText, range: { start_: textStateEndPos, end_: textEndPos } }); } textStateEndPos = textEndPos; if (m[3]) { lastTag.children.push({ type: TYPE_TEXT, refs: ["l10n:" + m[3]], value: "{l10n:" + m[3] + "}", range: { start_: textEndPos, end_: pos } }); } else if (m[2] == "{") { bufferPos = pos - 1; lastTag.children.push(token = { type: TYPE_TEXT, range: { start_: textEndPos, end_: textEndPos } }); state = REFERENCE; } else if (m[4]) { if (m[4] == "/") { token = null; state = CLOSE_TAG; } else { lastTag.children.push(token = { type: TYPE_COMMENT, range: { start_: textEndPos, end_: textEndPos } }); if (m[5]) { bufferPos = pos - m[5].length; state = REFERENCE; } else { bufferPos = pos; state = COMMENT; } } } else if (m[2]) { parseTag = true; tagStack.push(lastTag); lastTag.children.push(token = { type: TYPE_ELEMENT, attrs: [], children: [], range: { start_: textEndPos, end_: textEndPos } }); lastTag = token; state = TAG_NAME; attrMap = {}; } break; case CLOSE_TAG: if (m[1] !== (lastTag.prefix ? lastTag.prefix + ":" : "") + lastTag.name) { lastTag.children.push({ type: TYPE_TEXT, value: "</" + m[0], range: { start_: startPos - 2, end_: startPos + m[0].length } }); result.warns.push([ "Wrong close tag: " + source.substr(startPos - 2, m[0].length + 2), lastTag.children[lastTag.children.length - 1] ]); } else { lastTag.range.end_ = startPos + m[0].length; lastTag = tagStack.pop(); } state = TEXT; break; case TAG_NAME: case ATTRIBUTE_NAME_OR_END: if (m[2] == ":") { if (token.prefix) state = BREAK_TAG_PARSE; else token.prefix = m[1]; break; } if (m[1]) { token.name = m[1]; token.range.end_ = startPos + m[1].length; if (token.type == TYPE_ATTRIBUTE) { var fullName = (token.prefix ? token.prefix + ":" : "") + token.name; if (Object.prototype.hasOwnProperty.call(attrMap, fullName)) result.warns.push([ "Duplicate attribute: " + fullName, token ]); attrMap[fullName] = true; lastTag.attrs.push(token); } } if (m[2] == "{") { if (token.type == TYPE_ELEMENT) state = REFERENCE; else state = BREAK_TAG_PARSE; break; } if (m[3]) { parseTag = false; lastTag.range.end_ = pos; if (m[3] == "/>" || !lastTag.prefix && SINGLETON_TAG.test(lastTag.name)) { if (m[3] != "/>") result.warns.push([ "Tag <" + lastTag.name + "> doesn't closed explicit (use `/>` as tag ending)", lastTag ]); lastTag = tagStack.pop(); } else { if (lastTag.prefix == "b" && lastTag.name in TAG_IGNORE_CONTENT) { state = TAG_IGNORE_CONTENT[lastTag.name]; break; } } state = TEXT; break; } if (m[2] == "=") { state = ATTRIBUTE_VALUE; break; } token = { type: TYPE_ATTRIBUTE, range: { start_: pos, end_: pos } }; state = ATTRIBUTE_NAME_OR_END; break; case COMMENT: token.value = source.substring(bufferPos, pos - 3); token.range.end_ = pos; state = TEXT; break; case REFERENCE: if (token.refs) token.refs.push(m[1]); else token.refs = [m[1]]; if (m[2] != "|") { if (token.type == TYPE_TEXT) { pos -= m[2].length - 1; token.value = source.substring(bufferPos, pos); token.range.end_ = pos; state = TEXT; } else if (token.type == TYPE_COMMENT) { state = COMMENT; } else if (token.type == TYPE_ATTRIBUTE && source[pos] == "=") { pos++; state = ATTRIBUTE_VALUE; } else { token = { type: TYPE_ATTRIBUTE, range: { start_: pos, end_: pos } }; state = ATTRIBUTE_NAME_OR_END; } } break; case ATTRIBUTE_VALUE: token.value = m[1].replace(QUOTE_UNESCAPE, "\""); token.range.end_ = pos; token.valueRange = { start_: startPos + 1, end_: startPos + 1 + m[1].length }; token = { type: TYPE_ATTRIBUTE, range: { start_: pos, end_: pos } }; state = ATTRIBUTE_NAME_OR_END; break; case TAG_IGNORE_CONTENT.text: case TAG_IGNORE_CONTENT.style: lastTag.children.push({ type: TYPE_TEXT, value: m[1], range: { start_: startPos, end_: startPos + m[1].length } }); lastTag = tagStack.pop(); state = TEXT; break; default: throw SYNTAX_ERROR; } if (state == TEXT) textStateEndPos = pos; } if (textStateEndPos != pos) lastTag.children.push({ type: TYPE_TEXT, value: source.substring(textStateEndPos, pos), range: { start_: textStateEndPos, end_: pos } }); postProcessing(result, options || {}, source); if (lastTag.name) result.warns.push([ "No close tag for <" + (lastTag.prefix ? lastTag.prefix + ":" : "") + lastTag.name + ">", lastTag ]); if (!result.warns.length) result.warns = false; result.templateTokens = true; return result; } ; module.exports = tokenize; }, "14.js": function (exports, module, basis, global, __filename, __dirname, require, resource, asset) { var CSS_CLASSNAME_START = /^\-?([_a-z]|[^\x00-\xb1]|\\[0-9a-f]{1,6}(\r\n|[ \n\r\t\f])?|\\[^\n\r\f0-9a-f])/i; var CSS_CLASSNAME_START_MAXLEN = 8; var CSS_NESTED_ATRULE = /^(media|supports|document)\b/i; var CSS_NESTED_ATRULE_MAXLEN = 8; var CSS_FNSELECTOR = /^(not|has|matches|nth-child|nth-last-child)\(/i; var CSS_FNSELECTOR_MAXLEN = 15; function genIsolateMarker() { return basis.genUID() + "__"; } function isolateCss(css, prefix, info) { function jumpTo(str, offset) { var index = css.indexOf(str, offset); i = index !== -1 ? index + str.length - 1 : sym.length; } function parseString() { var quote = sym[i]; if (quote !== "\"" && quote !== "'") return; for (i++; i < len && sym[i] !== quote; i++) if (sym[i] === "\\") i++; return true; } function parseBraces() { var bracket = sym[i]; if (bracket === "(") { jumpTo(")", i + 1); return true; } if (bracket === "[") { for (i++; i < len && sym[i] !== "]"; i++) parseString(); return true; } } function parseComment() { if (sym[i] !== "/" || sym[i + 1] !== "*") return; jumpTo("*/", i + 2); return true; } function parsePseudoContent() { for (; i < len && sym[i] != ")"; i++) if (parseComment() || parseBraces() || parsePseudo() || parseClassName()) continue; } function parsePseudo() { if (sym[i] !== ":") return; var m = css.substr(i + 1, CSS_FNSELECTOR_MAXLEN).match(CSS_FNSELECTOR); if (m) { i += m[0].length + 1; parsePseudoContent(); } return true; } function parseAtRule() { if (sym[i] !== "@") return; var m = css.substr(i + 1, CSS_NESTED_ATRULE_MAXLEN).match(CSS_NESTED_ATRULE); if (m) { i += m[0].length; nestedStyleSheet = true; } return true; } function parseBlock() { if (sym[i] !== "{") return; if (nestedStyleSheet) { i++; parseStyleSheet(true); return; } for (i++; i < len && sym[i] !== "}"; i++) parseComment() || parseString() || parseBraces(); return true; } function parseClassName() { if (sym[i] !== ".") return; var m = css.substr(i + 1, CSS_CLASSNAME_START_MAXLEN).match(CSS_CLASSNAME_START); if (m) { i++; map[i + result.length / 2 * prefix.length - 1] = i; result.push(css.substring(lastMatchPos, i), prefix); lastMatchPos = i; } return true; } function parseStyleSheet(nested) { for (nestedStyleSheet = false; i < len; i++) { if (parseComment() || parseAtRule() || parsePseudo() || parseBraces() || parseString() || parseClassName()) continue; if (nested && sym[i] == "}") return; parseBlock(); } } var map = {}; var result = []; var sym = css.split(""); var len = sym.length; var lastMatchPos = 0; var i = 0; var nestedStyleSheet; if (!prefix) prefix = genIsolateMarker(); parseStyleSheet(false); result = result.join("") + css.substring(lastMatchPos); return info ? { css: result, map: map, prefix: prefix } : result; } module.exports = isolateCss; }, "15.js": function (exports, module, basis, global, __filename, __dirname, require, resource, asset) { var arrayAdd = basis.array.add; function resourceHash(resource) { return [ resource.type, resource.url, resource.isolate ].join(";"); } function addUnique(array, items) { for (var i = 0; i < items.length; i++) arrayAdd(array, items[i]); } function getTokenName(token) { return (token.prefix ? token.prefix + ":" : "") + token.name; } function bindingList(token) { var refs = token.refs; return refs && refs.length ? refs[0] : 0; } function getTokenAttrValues(token) { var result = {}; if (token.attrs) for (var i = 0, attr; attr = token.attrs[i]; i++) result[getTokenName(attr)] = attr.value; return result; } function getTokenAttrs(token) { var result = {}; if (token.attrs) for (var i = 0, attr; attr = token.attrs[i]; i++) result[getTokenName(attr)] = attr; return result; } function parseOptionsValue(str) { var result = {}; var pairs = (str || "").trim().split(/\s*,\s*/); for (var i = 0; i < pairs.length; i++) { var pair = pairs[i].split(/\s*:\s*/); if (pair.length != 2) { return {}; } result[pair[0]] = pair[1]; } return result; } function getLocation(template, loc) { if (loc) return (template.sourceUrl || "") + ":" + loc.start.line + ":" + (loc.start.column + 1); } function addTemplateWarn(template, options, message, loc) { if (loc && options.loc) { message = Object(message); message.loc = typeof loc == "string" ? loc : getLocation(template, loc); } template.warns.push(message); } function addTokenLocation(template, options, dest, source) { if (options.loc && source && source.loc && !dest.loc) dest.loc = getLocation(template, source.loc); } module.exports = { resourceHash: resourceHash, addUnique: addUnique, getTokenName: getTokenName, bindingList: bindingList, getTokenAttrValues: getTokenAttrValues, getTokenAttrs: getTokenAttrs, parseOptionsValue: parseOptionsValue, getLocation: getLocation, addTemplateWarn: addTemplateWarn, addTokenLocation: addTokenLocation }; }, "16.js": function (exports, module, basis, global, __filename, __dirname, require, resource, asset) { var arrayAdd = basis.array.add; var walk = basis.require("./17.js").walk; var consts = basis.require("./7.js"); var TYPE_ATTRIBUTE_EVENT = consts.TYPE_ATTRIBUTE_EVENT; var TYPE_CONTENT = consts.TYPE_CONTENT; var CONTENT_PRIORITY = consts.CONTENT_PRIORITY; var TOKEN_BINDINGS = consts.TOKEN_BINDINGS; var TOKEN_REFS = consts.TOKEN_REFS; function refList(token) { var array = token.refs; if (array && array.length) return array; return 0; } function addTokenRef(token, refName) { if (!token[TOKEN_REFS]) token[TOKEN_REFS] = []; arrayAdd(token[TOKEN_REFS], refName); if (refName != "element" && !token[TOKEN_BINDINGS]) token[TOKEN_BINDINGS] = token[TOKEN_REFS].length == 1 ? refName : 0; } function removeTokenRef(token, refName) { var idx = token[TOKEN_REFS].indexOf(refName); if (idx != -1) { var indexBinding = token[TOKEN_BINDINGS] && typeof token[TOKEN_BINDINGS] == "number"; token[TOKEN_REFS].splice(idx, 1); if (indexBinding) if (idx == token[TOKEN_BINDINGS] - 1) { token[TOKEN_BINDINGS] = refName; indexBinding = false; } if (!token[TOKEN_REFS].length) token[TOKEN_REFS] = 0; else { if (indexBinding) token[TOKEN_BINDINGS] -= idx < token[TOKEN_BINDINGS] - 1; } } } function normalizeRefs(nodes) { var map = {}; walk(nodes, function (type, node, parent) { if (type === TYPE_CONTENT) { var contentNodeRef = map[":content"]; if (!contentNodeRef) { map[":content"] = { parent: parent, node: node, overrided: [] }; } else { if (node[CONTENT_PRIORITY] >= contentNodeRef.node[CONTENT_PRIORITY]) { contentNodeRef.overrided.push({ parent: contentNodeRef.parent, node: contentNodeRef.node }); contentNodeRef.parent = parent; contentNodeRef.node = node; } else { contentNodeRef.overrided.push({ parent: parent, node: node }); } } } else if (type !== TYPE_ATTRIBUTE_EVENT) { var refs = node[TOKEN_REFS]; if (!refs) return; for (var j = refs.length - 1, refName; refName = refs[j]; j--) { if (refName.indexOf(":") != -1) { removeTokenRef(node, refName); continue; } if (map[refName]) removeTokenRef(map[refName].node, refName); if (node[TOKEN_BINDINGS] == refName) node[TOKEN_BINDINGS] = j + 1; map[refName] = { parent: parent, node: node }; } } }); return map; } module.exports = { refList: refList, addTokenRef: addTokenRef, removeTokenRef: removeTokenRef, normalizeRefs: normalizeRefs }; }, "17.js": function (exports, module, basis, global, __filename, __dirname, require, resource, asset) { var consts = basis.require("./7.js"); var TYPE_ELEMENT = consts.TYPE_ELEMENT; var TYPE_CONTENT = consts.TYPE_CONTENT; var TOKEN_TYPE = consts.TOKEN_TYPE; var ELEMENT_ATTRIBUTES_AND_CHILDREN = consts.ELEMENT_ATTRIBUTES_AND_CHILDREN; var CONTENT_CHILDREN = consts.CONTENT_CHILDREN; function walker(nodes, fn) { function walk(nodes, offset) { for (var i = offset, node; node = nodes[i]; i++) { var type = node[TOKEN_TYPE]; fn(type, node, nodes); switch (type) { case TYPE_ELEMENT: walk(node, ELEMENT_ATTRIBUTES_AND_CHILDREN); break; case TYPE_CONTENT: walk(node, CONTENT_CHILDREN); break; } } } walk(nodes, 0); } ; module.exports = { walk: walker }; }, "18.js": function (exports, module, basis, global, __filename, __dirname, require, resource, asset) { var hasOwnProperty = Object.prototype.hasOwnProperty; var utils = basis.require("./15.js"); var walk = basis.require("./17.js").walk; var consts = basis.require("./7.js"); var TYPE_ATTRIBUTE_CLASS = consts.TYPE_ATTRIBUTE_CLASS; var TOKEN_BINDINGS = consts.TOKEN_BINDINGS; var ATTR_VALUE_INDEX = consts.ATTR_VALUE_INDEX; var styleNamespaceIsolate = {}; function adoptStyles(resources, prefix, includeToken) { for (var i = 0, item; item = resources[i]; i++) if (item.type == "style") { if (item.isolate !== styleNamespaceIsolate) item.isolate = prefix + item.isolate; if (!item.includeToken) item.includeToken = includeToken; } } function addStyle(template, token, src, isolatePrefix, namespace) { var text = token.children[0]; var url = src ? basis.resource.resolveURI(src, template.baseURI, "<b:style src=\"{url}\"/>") : basis.resource.virtual("css", text ? text.value : "", template.sourceUrl).url; token.sourceUrl = template.sourceUrl; template.resources.push({ type: "style", url: url, isolate: isolatePrefix, token: token, includeToken: null, inline: src ? false : text || true, namespace: namespace }); return url; } function applyStyleNamespaces(tokens, isolate) { function processName(name) { if (name.indexOf(":") <= 0) return name; var prefix = name.split(":")[0]; isolate.map[isolate.prefix + prefix] = prefix; return isolate.prefix + name; } walk(tokens, function (type, node) { if (type !== TYPE_ATTRIBUTE_CLASS) return; var bindings = node[TOKEN_BINDINGS]; var valueIndex = ATTR_VALUE_INDEX[type]; if (node[valueIndex]) node[valueIndex] = node[valueIndex].replace(/\S+/g, processName); if (node.valueLocMap) { var oldValueLocMap = node.valueLocMap; node.valueLocMap = {}; for (var name in oldValueLocMap) node.valueLocMap[processName(name)] = oldValueLocMap[name]; } if (bindings) for (var k = 0, bind; bind = bindings[k]; k++) bind[0] = processName(bind[0]); }); } function isolateTokens(tokens, isolate, template) { function processName(name) { if (name.indexOf(":") == -1) return isolate + name; if (!template) return name; var parts = name.split(":"); if (!parts[0]) return parts[1]; var namespace = hasOwnProperty.call(template.styleNSPrefix, parts[0]) ? template.styleNSPrefix[parts[0]] : false; if (!namespace) { var isolatedPrefix = options.styleNSIsolateMap[parts[0]]; var oldPrefix = parts[0]; var fullName = arguments[1]; var loc = arguments[2]; if (fullName) { if (isolatedPrefix) fullName = fullName.replace(oldPrefix, isolatedPrefix); utils.addTemplateWarn(template, options, "Namespace `" + (isolatedPrefix || oldPrefix) + "` is not defined: " + fullName, loc); } return false; } else { namespace.used = true; return namespace.prefix + parts[1]; } } var options = arguments[3]; walk(tokens, function (type, node) { if (type !== TYPE_ATTRIBUTE_CLASS) return; var bindings = node[TOKEN_BINDINGS]; var valueIndex = ATTR_VALUE_INDEX[type]; if (node[valueIndex]) node[valueIndex] = node[valueIndex].split(/\s+/).map(function (name) { return processName(name, name, node.valueLocMap ? node.valueLocMap[name] : null); }).filter(Boolean).join(" "); if (bindings) { for (var j = 0, bind, prefix, removed; bind = bindings[j]; j++) { prefix = processName(bind[0], bind[0] + "{" + bind[1] + "}", bind.loc); if (prefix === false) { removed = true; bindings[j] = null; } else bind[0] = prefix; } if (removed) { bindings = bindings.filter(Boolean); node[TOKEN_BINDINGS] = bindings.length ? bindings : 0; } } if (node.valueLocMap) { var oldValueLocMap = node.valueLocMap; node.valueLocMap = {}; for (var name in oldValueLocMap) { var newKey = processName(name); if (newKey) node.valueLocMap[newKey] = oldValueLocMap[name]; } } }); } module.exports = { styleNamespaceIsolate: styleNamespaceIsolate, adoptStyles: adoptStyles, addStyle: addStyle, applyStyleNamespaces: applyStyleNamespaces, isolateTokens: isolateTokens }; }, "19.js": function (exports, module, basis, global, __filename, __dirname, require, resource, asset) { var arrayAdd = basis.array.add; var arrayRemove = basis.array.remove; var addTokenRef = basis.require("./16.js").addTokenRef; var consts = basis.require("./7.js"); var utils = basis.require("./15.js"); var getTokenName = utils.getTokenName; var getTokenAttrValues = utils.getTokenAttrValues; var getTokenAttrs = utils.getTokenAttrs; var TYPE_ELEMENT = consts.TYPE_ELEMENT; var TYPE_ATTRIBUTE = consts.TYPE_ATTRIBUTE; var TYPE_ATTRIBUTE_EVENT = consts.TYPE_ATTRIBUTE_EVENT; var TYPE_ATTRIBUTE_STYLE = consts.TYPE_ATTRIBUTE_STYLE; var ATTR_NAME = consts.ATTR_NAME; var ATTR_NAME_BY_TYPE = consts.ATTR_NAME_BY_TYPE; var ATTR_TYPE_BY_NAME = consts.ATTR_TYPE_BY_NAME; var ATTR_VALUE_INDEX = consts.ATTR_VALUE_INDEX; var ATTR_VALUE = consts.ATTR_VALUE; var TOKEN_TYPE = consts.TOKEN_TYPE; var TOKEN_BINDINGS = consts.TOKEN_BINDINGS; var ELEMENT_ATTRIBUTES_AND_CHILDREN = consts.ELEMENT_ATTRIBUTES_AND_CHILDREN; var ATTR_NAME_RX = /^[a-z_][a-z0-9_\-:]*$/i; var ATTR_EVENT_RX = /^event-(.+)$/; function getAttrByName(token, name) { var offset = typeof token[0] == "number" ? ELEMENT_ATTRIBUTES_AND_CHILDREN : 0; for (var i = offset, attr, attrName; attr = token[i]; i++) { if (attr[TOKEN_TYPE] == TYPE_ATTRIBUTE_EVENT) attrName = "event-" + attr[1]; else attrName = ATTR_NAME_BY_TYPE[attr[TOKEN_TYPE]] || attr[ATTR_NAME]; if (attrName == name) return attr; } } function getStyleBindingProperty(attr, name) { var bindings = attr[TOKEN_BINDINGS]; if (bindings) for (var i = 0, binding; binding = bindings[i]; i++) if (binding[2] == name) return binding; } function getAttributeValueLocationMap(template, token) { if (!token || !token.map_) return null; return token.map_.reduce(function (res, part) { if (!part.binding) res[part.value] = utils.getLocation(template, part.loc); return res; }, {}); } function setStylePropertyBinding(template, options, host, attr, property, showByDefault, defaultValue) { var styleAttr = getAttrByName(host, "style"); if (!styleAttr) { styleAttr = [ TYPE_ATTRIBUTE_STYLE, 0, 0 ]; utils.addTokenLocation(template, options, styleAttr, attr); host.push(styleAttr); } var binding = attr.binding; var styleBindings = styleAttr[TOKEN_BINDINGS]; var addDefault = false; var show = attr.name == showByDefault; var value = styleAttr[3]; if (styleBindings) arrayRemove(styleBindings, getStyleBindingProperty(styleAttr, property)); if (!binding || binding[0].length != binding[1].length) { addDefault = !(show ^ attr.value === ""); } else { binding = binding.concat(property, attr.name); addDefault = show; if (styleBindings) styleBindings.push(binding); else styleAttr[TOKEN_BINDINGS] = [binding]; } if (value) value = value.replace(new RegExp(property + "\\s*:\\s*[^;]+(;|$)"), ""); if (addDefault) value = (value ? value + " " : "") + defaultValue; styleAttr[3] = value; } function applyShowHideAttribute(template, options, host, attr) { if (attr.name == "show" || attr.name == "hide") setStylePropertyBinding(template, options, host, attr, "display", "show", "display: none;"); if (attr.name == "visible" || attr.name == "hidden") setStylePropertyBinding(template, options, host, attr, "visibility", "visible", "visibility: hidden;"); } function addRoleAttribute(template, options, host, role) { var sourceToken = arguments[4]; if (host[TOKEN_TYPE] !== TYPE_ELEMENT) { utils.addTemplateWarn(template, options, "Role can't to be added to non-element node", sourceToken.loc); return; } if (!/[\/\(\)]/.test(role)) { var item = [ TYPE_ATTRIBUTE, [ ["$role"], [ 0, role ? "/" + role : "" ] ], 0, "role-marker" ]; item.sourceToken = sourceToken; utils.addTokenLocation(template, options, item, sourceToken); host.push(item); } else utils.addTemplateWarn(template, options, "Value for role was ignored as value can't contains [\"/\", \"(\", \")\"]: " + role, sourceToken.loc); } function applyAttrs(template, options, host, attrs) { var displayAttr; var visibilityAttr; var item; var m; for (var i = 0, attr; attr = attrs[i]; i++) { if (attr.prefix == "b") { switch (attr.name) { case "ref": var refs = (attr.value || "").trim().split(/\s+/); for (var j = 0; j < refs.length; j++) addTokenRef(host, refs[j]); break; case "show": case "hide": displayAttr = attr; break; case "visible": case "hidden": visibilityAttr = attr; break; case "role": addRoleAttribute(template, options, host, attr.value || "", attr); break; } continue; } if (m = attr.name.match(ATTR_EVENT_RX)) { item = m[1] == attr.value ? [ TYPE_ATTRIBUTE_EVENT, m[1] ] : [ TYPE_ATTRIBUTE_EVENT, m[1], attr.value ]; } else { item = [ attr.type, attr.binding, 0 ]; if (attr.type == TYPE_ATTRIBUTE) item.push(getTokenName(attr)); if (attr.value && (!options.optimizeSize || !attr.binding || attr.type != TYPE_ATTRIBUTE)) item.push(attr.value); } item.valueLocMap = getAttributeValueLocationMap(template, attr); item.sourceToken = attr; utils.addTokenLocation(template, options, item, attr); host.push(item); } if (displayAttr) applyShowHideAttribute(template, options, host, displayAttr); if (visibilityAttr) applyShowHideAttribute(template, options, host, visibilityAttr); return host; } function modifyAttr(template, options, include, target, token, name, action) { var attrs = getTokenAttrValues(token); var attrs_ = getTokenAttrs(token); if (name) attrs.name = name; if (!attrs.name) { utils.addTemplateWarn(template, options, "Instruction <b:" + token.name + "> has no `name` attribute", token.loc); return; } if (!ATTR_NAME_RX.test(attrs.name)) { utils.addTemplateWarn(template, options, "Bad attribute name `" + attrs.name + "`", token.loc); return; } if (target) { if (target[TOKEN_TYPE] == TYPE_ELEMENT) { var itAttrs = target; var isEvent = attrs.name.match(ATTR_EVENT_RX); var isClassOrStyle = attrs.name == "class" || attrs.name == "style"; var itType = isEvent ? TYPE_ATTRIBUTE_EVENT : ATTR_TYPE_BY_NAME[attrs.name] || TYPE_ATTRIBUTE; var valueIdx = ATTR_VALUE_INDEX[itType] || ATTR_VALUE; var valueLocMap = getAttributeValueLocationMap(template, attrs_.value); var itAttrToken = itAttrs && getAttrByName(itAttrs, attrs.name); if (itAttrToken && action == "set") { template.removals.push({ reason: "<b:" + token.name + ">", removeToken: token, includeToken: include, token: itAttrToken, node: itAttrToken }); arrayRemove(itAttrs, itAttrToken); itAttrToken = null; } if (!itAttrToken && (action == "set" || action == "append")) { action = "set"; if (isEvent) { itAttrToken = [ itType, isEvent[1] ]; } else { itAttrToken = [ itType, 0, 0, itType == TYPE_ATTRIBUTE ? attrs.name : "" ]; if (itType == TYPE_ATTRIBUTE) itAttrToken.push(""); } if (!itAttrs) { itAttrs = []; target.push(itAttrs); } itAttrs.push(itAttrToken); itAttrToken.valueLocMap = valueLocMap; utils.addTokenLocation(template, options, itAttrToken, token); } switch (action) { case "set": if (itAttrToken[TOKEN_TYPE] == TYPE_ATTRIBUTE_EVENT) { if (attrs.value == isEvent[1]) itAttrToken.length = 2; else itAttrToken[valueIdx] = attrs.value; return; } var valueAttr = attrs_.value || {}; itAttrToken[TOKEN_BINDINGS] = valueAttr.binding || 0; itAttrToken.valueLocMap = valueLocMap; if (!options.optimizeSize || !itAttrToken[TOKEN_BINDINGS] || isClassOrStyle) itAttrToken[valueIdx] = valueAttr.value || ""; else itAttrToken.length = valueIdx; if (isClassOrStyle) if (!itAttrToken[TOKEN_BINDINGS] && !itAttrToken[valueIdx]) { arrayRemove(itAttrs, itAttrToken); return; } break; case "append": var valueAttr = attrs_.value || {}; var appendValue = valueAttr.value || ""; var appendBinding = valueAttr.binding; if (!isEvent) { if (appendBinding) { var attrBindings = itAttrToken[TOKEN_BINDINGS]; if (attrBindings) { switch (attrs.name) { case "style": for (var i = 0, newBinding; newBinding = appendBinding[i]; i++) { arrayRemove(attrBindings, getStyleBindingProperty(itAttrToken, newBinding[2])); attrBindings.push(newBinding); } break; case "class": attrBindings.push.apply(attrBindings, appendBinding); break; default: appendBinding[0].forEach(function (name) { arrayAdd(this, name); }, attrBindings[0]); for (var i = 0; i < appendBinding[1].length; i++) { var value = appendBinding[1][i]; if (typeof value == "number") value = attrBindings[0].indexOf(appendBinding[0][value]); attrBindings[1].push(value); } } } else { itAttrToken[TOKEN_BINDINGS] = appendBinding; if (!isClassOrStyle) itAttrToken[TOKEN_BINDINGS][1].unshift(itAttrToken[valueIdx]); } } else { if (!isClassOrStyle && itAttrToken[TOKEN_BINDINGS]) itAttrToken[TOKEN_BINDINGS][1].push(attrs.value); } } if (appendValue) { if (isEvent || attrs.name == "class") { var parts = (itAttrToken[valueIdx] || "").trim(); var appendParts = appendValue.trim(); parts = parts ? parts.split(/\s+/) : []; appendParts = appendParts ? appendParts.split(/\s+/) : []; for (var i = 0; i < appendParts.length; i++) { var part = appendParts[i]; basis.array.remove(parts, part); parts.push(part); } itAttrToken[valueIdx] = parts.join(" "); } else { itAttrToken[valueIdx] = (itAttrToken[valueIdx] || "") + (itAttrToken[valueIdx] && isClassOrStyle ? " " : "") + appendValue; } if (valueLocMap) { if (itAttrToken.valueLocMap) for (var name in valueLocMap) itAttrToken.valueLocMap[name] = valueLocMap[name]; else itAttrToken.valueLocMap = valueLocMap; } } if (isClassOrStyle && !itAttrToken[TOKEN_BINDINGS] && !itAttrToken[valueIdx]) arrayRemove(itAttrs, itAttrToken); break; case "remove-class": if (itAttrToken) { var valueAttr = attrs_.value || {}; var values = (itAttrToken[valueIdx] || "").split(" "); var removeValues = (valueAttr.value || "").split(" "); var bindings = itAttrToken[TOKEN_BINDINGS]; var removedValues = []; var removedBindings = 0; if (valueAttr.binding && bindings) { for (var i = 0, removeBinding; removeBinding = valueAttr.binding[i]; i++) for (var j = bindings.length - 1, classBinding; classBinding = bindings[j]; j--) { var prefix = classBinding[0]; var bindingName = classBinding[3] || classBinding[1]; if (prefix === removeBinding[0] && bindingName === removeBinding[1]) { bindings.splice(j, 1); if (!removedBindings) removedBindings = [classBinding]; else removedBindings.push(classBinding); } } if (!bindings.length) itAttrToken[TOKEN_BINDINGS] = 0; } for (var i = 0; i < removeValues.length; i++) { if (values.indexOf(removeValues[i]) != -1) removedValues.push(removeValues[i]); arrayRemove(values, removeValues[i]); if (itAttrToken.valueLocMap) delete itAttrToken.valueLocMap[removeValues[i]]; } itAttrToken[valueIdx] = values.join(" "); if (!bindings.length && !values.length) arrayRemove(itAttrs, itAttrToken); if (removedValues.length || removedBindings.length) { var removedNode = [ consts.TYPE_ATTRIBUTE_CLASS, removedBindings, 0, removedValues.join(" ") ]; template.removals.push({ reason: "<b:" + token.name + ">", removeToken: token, includeToken: include, token: removedNode, node: removedNode }); } } break; case "remove": if (itAttrToken) { arrayRemove(itAttrs, itAttrToken); template.removals.push({ reason: "<b:" + token.name + ">", removeToken: token, includeToken: include, token: itAttrToken, node: itAttrToken }); } break; } } else { utils.addTemplateWarn(template, options, "Attribute modificator is not reference to element token (reference name: " + (attrs.ref || "element") + ")", token.loc); } } } module.exports = { getAttrByName: getAttrByName, applyShowHideAttribute: applyShowHideAttribute, addRoleAttribute: addRoleAttribute, applyAttrs: applyAttrs, modifyAttr: modifyAttr }; }, "1a.js": function (exports, module, basis, global, __filename, __dirname, require, resource, asset) { var consts = basis.require("./7.js"); var TYPE_CONTENT = consts.TYPE_CONTENT; var utils = basis.require("./15.js"); module.exports = function (template, options, token, result) { var node = [ TYPE_CONTENT, 2 ]; if (token.children) node.push.apply(node, options.process(token.children, template, options)); utils.addTokenLocation(template, options, node, token); node.sourceToken = token; result.push(node); }; }, "1b.js": function (exports, module, basis, global, __filename, __dirname, require, resource, asset) { var hasOwnProperty = Object.prototype.hasOwnProperty; var consts = basis.require("./7.js"); var utils = basis.require("./15.js"); var getTokenAttrValues = utils.getTokenAttrValues; var CLASS_BINDING_BOOL = consts.CLASS_BINDING_BOOL; var CLASS_BINDING_INVERT = consts.CLASS_BINDING_INVERT; var CLASS_BINDING_ENUM = consts.CLASS_BINDING_ENUM; function addStateInfo(template, name, type, value) { if (!hasOwnProperty.call(template.states, name)) template.states[name] = {}; var info = template.states[name]; var isArray = Array.isArray(value); if (!hasOwnProperty.call(info, type) || !isArray) info[type] = isArray ? basis.array(value) : value; else value.forEach(function (item) { basis.array.add(info[type], item); }); } module.exports = function (template, options, token) { var elAttrs = getTokenAttrValues(token); var elAttrs_ = utils.getTokenAttrs(token); if ("name" in elAttrs == false) utils.addTemplateWarn(template, options, "<b:define> has no `name` attribute", token.loc); if ("type" in elAttrs == false) utils.addTemplateWarn(template, options, "<b:define> has no `type` attribute", token.loc); if (hasOwnProperty.call(options.defines, elAttrs.name)) utils.addTemplateWarn(template, options, "<b:define> with name `" + elAttrs.name + "` is already defined", token.loc); if ("name" in elAttrs && "type" in elAttrs && !hasOwnProperty.call(options.defines, elAttrs.name)) { var bindingName = elAttrs.from || elAttrs.name; var defineName = elAttrs.name; var define = false; var defaultIndex; var values; switch (elAttrs.type) { case "bool": define = [ bindingName, CLASS_BINDING_BOOL, defineName, elAttrs["default"] == "true" ? 1 : 0 ]; addStateInfo(template, bindingName, "bool", true); if ("default" in elAttrs && !elAttrs["default"]) utils.addTemplateWarn(template, options, "Bool <b:define> has no value as default (value ignored)", elAttrs_["default"] && elAttrs_["default"].loc); break; case "invert": define = [ bindingName, CLASS_BINDING_INVERT, defineName, !elAttrs["default"] || elAttrs["default"] == "true" ? 1 : 0 ]; addStateInfo(template, bindingName, "invert", false); if ("default" in elAttrs && !elAttrs["default"]) utils.addTemplateWarn(template, options, "Invert <b:define> has no value as default (value ignored)", elAttrs_["default"] && elAttrs_["default"].loc); break; case "enum": if ("values" in elAttrs == false) { utils.addTemplateWarn(template, options, "Enum <b:define> has no `values` attribute", token.loc); break; } values = (elAttrs.values || "").trim(); if (!values) { utils.addTemplateWarn(template, options, "Enum <b:define> has no variants (`values` attribute is empty)", elAttrs_.values && elAttrs_.values.loc); break; } values = values.split(/\s+/); defaultIndex = values.indexOf(elAttrs["default"]); if ("default" in elAttrs && defaultIndex == -1) utils.addTemplateWarn(template, options, "Enum <b:define> has bad value as default (value ignored)", elAttrs_["default"] && elAttrs_["default"].loc); define = [ bindingName, CLASS_BINDING_ENUM, defineName, defaultIndex + 1, values ]; addStateInfo(template, bindingName, "enum", values); break; default: utils.addTemplateWarn(template, options, "Bad type in <b:define> for `" + defineName + "`: " + elAttrs.type, elAttrs_.type && elAttrs_.type.valueLoc); } if (define) { utils.addTokenLocation(template, options, define, token); options.defines[defineName] = define; } } }; }, "1c.js": function (exports, module, basis, global, __filename, __dirname, require, resource, asset) { var arrayRemove = basis.array.remove; var arrayAdd = basis.array.add; var walk = basis.require("./17.js").walk; var utils = basis.require("./15.js"); var addUnique = utils.addUnique; var getTokenAttrValues = utils.getTokenAttrValues; var getTokenAttrs = utils.getTokenAttrs; var parseOptionsValue = utils.parseOptionsValue; var refsUtils = basis.require("./16.js"); var normalizeRefs = refsUtils.normalizeRefs; var addTokenRef = refsUtils.addTokenRef; var removeTokenRef = refsUtils.removeTokenRef; var styleUtils = basis.require("./18.js"); var styleNamespaceIsolate = styleUtils.styleNamespaceIsolate; var adoptStyles = styleUtils.adoptStyles; var addStyle = styleUtils.addStyle; var isolateTokens = styleUtils.isolateTokens; var applyStyleNamespaces = styleUtils.applyStyleNamespaces; var attrUtils = basis.require("./19.js"); var getAttrByName = attrUtils.getAttrByName; var addRoleAttribute = attrUtils.addRoleAttribute; var applyShowHideAttribute = attrUtils.applyShowHideAttribute; var modifyAttr = attrUtils.modifyAttr; var consts = basis.require("./7.js"); var TOKEN_TYPE = consts.TOKEN_TYPE; var TOKEN_BINDINGS = consts.TOKEN_BINDINGS; var ATTR_NAME = consts.ATTR_NAME; var TYPE_ATTRIBUTE = consts.TYPE_ATTRIBUTE; var TYPE_ELEMENT = consts.TYPE_ELEMENT; var ELEMENT_ATTRIBUTES_AND_CHILDREN = consts.ELEMENT_ATTRIBUTES_AND_CHILDREN; var CONTENT_CHILDREN = consts.CONTENT_CHILDREN; var specialTagsAsRegular = [ "include", "content" ]; var attributesWhitelist = [ "src", "no-style", "isolate", "options" ]; var attributeToInstructionMap = { "class": { instruction: "append-class", valueTo: "value" }, "id": { instruction: "set-attr", valueTo: "value", attrs: { name: "id" } }, "ref": { instruction: "add-ref", valueTo: "name" }, "show": { instruction: "show", valueTo: "expr" }, "hide": { instruction: "hide", valueTo: "expr" }, "visible": { instruction: "visible", valueTo: "expr" }, "hidden": { instruction: "hidden", valueTo: "expr" } }; function adoptNodes(ast, includeToken) { walk(ast, function (type, node) { if (!node.includeToken) node.includeToken = includeToken; }); } function applyRole(ast, role) { walk(ast, function (type, node) { if (type !== TYPE_ATTRIBUTE || node[ATTR_NAME] != "role-marker") return; var roleExpression = node[TOKEN_BINDINGS][1]; var currentRole = roleExpression[1]; roleExpression[1] = "/" + role + currentRole; node.sourceToken = arguments[2]; node.loc = arguments[3]; }); } function clone(value) { if (Array.isArray(value)) return value.map(clone); if (value && value.constructor === Object) { var result = {}; for (var key in value) result[key] = clone(value[key]); return result; } return value; } function convertAttributeToInstruction(config, attribute) { return { type: TYPE_ELEMENT, prefix: "b", name: config.instruction, attrs: basis.object.iterate(config.attrs || {}, function (attrName, value) { return { type: TYPE_ATTRIBUTE, name: attrName, value: value }; }).concat(basis.object.complete({ name: config.valueTo }, attribute)) }; } module.exports = function (template, options, token, result) { var elAttrs = getTokenAttrValues(token); var elAttrs_ = getTokenAttrs(token); var includeStack = options.includeStack; var templateSrc = elAttrs.src; if ("src" in elAttrs == false) utils.addTemplateWarn(template, options, "<b:include> has no `src` attribute", token.loc); if (!templateSrc) return; var resource; var basisWarn = basis.dev.warn; basis.dev.warn = function () { utils.addTemplateWarn(template, options, basis.array(arguments).join(" "), token.loc); if (!basis.NODE_ENV) basisWarn.apply(this, arguments); }; if (/^#[^\d]/.test(templateSrc)) { resource = template.templates[templateSrc.substr(1)]; if (resource) resource = options.makeDeclaration(clone(resource.tokens), resource.baseURI, resource.options, resource.sourceUrl); } else { resource = options.resolveResource(templateSrc, template.baseURI); } basis.dev.warn = basisWarn; if (!resource) { utils.addTemplateWarn(template, options, "<b:include src=\"" + templateSrc + "\"> is not resolved, instruction ignored", token.loc); return; } if (includeStack.indexOf(resource) !== -1) { var stack = includeStack.slice(includeStack.indexOf(resource) || 0).concat(resource).map(function (res) { if (res instanceof options.Template) res = res.source; return res.id || res.url || "[inline template]"; }); template.warns.push("Recursion: ", stack.join(" -> ")); return; } var isolatePrefix = elAttrs_.isolate ? elAttrs_.isolate.value || options.genIsolateMarker() : ""; var includeOptions = elAttrs.options ? parseOptionsValue(elAttrs.options) : null; var decl = options.getDeclFromSource(resource, "", true, basis.object.merge(options, { includeOptions: includeOptions })); adoptNodes(decl.tokens, token); template.includes.push({ token: token, resource: resource, nested: decl.includes }); if (resource.bindingBridge) arrayAdd(template.deps, resource); if (decl.deps) addUnique(template.deps, decl.deps); if (decl.warns) { decl.warns.forEach(function (warn) { warn.source = warn.source || token; }); template.warns.push.apply(template.warns, decl.warns); } if (decl.removals) { template.removals.push.apply(template.removals, decl.removals); template.removals.forEach(function (item) { if (!item.includeToken) item.includeToken = token; }); } if (decl.resources) { var resources = decl.resources; if ("no-style" in elAttrs) resources = resources.filter(function (item) { return item.type != "style"; }); else adoptStyles(resources, isolatePrefix, token); template.resources.unshift.apply(template.resources, resources); } var styleNSIsolate = { map: options.styleNSIsolateMap, prefix: options.genIsolateMarker() }; applyStyleNamespaces(decl.tokens, styleNSIsolate); for (var key in decl.styleNSPrefix) template.styleNSPrefix[styleNSIsolate.prefix + key] = basis.object.merge(decl.styleNSPrefix[key], { used: Object.prototype.hasOwnProperty.call(options.styleNSIsolateMap, styleNSIsolate.prefix + key) }); if (isolatePrefix) { isolateTokens(decl.tokens, isolatePrefix); if (decl.removals) decl.removals.forEach(function (item) { isolateTokens([item.node], isolatePrefix); }); } var isContentReset = false; var instructions = []; var tokenRefMap = normalizeRefs(decl.tokens); for (var includeAttrName in elAttrs_) { if (attributeToInstructionMap.hasOwnProperty(includeAttrName)) { instructions.push(convertAttributeToInstruction(attributeToInstructionMap[includeAttrName], elAttrs_[includeAttrName])); } else if (includeAttrName === "role") { var role = elAttrs_.role.value; if (role) { if (!/[\/\(\)]/.test(role)) { var loc; loc = utils.getLocation(template, elAttrs_.role.loc); applyRole(decl.tokens, role, elAttrs_.role, loc); } else utils.addTemplateWarn(template, options, "Value for role was ignored as value can't contains [\"/\", \"(\", \")\"]: " + role, elAttrs_.role.loc); } } else if (attributesWhitelist.indexOf(includeAttrName) === -1) utils.addTemplateWarn(template, options, "Unknown attribute for <b:include>: " + includeAttrName, elAttrs_[includeAttrName].loc); } instructions = instructions.concat(token.children); for (var j = 0, child; child = instructions[j]; j++) { if (child.type == TYPE_ELEMENT && child.prefix == "b" && specialTagsAsRegular.indexOf(child.name) === -1) { var childAttrs = getTokenAttrValues(child); var ref = "ref" in childAttrs ? childAttrs.ref : "element"; var isSpecialRef = ref.charAt(0) === ":"; var targetRef = ref && tokenRefMap[ref]; var target = targetRef && targetRef.node; switch (child.name) { case "style": var childAttrs = getTokenAttrValues(child); var useStyle = true; if (childAttrs.options) { var filterOptions = parseOptionsValue(childAttrs.options); for (var name in filterOptions) useStyle = useStyle && filterOptions[name] == includeOptions[name]; } if (useStyle) { var namespaceAttrName = childAttrs.namespace ? "namespace" : "ns"; var styleNamespace = childAttrs[namespaceAttrName]; var styleIsolate = styleNamespace ? styleNamespaceIsolate : isolatePrefix; var src = addStyle(template, child, childAttrs.src, styleIsolate, styleNamespace); if (styleNamespace) { if (src in styleNamespaceIsolate == false) styleNamespaceIsolate[src] = options.genIsolateMarker(); template.styleNSPrefix[styleNSIsolate.prefix + styleNamespace] = { loc: utils.getLocation(template, getTokenAttrs(child)[namespaceAttrName].loc), used: false, name: styleNamespace, prefix: styleNamespaceIsolate[src] }; } } else { child.sourceUrl = template.sourceUrl; template.resources.push([ null, styleIsolate, child, token, childAttrs.src ? false : child.children[0] || true, styleNamespace ]); } break; case "replace": case "remove": case "before": case "after": var replaceOrRemove = child.name == "replace" || child.name == "remove"; var childAttrs = getTokenAttrValues(child); var ref = "ref" in childAttrs || !replaceOrRemove ? childAttrs.ref : "element"; var targetRef = ref && tokenRefMap[ref]; if (targetRef) { var parent = targetRef.parent; var pos = parent.indexOf(targetRef.node); if (pos != -1) { var args = [ pos + (child.name == "after"), replaceOrRemove ]; if (child.name != "remove") args = args.concat(options.process(child.children, template, options)); parent.splice.apply(parent, args); if (replaceOrRemove) template.removals.push({ reason: "<b:" + child.name + ">", removeToken: child, includeToken: token, token: targetRef.node, node: targetRef.node }); } } break; case "prepend": case "append": if (target && target[TOKEN_TYPE] == TYPE_ELEMENT) { var children = options.process(child.children, template, options); if (child.name == "prepend") target.splice.apply(target, [ ELEMENT_ATTRIBUTES_AND_CHILDREN, 0 ].concat(children)); else target.push.apply(target, children); } break; case "show": case "hide": case "visible": case "hidden": if (target && target[TOKEN_TYPE] == TYPE_ELEMENT) { var expr = getTokenAttrs(child).expr; if (!expr) { utils.addTemplateWarn(template, options, "Instruction <b:" + child.name + "> has no `expr` attribute", child.loc); break; } applyShowHideAttribute(template, options, target, basis.object.complete({ name: child.name }, getTokenAttrs(child).expr)); } break; case "attr": case "set-attr": modifyAttr(template, options, token, target, child, false, "set"); break; case "append-attr": modifyAttr(template, options, token, target, child, false, "append"); break; case "remove-attr": modifyAttr(template, options, token, target, child, false, "remove"); break; case "class": case "append-class": modifyAttr(template, options, token, target, child, "class", "append"); break; case "set-class": modifyAttr(template, options, token, target, child, "class", "set"); break; case "remove-class": var valueAttr = getTokenAttrs(child).value; if (valueAttr) { valueAttr.value = valueAttr.value.split(/\s+/).map(function (name) { return name.indexOf(":") > 0 ? styleNSIsolate.prefix + name : name; }).join(" "); if (valueAttr.binding) valueAttr.binding.forEach(function (bind) { if (bind[0].indexOf(":") > 0) bind[0] = styleNSIsolate.prefix + bind[0]; }); if (valueAttr.map_) valueAttr.map_.forEach(function (item) { if (item.value.indexOf(":") > 0) item.value = styleNSIsolate.prefix + item.value; }); } modifyAttr(template, options, token, target, child, "class", "remove-class"); break; case "add-ref": var refName = (childAttrs.name || "").trim(); if (!target) { utils.addTemplateWarn(template, options, "Target node for <b:" + child.name + "> is not found", child.loc); break; } if (isSpecialRef) { utils.addTemplateWarn(template, options, "<b:" + child.name + "> can't to be applied to special reference `" + ref + "`", child.loc); break; } if (!/^[a-z_][a-z0-9_]*$/i.test(refName)) { utils.addTemplateWarn(template, options, "Bad reference name for <b:" + child.name + ">: " + refName, child.loc); break; } addTokenRef(target, refName); break; case "remove-ref": var refName = (childAttrs.name || "").trim(); var ref = "ref" in childAttrs ? childAttrs.ref : refName || "element"; var isSpecialRef = ref.charAt(0) === ":"; var targetRef = ref && tokenRefMap[ref]; var target = targetRef && targetRef.node; if (!target) { utils.addTemplateWarn(template, options, "Target node for <b:" + child.name + "> is not found", child.loc); break; } if (isSpecialRef) { utils.addTemplateWarn(template, options, "<b:" + child.name + "> can't to be applied to special reference `" + ref + "`", child.loc); break; } if (!/^[a-z_][a-z0-9_]*$/i.test(refName)) { utils.addTemplateWarn(template, options, "Bad reference name for <b:" + child.name + ">: " + refName, child.loc); break; } removeTokenRef(target, refName || ref); break; case "role": case "set-role": var name = childAttrs.name; if (!name && "value" in childAttrs) { utils.addTemplateWarn(template, options, "`value` attribute for <b:" + child.name + "> is deprecated, use `name` instead", getTokenAttrs(child).value.loc); name = childAttrs.value; } if (!target) { utils.addTemplateWarn(template, options, "Target node for <b:" + child.name + "> is not found", child.loc); break; } arrayRemove(target, getAttrByName(target, "role-marker")); addRoleAttribute(template, options, target, name || "", child); break; case "remove-role": if (!target) { utils.addTemplateWarn(template, options, "Target node for <b:" + child.name + "> is not found", child.loc); break; } arrayRemove(target, getAttrByName(target, "role-marker")); break; default: utils.addTemplateWarn(template, options, "Unknown instruction tag: <b:" + child.name + ">", child.loc); } } else { var targetRef = tokenRefMap[":content"]; var processedChild = options.process([child], template, options); if (targetRef) { var parent = targetRef.parent; var pos = parent.indexOf(targetRef.node); if (!isContentReset) { isContentReset = true; for (var i = CONTENT_CHILDREN; i < targetRef.node.length; i++) template.removals.push({ reason: "node from including template", removeToken: child, includeToken: token, token: targetRef.node[i], node: targetRef.node[i] }); targetRef.node.splice(CONTENT_CHILDREN); } targetRef.node.push.apply(targetRef.node, processedChild); } else { decl.tokens.push.apply(decl.tokens, processedChild); } } } if (tokenRefMap.element) removeTokenRef(tokenRefMap.element.node, "element"); result.push.apply(result, decl.tokens); }; }, "1d.js": function (exports, module, basis, global, __filename, __dirname, require, resource, asset) { var utils = basis.require("./15.js"); var getTokenAttrValues = utils.getTokenAttrValues; module.exports = function (template, options, token) { if (template.isolate) { utils.addTemplateWarn(template, options, "<b:isolate> is already set to `" + template.isolate + "`", token.loc); return; } template.isolate = getTokenAttrValues(token).prefix || options.isolate || options.genIsolateMarker(); }; }, "1e.js": function (exports, module, basis, global, __filename, __dirname, require, resource, asset) { var getTokenAttrValues = basis.require("./15.js").getTokenAttrValues; module.exports = function (template, options, token) { var elAttrs = getTokenAttrValues(token); if (elAttrs.src) options.dictURI = basis.resource.resolveURI(elAttrs.src, template.baseURI, "<b:" + token.name + " src=\"{url}\"/>"); }; }, "1f.js": function (exports, module, basis, global, __filename, __dirname, require, resource, asset) { var utils = basis.require("./15.js"); var styleUtils = basis.require("./18.js"); var styleNamespaceIsolate = styleUtils.styleNamespaceIsolate; var addStyle = styleUtils.addStyle; var parseOptionsValue = utils.parseOptionsValue; var getTokenAttrValues = utils.getTokenAttrValues; module.exports = function (template, options, token) { var useStyle = true; var elAttrs = getTokenAttrValues(token); if (elAttrs.options) { var filterOptions = parseOptionsValue(elAttrs.options); for (var name in filterOptions) useStyle = useStyle && filterOptions[name] == options.includeOptions[name]; } if (useStyle) { var namespaceAttrName = elAttrs.namespace ? "namespace" : "ns"; var styleNamespace = elAttrs[namespaceAttrName]; var styleIsolate = styleNamespace ? styleNamespaceIsolate : ""; var src = addStyle(template, token, elAttrs.src, styleIsolate, styleNamespace); if (styleNamespace) { if (src in styleNamespaceIsolate == false) styleNamespaceIsolate[src] = options.genIsolateMarker(); if (styleNamespace in template.styleNSPrefix) { utils.addTemplateWarn(template, options, "Duplicate value for `" + styleNamespace + "` attribute, style ignored", utils.getTokenAttrs(token)[namespaceAttrName].loc); return; } template.styleNSPrefix[styleNamespace] = { loc: utils.getLocation(template, utils.getTokenAttrs(token)[namespaceAttrName].loc), used: false, name: styleNamespace, prefix: styleNamespaceIsolate[src] }; } } else { token.sourceUrl = template.sourceUrl; template.resources.push({ type: "style", url: null, isolate: styleIsolate, token: token, includeToken: null, inline: elAttrs.src ? false : token.children[0] || true, namespace: styleNamespace }); } }; }, "1g.js": function (exports, module, basis, global, __filename, __dirname, require, resource, asset) { var arrayAdd = basis.array.add; var utils = basis.require("./15.js"); var getTokenName = utils.getTokenName; var getTokenAttrs = utils.getTokenAttrs; var bindingList = utils.bindingList; var refList = basis.require("./16.js").refList; var applyAttrs = basis.require("./19.js").applyAttrs; var TYPE_ELEMENT = basis.require("./7.js").TYPE_ELEMENT; module.exports = function (template, options, token, result) { var attrs = getTokenAttrs(token); var svgAttributes = []; var svgUse = [ TYPE_ELEMENT, 0, 0, "svg:use" ]; var svgElement = [ TYPE_ELEMENT, bindingList(token), refList(token), "svg:svg", svgUse ]; for (var key in attrs) { var attrToken = attrs[key]; switch (getTokenName(attrToken)) { case "src": if (!attrToken.value) { utils.addTemplateWarn(template, options, "Value for `src` attribute should be specified", attrToken.loc); continue; } var svgUrl = basis.resource.resolveURI(attrToken.value, template.baseURI, "<b:" + token.name + " src=\"{url}\"/>"); arrayAdd(template.deps, basis.resource.buildCloak(svgUrl)); template.resources.push({ type: "svg", url: svgUrl }); break; case "use": applyAttrs(template, options, svgUse, [basis.object.merge(attrToken, { prefix: "xlink", name: "href" })]); break; default: svgAttributes.push(attrToken); } } result.push(applyAttrs(template, options, svgElement, svgAttributes)); }; }, "1h.js": function (exports, module, basis, global, __filename, __dirname, require, resource, asset) { var getTokenAttrValues = basis.require("./15.js").getTokenAttrValues; module.exports = function (template, options, token, result) { var elAttrs = getTokenAttrValues(token); var refs = (elAttrs.ref || "").trim(); var text = token.children[0] || { type: 3, value: "" }; text = basis.object.merge(text, { refs: refs ? refs.split(/\s+/) : [], value: "notrim" in elAttrs ? text.value : (text.value || "").replace(/^ *(\r\n?|\n)( *$)?|(\r\n?|\n) *$/g, "") }); result.push.apply(result, options.process([text], template, options)); }; }, "b.js": function (exports, module, basis, global, __filename, __dirname, require, resource, asset) { var templates = {}; function add(id, template, instances) { templates[id] = { template: template, instances: instances }; } function remove(id) { delete templates[id]; } function resolveInstanceById(refId) { var templateId = refId & 4095; var instanceId = refId >> 12; var templateInfo = templates[templateId]; return templateInfo && templateInfo.instances[instanceId]; } function resolveInfoById(refId) { var templateId = refId & 4095; var instanceId = refId >> 12; var templateInfo = templates[templateId]; var instanceInfo = templateInfo && templateInfo.instances[instanceId]; if (instanceInfo) return { debug: instanceInfo.debug ? instanceInfo.debug() : null, id: refId, template: templateInfo.template, context: instanceInfo.context, tmpl: instanceInfo.tmpl }; } function resolveTemplateById(refId) { var templateId = refId & 4095; var templateInfo = templates[templateId]; return templateInfo && templateInfo.template; } function resolveObjectById(refId) { var instanceInfo = resolveInstanceById(refId); return instanceInfo && instanceInfo.context; } function resolveTmplById(refId) { var instanceInfo = resolveInstanceById(refId); return instanceInfo && instanceInfo.tmpl; } function resolveActionById(refId) { var instanceInfo = resolveInstanceById(refId); return instanceInfo && { context: instanceInfo.context, action: instanceInfo.action }; } function getDebugInfoById(refId) { var instanceInfo = resolveInstanceById(refId); return instanceInfo && instanceInfo.debug && instanceInfo.debug(); } module.exports = { getDebugInfoById: getDebugInfoById, add: add, remove: remove, resolveInfoById: resolveInfoById, resolveTemplateById: resolveTemplateById, resolveObjectById: resolveObjectById, resolveTmplById: resolveTmplById, resolveActionById: resolveActionById }; }, "c.js": function (exports, module, basis, global, __filename, __dirname, require, resource, asset) { var namespace = "basis.template.theme"; var themes = {}; var sourceByPath = {}; var themeChangeHandlers = []; var currentThemeName = "base"; var baseTheme; var Theme = basis.Class(null, { className: namespace + ".Theme", get: getSourceByPath }); var SourceWrapper = basis.Class(basis.Token, { className: namespace + ".SourceWrapper", path: "", url: "", baseURI: "", init: function (value, path) { this.path = path; basis.Token.prototype.init.call(this, ""); }, get: function () { return this.value && this.value.bindingBridge ? this.value.bindingBridge.get(this.value) : this.value; }, set: function () { var content = getThemeSource(currentThemeName, this.path); if (this.value != content) { if (this.value && this.value.bindingBridge) this.value.bindingBridge.detach(this.value, SourceWrapper.prototype.apply, this); this.value = content; this.url = content && content.url || ""; this.baseURI = (typeof content == "object" || typeof content == "function") && "baseURI" in content ? content.baseURI : basis.path.dirname(this.url) + "/"; if (this.value && this.value.bindingBridge) this.value.bindingBridge.attach(this.value, SourceWrapper.prototype.apply, this); this.apply(); } }, destroy: function () { this.url = null; this.baseURI = null; if (this.value && this.value.bindingBridge) this.value.bindingBridge.detach(this.value, this.apply, this); basis.Token.prototype.destroy.call(this); } }); function getSourceByPath() { var path = basis.array(arguments).join("."); var source = sourceByPath[path]; if (!source) { source = new SourceWrapper("", path); sourceByPath[path] = source; } return source; } function normalize(list) { var used = {}; var result = []; for (var i = 0; i < list.length; i++) if (!used[list[i]]) { used[list[i]] = true; result.push(list[i]); } return result; } function extendFallback(themeName, list) { var result = []; result.source = normalize(list).join("/"); var used = { base: true }; for (var i = 0; i < list.length; i++) { var name = list[i] || "base"; if (name == themeName || used[name]) continue; used[name] = true; result.push(name); getTheme(name); list.splice.apply(list, [ i + 1, 0 ].concat(themes[name].fallback)); } result.unshift(themeName); if (themeName != "base") result.push("base"); result.value = result.join("/"); return result; } function getThemeSource(name, path) { var sourceList = themes[name].sourcesList; for (var i = 0, map; map = sourceList[i]; i++) if (map.hasOwnProperty(path)) return map[path]; return ""; } function themeHasEffect(themeName) { return themes[currentThemeName].fallback.indexOf(themeName) != -1; } function syncCurrentThemePath(path) { getSourceByPath(path).set(); } function syncCurrentTheme() { basis.dev.log("re-apply templates"); for (var path in sourceByPath) syncCurrentThemePath(path); } function getTheme(name) { if (!name) name = "base"; if (themes[name]) return themes[name].theme; if (!/^([a-z0-9\_\-]+)$/.test(name)) throw "Bad name for theme - " + name; var sources = {}; var sourceList = [sources]; var themeInterface = new Theme(); themes[name] = { theme: themeInterface, sources: sources, sourcesList: sourceList, fallback: [] }; var addSource = function (path, source) { if (path in sources == false) { sources[path] = source; if (themeHasEffect(name)) syncCurrentThemePath(path); } else basis.dev.warn("Template path `" + path + "` is already defined for theme `" + name + "` (definition ignored)."); return getSourceByPath(path); }; basis.object.extend(themeInterface, { name: name, fallback: function (value) { if (themeInterface !== baseTheme && arguments.length > 0) { var newFallback = typeof value == "string" ? value.split("/") : []; var changed = {}; newFallback = extendFallback(name, newFallback); if (themes[name].fallback.source != newFallback.source) { themes[name].fallback.source = newFallback.source; basis.dev.log("fallback changed"); for (var themeName in themes) { var curFallback = themes[themeName].fallback; var newFallback = extendFallback(themeName, (curFallback.source || "").split("/")); if (newFallback.value != curFallback.value) { changed[themeName] = true; themes[themeName].fallback = newFallback; var sourceList = themes[themeName].sourcesList; sourceList.length = newFallback.length; for (var i = 0; i < sourceList.length; i++) sourceList[i] = themes[newFallback[i]].sources; } } } for (var themeName in changed) if (themeHasEffect(themeName)) { syncCurrentTheme(); break; } } var result = themes[name].fallback.slice(1); result.source = themes[name].fallback.source; return result; }, define: function (what, wherewith) { if (typeof what == "function") what = what(); if (typeof what == "string") { if (typeof wherewith == "object") { var namespace = what; var dictionary = wherewith; var result = {}; for (var key in dictionary) if (dictionary.hasOwnProperty(key)) result[key] = addSource(namespace + "." + key, dictionary[key]); return result; } else { if (arguments.length == 1) { return getSourceByPath(what); } else { return addSource(what, wherewith); } } } else { if (typeof what == "object") { var dictionary = what; for (var path in dictionary) if (dictionary.hasOwnProperty(path)) addSource(path, dictionary[path]); return themeInterface; } else { basis.dev.warn("Wrong first argument for basis.template.Theme#define"); } } }, apply: function () { if (name != currentThemeName) { currentThemeName = name; syncCurrentTheme(); basis.Token.prototype.set.call(getTheme, currentThemeName); for (var i = 0, handler; handler = themeChangeHandlers[i]; i++) handler.fn.call(handler.context, name); basis.dev.info("Template theme switched to `" + name + "`"); } return themeInterface; }, getSource: function (path, withFallback) { return withFallback ? getThemeSource(name, path) : sources[path]; }, drop: function (path) { if (sources.hasOwnProperty(path)) { delete sources[path]; if (themeHasEffect(name)) syncCurrentThemePath(path); } } }); themes[name].fallback = extendFallback(name, []); sourceList.push(themes.base.sources); return themeInterface; } function setTheme(name) { return getTheme(name).apply(); } basis.object.extend(getTheme, new basis.Token(currentThemeName)); getTheme.set = setTheme; function onThemeChange(fn, context, fire) { themeChangeHandlers.push({ fn: fn, context: context }); if (fire) fn.call(context, currentThemeName); } basis.cleaner.add({ destroy: function () { for (var path in sourceByPath) sourceByPath[path].destroy(); themes = null; sourceByPath = null; } }); baseTheme = getTheme(); module.exports = { SourceWrapper: SourceWrapper, Theme: Theme, theme: getTheme, getThemeList: function () { return basis.object.keys(themes); }, currentTheme: function () { return themes[currentThemeName].theme; }, setTheme: setTheme, onThemeChange: onThemeChange, define: baseTheme.define, get: getSourceByPath, getPathList: function () { return basis.object.keys(sourceByPath); } }; }, "d.js": function (exports, module, basis, global, __filename, __dirname, require, resource, asset) { var Node = global.Node; var hasOwnProperty = Object.prototype.hasOwnProperty; var eventUtils = basis.require("./e.js"); var resolveActionById = basis.require("./b.js").resolveActionById; var consts = basis.require("./7.js"); var namespaces = basis.require("./8.js"); var MARKER = consts.MARKER; var CLONE_NORMALIZATION_TEXT_BUG = consts.CLONE_NORMALIZATION_TEXT_BUG; var TYPE_ELEMENT = consts.TYPE_ELEMENT; var TYPE_ATTRIBUTE = consts.TYPE_ATTRIBUTE; var TYPE_ATTRIBUTE_CLASS = consts.TYPE_ATTRIBUTE_CLASS; var TYPE_ATTRIBUTE_STYLE = consts.TYPE_ATTRIBUTE_STYLE; var TYPE_ATTRIBUTE_EVENT = consts.TYPE_ATTRIBUTE_EVENT; var TYPE_TEXT = consts.TYPE_TEXT; var TYPE_COMMENT = consts.TYPE_COMMENT; var TYPE_CONTENT = consts.TYPE_CONTENT; var TOKEN_TYPE = consts.TOKEN_TYPE; var TOKEN_BINDINGS = consts.TOKEN_BINDINGS; var TOKEN_REFS = consts.TOKEN_REFS; var ATTR_NAME = consts.ATTR_NAME; var ATTR_VALUE = consts.ATTR_VALUE; var ATTR_VALUE_INDEX = consts.ATTR_VALUE_INDEX; var ELEMENT_NAME = consts.ELEMENT_NAME; var ELEMENT_ATTRIBUTES_AND_CHILDREN = consts.ELEMENT_ATTRIBUTES_AND_CHILDREN; var CONTENT_CHILDREN = consts.CONTENT_CHILDREN; var TEXT_VALUE = consts.TEXT_VALUE; var COMMENT_VALUE = consts.COMMENT_VALUE; var CLASS_BINDING_ENUM = consts.CLASS_BINDING_ENUM; var CLASS_BINDING_BOOL = consts.CLASS_BINDING_BOOL; var CLASS_BINDING_INVERT = consts.CLASS_BINDING_INVERT; var MOUSE_ENTER_LEAVE_SUPPORT = "onmouseenter" in document.documentElement; var USE_CAPTURE_FALLBACK = false; var tmplEventListeners = {}; var afterEventAction = {}; var insideElementEvent = {}; var contains; var IS_TOUCH_DEVICE = "ontouchstart" in document.documentElement; var MOUSE_EVENTS = [ "mouseover", "mouseup", "mousedown", "mousemove", "click", "dblclick" ]; if (Node && !Node.prototype.contains) contains = function (parent, child) { return parent.compareDocumentPosition(child) & 16; }; else contains = function (parent, child) { return parent.contains(child); }; if (!document.addEventListener) USE_CAPTURE_FALLBACK = basis.publicCallback(function (eventName, event) { eventUtils.fireEvent(document, eventName); event.returnValue = true; var listener = tmplEventListeners[eventName]; if (listener) listener(new eventUtils.Event(event)); }, true); function createEventHandler(attrName) { return function (event) { if (event.type == "click" && event.which == 3) return; var bubble = insideElementEvent[event.type] || event.type != "mouseenter" && event.type != "mouseleave"; var nodePath = event.path.slice(0, event.path.length - 1); var attrCursor = nodePath.shift(); var attr; while (attrCursor) { attr = attrCursor.getAttribute && attrCursor.getAttribute(attrName); if (!bubble || typeof attr == "string") break; attrCursor = nodePath.shift(); } if (typeof attr == "string") { var cursor = attrCursor; var actionTarget = cursor; var refId; var tmplRef; if (insideElementEvent[event.type]) { var relTarget = event.relatedTarget; if (relTarget && (cursor === relTarget || contains(cursor, relTarget))) cursor = null; } while (cursor) { refId = cursor[MARKER]; if (typeof refId == "number") { if (tmplRef = resolveActionById(refId)) break; } cursor = nodePath.shift(); } var actions = attr.trim().split(/\s+/); var actionCallback = tmplRef && tmplRef.action; for (var i = 0, actionName; actionName = actions[i++];) switch (actionName) { case "prevent-default": event.preventDefault(); break; case "stop-propagation": event.stopPropagation(); break; case "log-event": basis.dev.log("Template event:", event); break; default: if (actionCallback) { event.actionTarget = actionTarget; actionCallback.call(tmplRef.context, actionName, event); } } } if (event.type in afterEventAction) afterEventAction[event.type](event, attrCursor); }; } function emulateEvent(origEventName, emulEventName) { regEventHandler(emulEventName); insideElementEvent[origEventName] = true; afterEventAction[emulEventName] = function (event) { event = new eventUtils.Event(event); event.type = origEventName; tmplEventListeners[origEventName](event); }; afterEventAction[origEventName] = function (event, cursor) { if (!cursor || !cursor.parentNode) return; event = new eventUtils.Event(event); event.type = origEventName; event.sender = cursor.parentNode; tmplEventListeners[origEventName](event); }; } function regEventHandler(eventName) { if (hasOwnProperty.call(tmplEventListeners, eventName)) return; tmplEventListeners[eventName] = createEventHandler("event-" + eventName); if (USE_CAPTURE_FALLBACK) return; if (!MOUSE_ENTER_LEAVE_SUPPORT) { if (eventName == "mouseenter") return emulateEvent(eventName, "mouseover"); if (eventName == "mouseleave") return emulateEvent(eventName, "mouseout"); } for (var i = 0, names = eventUtils.browserEvents(eventName), browserEventName; browserEventName = names[i]; i++) eventUtils.addGlobalHandler(browserEventName, tmplEventListeners[eventName]); } var SET_CLASS_ATTRIBUTE_BUG = function () { var element = document.createElement("div"); element.setAttribute("class", "a"); return !element.className; }(); var SET_STYLE_ATTRIBUTE_BUG = function () { var element = document.createElement("div"); element.setAttribute("style", "position:absolute"); return element.style.position != "absolute"; }(); function setEventAttribute(node, eventName, actions) { regEventHandler(eventName); if (IS_TOUCH_DEVICE && MOUSE_EVENTS.indexOf(eventName) != -1) node.setAttribute("style", "cursor:pointer;" + (node.getAttribute("style") || "")); if (USE_CAPTURE_FALLBACK) node.setAttribute("on" + eventName, USE_CAPTURE_FALLBACK + "(\"" + eventName + "\",event)"); node.setAttribute("event-" + eventName, actions); } function setAttribute(node, name, value) { if (SET_CLASS_ATTRIBUTE_BUG && name == "class") name = "className"; if (SET_STYLE_ATTRIBUTE_BUG && name == "style") return node.style.cssText = value; var namespace = namespaces.getNamespace(name, node); if (namespace) node.setAttributeNS(namespace, name, value); else node.setAttribute(name, value); } var buildDOM = function (tokens, offset, result) { for (var i = offset, token; token = tokens[i]; i++) { var tokenType = token[TOKEN_TYPE]; switch (tokenType) { case TYPE_ELEMENT: var tagName = token[ELEMENT_NAME]; var namespace = namespaces.getNamespace(tagName); var element = namespace ? document.createElementNS(namespace, tagName) : document.createElement(tagName); buildDOM(token, ELEMENT_ATTRIBUTES_AND_CHILDREN, element); result.appendChild(element); break; case TYPE_CONTENT: buildDOM(token, CONTENT_CHILDREN, result); break; case TYPE_ATTRIBUTE: if (!token[TOKEN_BINDINGS]) setAttribute(result, token[ATTR_NAME], token[ATTR_VALUE] || ""); break; case TYPE_ATTRIBUTE_CLASS: var attrValue = token[ATTR_VALUE_INDEX[tokenType]]; attrValue = attrValue ? [attrValue] : []; if (token[TOKEN_BINDINGS]) for (var j = 0, binding; binding = token[TOKEN_BINDINGS][j]; j++) { var defaultValue = binding[4]; if (defaultValue) { var prefix = binding[0]; if (Array.isArray(prefix)) { attrValue.push(prefix[defaultValue - 1]); } else { switch (binding[2]) { case CLASS_BINDING_BOOL: case CLASS_BINDING_INVERT: attrValue.push(prefix + binding[3]); break; case CLASS_BINDING_ENUM: attrValue.push(prefix + binding[5][defaultValue - 1]); break; } } } } if (attrValue.length) setAttribute(result, "class", attrValue.join(" ")); break; case TYPE_ATTRIBUTE_STYLE: var attrValue = token[ATTR_VALUE_INDEX[tokenType]]; if (attrValue) setAttribute(result, "style", (result.getAttribute("style") || "") + attrValue); break; case TYPE_ATTRIBUTE_EVENT: setEventAttribute(result, token[1], token[2] || token[1]); break; case TYPE_COMMENT: result.appendChild(document.createComment(token[COMMENT_VALUE] || (token[TOKEN_REFS] ? "{" + token[TOKEN_REFS].join("|") + "}" : ""))); break; case TYPE_TEXT: if (CLONE_NORMALIZATION_TEXT_BUG && i && tokens[i - 1][TOKEN_TYPE] == TYPE_TEXT) result.appendChild(document.createComment("")); result.appendChild(document.createTextNode(token[TEXT_VALUE] || (token[TOKEN_REFS] ? "{" + token[TOKEN_REFS].join("|") + "}" : "") || (token[TOKEN_BINDINGS] ? "{" + token[TOKEN_BINDINGS] + "}" : ""))); break; } } return result; }; module.exports = function (tokens) { var result = buildDOM(tokens, 0, document.createDocumentFragment()); if (result.childNodes.length === 1) result = result.removeChild(result.firstChild); return result; }; }, "e.js": function (exports, module, basis, global, __filename, __dirname, require, resource, asset) { var namespace = "basis.dom.event"; var document = global.document; var extend = basis.object.extend; var $null = basis.fn.$null; var arrayFrom = basis.array.from; var globalEvents = {}; var EVENT_HOLDER = "basisEvents_" + basis.genUID(); var W3CSUPPORT = !!document.addEventListener; var KEY = { BACKSPACE: 8, TAB: 9, CTRL_ENTER: 10, ENTER: 13, SHIFT: 16, CTRL: 17, ALT: 18, ESC: 27, ESCAPE: 27, SPACE: 32, PAGEUP: 33, PAGEDOWN: 34, END: 35, HOME: 36, LEFT: 37, UP: 38, RIGHT: 39, DOWN: 40, INSERT: 45, DELETE: 46, F1: 112, F2: 113, F3: 114, F4: 115, F5: 116, F6: 117, F7: 118, F8: 119, F9: 120, F10: 121, F11: 122, F12: 123 }; var MOUSE_LEFT = { VALUE: 1, BIT: 1 }; var MOUSE_MIDDLE = { VALUE: 2, BIT: 4 }; var MOUSE_RIGHT = { VALUE: 3, BIT: 2 }; var BROWSER_EVENTS = { mousewheel: [ "wheel", "mousewheel", "DOMMouseScroll" ] }; var DEPRECATED_PROPERTIES = [ "returnValue", "keyLocation", "layerX", "layerY", "webkitMovementX", "webkitMovementY", "keyIdentifier" ]; var TYPE_KEYBOARD = 0; var TYPE_MOUSE = 1; var TYPE_TOUCH = 2; var TYPE_POINTER = 3; var INPUT_TYPE = { keydown: TYPE_KEYBOARD, keypress: TYPE_KEYBOARD, keyup: TYPE_KEYBOARD, click: TYPE_MOUSE, dblclick: TYPE_MOUSE, mousedown: TYPE_MOUSE, mouseup: TYPE_MOUSE, mouseover: TYPE_MOUSE, mousemove: TYPE_MOUSE, mouseout: TYPE_MOUSE, mouseenter: TYPE_MOUSE, mouseleave: TYPE_MOUSE, wheel: TYPE_MOUSE, mousewheel: TYPE_MOUSE, DOMMouseScroll: TYPE_MOUSE, touchstart: TYPE_TOUCH, touchmove: TYPE_TOUCH, touchend: TYPE_TOUCH, touchcancel: TYPE_TOUCH, pointerover: TYPE_POINTER, pointerenter: TYPE_POINTER, pointerdown: TYPE_POINTER, pointermove: TYPE_POINTER, pointerup: TYPE_POINTER, pointercancel: TYPE_POINTER, pointerout: TYPE_POINTER, pointerleave: TYPE_POINTER }; function browserEvents(eventName) { return BROWSER_EVENTS[eventName] || [eventName]; } function getPath(node) { var path = []; do { path.push(node); } while (node = node.parentNode); path.push(global); return path; } var Event = basis.Class(null, { className: namespace + ".Event", KEY: KEY, init: function (event) { event = wrap(event); for (var name in event) if (DEPRECATED_PROPERTIES.indexOf(name) == -1 && (event.type != "progress" || name != "totalSize" && name != "position")) if (typeof event[name] != "function" && name in this == false) this[name] = event[name]; var target = sender(event); extend(this, { event_: event, sender: target, target: target, path: event.path ? basis.array(event.path) : getPath(target) }); switch (INPUT_TYPE[event.type]) { case TYPE_KEYBOARD: extend(this, { key: key(event), charCode: charCode(event) }); break; case TYPE_MOUSE: extend(this, { mouseLeft: mouseButton(event, MOUSE_LEFT), mouseMiddle: mouseButton(event, MOUSE_MIDDLE), mouseRight: mouseButton(event, MOUSE_RIGHT), mouseX: mouseX(event), mouseY: mouseY(event), wheelDelta: wheelDelta(event), pointerX: mouseX(event), pointerY: mouseY(event) }); break; case TYPE_TOUCH: extend(this, { touchX: touchX(event), touchY: touchY(event), mouseX: touchX(event), mouseY: touchY(event), pointerX: touchX(event), pointerY: touchY(event) }); break; case TYPE_POINTER: extend(this, { pointerX: mouseX(event), pointerY: mouseY(event), mouseX: mouseX(event), mouseY: mouseY(event) }); break; } }, stopBubble: function () { cancelBubble(this.event_); }, stopPropagation: function () { cancelBubble(this.event_); }, preventDefault: function () { cancelDefault(this.event_); }, die: function () { this.stopBubble(); this.preventDefault(); } }); function wrap(event) { return event instanceof Event ? event.event_ : event || global.event; } function getNode(ref) { return typeof ref == "string" ? document.getElementById(ref) : ref; } function sender(event) { var target = event.target || event.srcElement || document; return target.nodeType == 3 ? target.parentNode : target; } function cancelBubble(event) { if (event.stopPropagation) event.stopPropagation(); else event.cancelBubble = true; } function cancelDefault(event) { if (event.preventDefault) event.preventDefault(); else event.returnValue = false; } function kill(event, node) { node = getNode(node); if (node) addHandler(node, event, kill); else { cancelDefault(event); cancelBubble(event); } } function key(event) { return event.keyCode || event.which || 0; } function charCode(event) { return event.charCode || event.keyCode || 0; } function mouseButton(event, button) { if (typeof event.which == "number") return event.which == button.VALUE; else return !!(event.button & button.BIT); } function mouseX(event) { if ("pageX" in event) return event.pageX; else return "clientX" in event ? event.clientX + (document.compatMode == "CSS1Compat" ? document.documentElement.scrollLeft : document.body.scrollLeft) : 0; } function mouseY(event) { if ("pageY" in event) return event.pageY; else return "clientY" in event ? event.clientY + (document.compatMode == "CSS1Compat" ? document.documentElement.scrollTop : document.body.scrollTop) : 0; } function touchX(event) { if (event.changedTouches) return event.changedTouches[0].pageX; } function touchY(event) { if (event.changedTouches) return event.changedTouches[0].pageY; } function wheelDelta(event) { var delta = 0; if ("deltaY" in event) delta = -event.deltaY; else if ("wheelDelta" in event) delta = event.wheelDelta; else if (event.type == "DOMMouseScroll") delta = -event.detail; return delta && delta / Math.abs(delta); } var globalHandlers = {}; var captureHandlers = {}; var noCaptureScheme = !W3CSUPPORT; var flushAsap = true; var lastFrameStartEvent; var lastFrameFinishEvent; function startFrame(event) { if (flushAsap && event !== lastFrameStartEvent) { lastFrameStartEvent = event; basis.codeFrame.start(); } } function finishFrame(event) { if (flushAsap && event !== lastFrameFinishEvent) { lastFrameFinishEvent = event; basis.codeFrame.finish(); } } function observeGlobalEvents(event) { var handlers = arrayFrom(globalHandlers[event.type]); var captureHandler = captureHandlers[event.type]; var wrappedEvent = new Event(event); startFrame(event); if (captureHandler) { captureHandler.handler.call(captureHandler.thisObject, wrappedEvent); } else { if (handlers) { for (var i = handlers.length; i-- > 0;) { var handlerObject = handlers[i]; handlerObject.handler.call(handlerObject.thisObject, wrappedEvent); } } } finishFrame(event); } function captureEvent(eventType, handler, thisObject) { if (captureHandlers[eventType]) releaseEvent(eventType); if (!handler) handler = basis.fn.$undef; addGlobalHandler(eventType, handler, thisObject); captureHandlers[eventType] = { handler: handler, thisObject: thisObject }; } function releaseEvent(eventType) { var handlerObject = captureHandlers[eventType]; if (handlerObject) { removeGlobalHandler(eventType, handlerObject.handler, handlerObject.thisObject); delete captureHandlers[eventType]; } } function addGlobalHandler(eventType, handler, thisObject) { var handlers = globalHandlers[eventType]; if (handlers) { for (var i = 0, item; item = handlers[i]; i++) if (item.handler === handler && item.thisObject === thisObject) return; } else { if (noCaptureScheme) addHandler(document, eventType, $null); else document.addEventListener(eventType, observeGlobalEvents, true); handlers = globalHandlers[eventType] = []; } handlers.push({ handler: handler, thisObject: thisObject }); } function removeGlobalHandler(eventType, handler, thisObject) { var handlers = globalHandlers[eventType]; if (handlers) { for (var i = 0, item; item = handlers[i]; i++) { if (item.handler === handler && item.thisObject === thisObject) { handlers.splice(i, 1); if (!handlers.length) { delete globalHandlers[eventType]; if (noCaptureScheme) removeHandler(document, eventType, $null); else document.removeEventListener(eventType, observeGlobalEvents, true); } return; } } } } function addHandler(node, eventType, handler, thisObject) { node = getNode(node); if (!node) throw "basis.event.addHandler: can't attach event listener to undefined"; if (typeof handler != "function") throw "basis.event.addHandler: handler is not a function"; var handlers = node === global ? globalEvents : node[EVENT_HOLDER]; if (!handlers) handlers = node[EVENT_HOLDER] = {}; var eventTypeHandlers = handlers[eventType]; var handlerObject = { handler: handler, thisObject: thisObject }; if (!eventTypeHandlers) { eventTypeHandlers = handlers[eventType] = [handlerObject]; eventTypeHandlers.fireEvent = function (event) { event = wrap(event); if (noCaptureScheme && event && globalHandlers[eventType]) { if (typeof event.returnValue == "undefined") { observeGlobalEvents(event); if (event.cancelBubble === true) return; if (typeof event.returnValue == "undefined") event.returnValue = true; } } startFrame(event); for (var i = 0, wrappedEvent = new Event(event), item; item = eventTypeHandlers[i++];) item.handler.call(item.thisObject, wrappedEvent); finishFrame(event); }; if (W3CSUPPORT) node.addEventListener(eventType, eventTypeHandlers.fireEvent, false); else node.attachEvent("on" + eventType, eventTypeHandlers.fireEvent); } else { for (var i = 0, item; item = eventTypeHandlers[i]; i++) if (item.handler === handler && item.thisObject === thisObject) return; eventTypeHandlers.push(handlerObject); } } function addHandlers(node, handlers, thisObject) { node = getNode(node); for (var eventType in handlers) addHandler(node, eventType, handlers[eventType], thisObject); } function removeHandler(node, eventType, handler, thisObject) { node = getNode(node); var handlers = node === global ? globalEvents : node[EVENT_HOLDER]; if (handlers) { var eventTypeHandlers = handlers[eventType]; if (eventTypeHandlers) { for (var i = 0, item; item = eventTypeHandlers[i]; i++) { if (item.handler === handler && item.thisObject === thisObject) { eventTypeHandlers.splice(i, 1); if (!eventTypeHandlers.length) clearHandlers(node, eventType); return; } } } } } function clearHandlers(node, eventType) { node = getNode(node); var handlers = node === global ? globalEvents : node[EVENT_HOLDER]; if (handlers) { if (typeof eventType != "string") { for (eventType in handlers) clearHandlers(node, eventType); } else { var eventTypeHandlers = handlers[eventType]; if (eventTypeHandlers) { if (node.removeEventListener) node.removeEventListener(eventType, eventTypeHandlers.fireEvent, false); else node.detachEvent("on" + eventType, eventTypeHandlers.fireEvent); delete handlers[eventType]; } } } } function fireEvent(node, eventType, event) { node = getNode(node); var handlers = node === global ? globalEvents : node[EVENT_HOLDER]; if (handlers && handlers[eventType]) { try { flushAsap = false; handlers[eventType].fireEvent(event); } finally { flushAsap = true; } } } function onUnload(handler, thisObject) { basis.dev.warn("basis.dom.event.onUnload() is deprecated, use basis.teardown() instead"); basis.teardown(handler, thisObject); } var tagNameEventMap = {}; function getEventInfo(eventName, tagName) { if (!tagName) tagName = "div"; var id = tagName + "-" + eventName; if (tagNameEventMap[id]) return tagNameEventMap[id]; else { var supported = false; var bubble = false; if (!W3CSUPPORT) { var onevent = "on" + eventName; var host = document.createElement("div"); var target = host.appendChild(document.createElement(tagName)); host[onevent] = function () { bubble = true; }; try { target.fireEvent(onevent); supported = true; } catch (e) { } } return tagNameEventMap[id] = { supported: supported, bubble: bubble }; } } function wrapEventFunction(fn) { return function (event, arg) { return fn(wrap(event), arg); }; } module.exports = { W3CSUPPORT: W3CSUPPORT, browserEvents: browserEvents, getEventInfo: getEventInfo, KEY: KEY, MOUSE_LEFT: MOUSE_LEFT, MOUSE_RIGHT: MOUSE_RIGHT, MOUSE_MIDDLE: MOUSE_MIDDLE, Event: Event, sender: wrapEventFunction(sender), cancelBubble: wrapEventFunction(cancelBubble), cancelDefault: wrapEventFunction(cancelDefault), kill: wrapEventFunction(kill), key: wrapEventFunction(key), charCode: wrapEventFunction(charCode), mouseButton: wrapEventFunction(mouseButton), mouseX: wrapEventFunction(mouseX), mouseY: wrapEventFunction(mouseY), wheelDelta: wrapEventFunction(wheelDelta), touchX: wrapEventFunction(touchX), touchY: wrapEventFunction(touchY), addGlobalHandler: addGlobalHandler, removeGlobalHandler: removeGlobalHandler, captureEvent: captureEvent, releaseEvent: releaseEvent, addHandler: addHandler, addHandlers: addHandlers, removeHandler: removeHandler, clearHandlers: clearHandlers, fireEvent: fireEvent, onUnload: onUnload, wrap: wrap }; }, "f.js": function (exports, module, basis, global, __filename, __dirname, require, resource, asset) { var namespace = "basis.dom.wrapper"; var hasOwnProperty = Object.prototype.hasOwnProperty; var Class = basis.Class; var complete = basis.object.complete; var arrayFrom = basis.array; var arrayRemove = basis.array.remove; var $undef = basis.fn.$undef; var getter = basis.getter; var nullGetter = basis.fn.nullGetter; var basisEvent = basis.require("./3.js"); var createEvent = basisEvent.create; var events = basisEvent.events; var basisData = basis.require("./g.js"); var resolveValue = basisData.resolveValue; var resolveDataset = basisData.resolveDataset; var createResolveFunction = basisData.createResolveFunction; var SUBSCRIPTION = basisData.SUBSCRIPTION; var STATE = basisData.STATE; var DataObject = basisData.Object; var ReadOnlyDataset = basisData.ReadOnlyDataset; var Dataset = basisData.Dataset; var EXCEPTION_CANT_INSERT = namespace + ": Node can't be inserted at specified point in hierarchy"; var EXCEPTION_NODE_NOT_FOUND = namespace + ": Node was not found"; var EXCEPTION_BAD_CHILD_CLASS = namespace + ": Child node has wrong class"; var EXCEPTION_NULL_CHILD = namespace + ": Child node is null"; var EXCEPTION_DATASOURCE_CONFLICT = namespace + ": Operation is not allowed because node is under dataSource control"; var EXCEPTION_DATASOURCEADAPTER_CONFLICT = namespace + ": Operation is not allowed because node is under dataSource adapter control"; var EXCEPTION_PARENTNODE_OWNER_CONFLICT = namespace + ": Node can't has owner and parentNode"; var EXCEPTION_NO_CHILDCLASS = namespace + ": Node can't has children and dataSource as childClass isn't specified"; var AUTO = "__auto__"; var DELEGATE = { ANY: true, NONE: false, PARENT: "parent", OWNER: "owner" }; var childNodesDatasetMap = {}; var satellitesDatasetMap = {}; function warnOnDataSourceItemNodeDestoy() { basis.dev.warn(namespace + ": node can't be destroyed as representing dataSource item, destroy delegate item or remove it from dataSource first"); } function warnOnAutoSatelliteOwnerChange() { basis.dev.warn(namespace + ": satellite can't change owner as it auto-satellite"); } function warnOnAutoSatelliteDestoy() { basis.dev.warn(namespace + ": satellite can't be destroyed as it auto-create satellite, and could be destroyed on owner destroy"); } function lockDataSourceItemNode(node) { node.setDelegate = basis.fn.$undef; node.destroy = warnOnDataSourceItemNodeDestoy; } function unlockDataSourceItemNode(node) { var proto = node.constructor.prototype; node.setDelegate = proto.setDelegate; node.destroy = proto.destroy; } function getSortingValue(node) { return node.sortingValue; } function sortAsc(a, b) { a = a.sortingValue || 0; b = b.sortingValue || 0; return +(a > b) || -(a < b); } function sortDesc(a, b) { a = a.sortingValue || 0; b = b.sortingValue || 0; return -(a > b) || +(a < b); } function sortChildNodes(obj) { return obj.childNodes.sort(obj.sortingDesc ? sortDesc : sortAsc); } function binarySearchPos(array, value, valueGetter, desc) { if (!array.length) return 0; desc = !!desc; var l = 0; var r = array.length - 1; var valueType = typeof value; var compareValue; var compareValueType; var pos; do { pos = l + r >> 1; compareValue = valueGetter(array[pos]); compareValueType = typeof compareValue; if (desc) { if (valueType > compareValueType || value > compareValue) { r = pos - 1; continue; } if (valueType < compareValueType || value < compareValue) { l = pos + 1; continue; } } else { if (valueType < compareValueType || value < compareValue) { r = pos - 1; continue; } if (valueType > compareValueType || value > compareValue) { l = pos + 1; continue; } } return value == compareValue ? pos : 0; } while (l <= r); return pos + ((compareValueType < valueType || compareValue < value) ^ desc); } function updateNodeContextSelection(root, oldSelection, newSelection, rootUpdate, ignoreRootSelection) { if (oldSelection === newSelection) return; var nextNode; var cursor = root; var selected = []; if (rootUpdate) { root.contextSelection = newSelection; if (root.selected && !root.selectedRA_) selected.push(root); } while (cursor) { nextNode = !cursor.selection || ignoreRootSelection && cursor === root ? cursor.firstChild : null; if (nextNode && nextNode.contextSelection !== oldSelection) throw "Try change wrong context selection"; while (!nextNode) { if (cursor === root) { if (selected.length) { if (oldSelection) oldSelection.remove(selected); if (newSelection) { newSelection.add(selected); for (var i = 0; i < selected.length; i++) { var node = selected[i]; if (node.selected && !newSelection.has(node)) { node.selected = false; node.emit_unselect(); } } } } return; } nextNode = cursor.nextSibling; if (!nextNode) cursor = cursor.parentNode; } cursor = nextNode; if (cursor.selected && !cursor.selectedRA_) selected.push(cursor); cursor.contextSelection = newSelection; } } function updateNodeDisableContext(node, disabled) { if (node.contextDisabled != disabled) { node.contextDisabled = disabled; if (node.disabled) return; if (disabled) node.emit_disable(); else node.emit_enable(); } } SUBSCRIPTION.addProperty("owner"); SUBSCRIPTION.addProperty("dataSource"); SUBSCRIPTION.add("CHILD", { childNodesModified: function (object, delta) { var array; if (array = delta.inserted) for (var i = 0, child; child = array[i]; i++) SUBSCRIPTION.link("child", object, child); if (array = delta.deleted) for (var i = 0, child; child = array[i]; i++) SUBSCRIPTION.unlink("child", object, child); } }, function (action, object) { var childNodes = object.childNodes || []; for (var i = 0, child; child = childNodes[i]; i++) action("child", object, child); }); SUBSCRIPTION.add("SATELLITE", { satelliteChanged: function (object, name, oldSatellite) { if (oldSatellite) SUBSCRIPTION.unlink("satellite", object, oldSatellite); if (object.satellite[name]) SUBSCRIPTION.link("satellite", object, object.satellite[name]); } }, function (action, object) { var satellites = object.satellite; if (satellites !== NULL_SATELLITE) for (var name in satellites) if (name !== AUTO) action("satellite", object, satellites[name]); }); function processInstanceClass(InstanceClass) { if (!InstanceClass.isSubclassOf(AbstractNode)) { basis.dev.warn(namespace + ": Bad class for instance, should be subclass of basis.dom.wrapper.AbstractNode"); return AbstractNode; } return InstanceClass; } function processSatelliteConfig(satelliteConfig) { var loc; if (!satelliteConfig) return null; if (satelliteConfig.isSatelliteConfig) return satelliteConfig; if (satelliteConfig instanceof AbstractNode) return satelliteConfig; if (satelliteConfig.constructor !== Object) satelliteConfig = { instance: satelliteConfig }; else loc = basis.dev.getInfo(satelliteConfig, "loc"); var handlerRequired = false; var events = "update"; var config = { isSatelliteConfig: true }; for (var key in satelliteConfig) { var value = satelliteConfig[key]; switch (key) { case "instance": if (value instanceof AbstractNode) { config.instance = value; } else { if (Class.isClass(value)) config.instanceClass = processInstanceClass(value); else { if (typeof value == "string") value = basis.getter(value); config.getInstance = value; } } break; case "instanceOf": case "satelliteClass": if (key == "instanceOf") { basis.dev.warn(namespace + ": `instanceOf` in satellite config is deprecated, use `instance` instead"); if ("satelliteClass" in satelliteConfig) { basis.dev.warn(namespace + ": `instanceOf` in satellite config has been ignored, as `satelliteClass` is specified"); break; } } if ("instance" in satelliteConfig) { basis.dev.warn(namespace + ": `" + key + "` in satellite config has been ignored, as `instance` is specified"); break; } if (Class.isClass(value)) { basis.dev.warn(namespace + ": `" + key + "` in satellite config is deprecated, use `instance` instead"); config.instanceClass = processInstanceClass(value); } else basis.dev.warn(namespace + ": bad value for `" + key + "` in satellite config, value should be a subclass of basis.dom.wrapper.AbstractNode"); break; case "existsIf": case "delegate": case "dataSource": if (value) { if (typeof value == "string") value = getter(value); if (typeof value != "function") value = basis.fn.$const(value); else handlerRequired = true; } config[key] = value; break; case "config": if (typeof value == "string") value = getter(value); config.config = value; break; case "events": events = satelliteConfig.events; break; default: basis.dev.warn("Unknown satellite config option \u2013 " + key); } } if (!config.instance && !config.getInstance && !config.instanceClass) config.instanceClass = processInstanceClass(AbstractNode); if (handlerRequired) { if (Array.isArray(events)) events = events.join(" "); if (typeof events == "string") { var handler = {}; events = events.split(/\s+/); for (var i = 0, eventName; eventName = events[i]; i++) { handler[eventName] = SATELLITE_UPDATE; config.handler = handler; } } } if (loc) basis.dev.setInfo(config, "loc", loc); return config; } function applySatellites(node, satellites) { for (var name in satellites) if (satellites[name] && typeof satellites[name] == "object") node.setSatellite(name, satellites[name]); } var NULL_SATELLITE = Class.customExtendProperty({}, function (result, extend) { var map = basis.dev.getInfo(extend, "map"); for (var name in extend) { result[name] = processSatelliteConfig(extend[name]); if (map && !basis.dev.getInfo(result[name]) && hasOwnProperty.call(map, name)) basis.dev.setInfo(result[name], "loc", map[name]); } }); var SATELLITE_UPDATE = function () { var name = this.name; var config = this.config; var owner = this.owner; var exists = "existsIf" in config == false || config.existsIf(owner); if (resolveValue(this, SATELLITE_UPDATE, exists, "existsRA_")) { var satellite = this.instance || config.instance; if (!satellite || this.factoryType == "value") { if (!this.factoryType) { var instanceValue = config.getInstance; var instanceClass = config.instanceClass; if (typeof instanceValue == "function") { instanceValue = instanceValue.call(owner, owner); if (Class.isClass(instanceValue)) instanceClass = processInstanceClass(instanceValue); } this.factoryType = instanceClass ? "class" : "value"; this.factory = instanceClass || instanceValue; } if (this.factoryType == "class") { var satelliteConfig = { destroy: warnOnAutoSatelliteDestoy }; if (config.delegate) { satelliteConfig.autoDelegate = false; satelliteConfig.delegate = config.delegate(owner); } if (config.dataSource) satelliteConfig.dataSource = config.dataSource(owner); if (config.config) basis.object.complete(satelliteConfig, typeof config.config == "function" ? config.config(owner) : config.config); this.instance = new this.factory(satelliteConfig); owner.setSatellite(name, this.instance, true); var loc = basis.dev.getInfo(config, "loc"); if (loc) basis.dev.setInfo(this.instance, "loc", loc); return; } satellite = resolveAbstractNode(this, SATELLITE_UPDATE, this.factory, "instanceRA_"); } if (this.instance !== satellite) { this.instance = satellite || null; owner.setSatellite(name, this.instance, true); } if (satellite && satellite.owner === owner) { if (config.delegate) satellite.setDelegate(config.delegate(owner)); if (config.dataSource) satellite.setDataSource(config.dataSource(owner)); } } else { var satellite = this.instance; if (satellite) { if (config.instance) { if (config.delegate) satellite.setDelegate(); if (config.dataSource) satellite.setDataSource(); } this.instance = null; owner.setSatellite(name, null, true); } } }; var AUTO_SATELLITE_INSTANCE_HANDLER = { destroy: function () { if (!this.instanceRA_) this.owner.setSatellite(this.name, null); } }; var AbstractNode = Class(DataObject, { className: namespace + ".AbstractNode", propertyDescriptors: { owner: "ownerChanged", parentNode: "parentChanged", childNodes: { nested: ["length"], events: "childNodesModified" }, childNodesState: "childNodesStateChanged", dataSource: "dataSourceChanged", "getChildNodesDataset()": true, satellite: { nested: true, events: "satelliteChanged" }, sorting: "sortingChanged", sortingDesc: "sortingChanged", grouping: "groupingChanged", ownerSatelliteName: "ownerSatelliteNameChanged", firstChild: false, lastChild: false, previousSibling: false, nextSibling: false, groupNode: false, groupId: true, autoDelegate: false, destroyDataSourceMember: false, name: true }, subscribeTo: DataObject.prototype.subscribeTo + SUBSCRIPTION.DATASOURCE + SUBSCRIPTION.SATELLITE, isSyncRequired: function () { return this.state == STATE.UNDEFINED || this.state == STATE.DEPRECATED; }, syncEvents: { activeChanged: false }, emit_update: function (delta) { DataObject.prototype.emit_update.call(this, delta); var parentNode = this.parentNode; if (parentNode) { if (parentNode.matchFunction) this.match(parentNode.matchFunction); parentNode.insertBefore(this, this.nextSibling); } }, listen: { owner: { destroy: function () { if (!this.ownerSatelliteName) this.setOwner(); } } }, autoDelegate: DELEGATE.NONE, name: null, childNodes: null, emit_childNodesModified: createEvent("childNodesModified", "delta") && function (delta) { events.childNodesModified.call(this, delta); var listen = this.listen.childNode; var array; if (listen) { if (array = delta.inserted) for (var i = 0, child; child = array[i]; i++) child.addHandler(listen, this); if (array = delta.deleted) for (var i = 0, child; child = array[i]; i++) child.removeHandler(listen, this); } }, childNodesState: STATE.UNDEFINED, emit_childNodesStateChanged: createEvent("childNodesStateChanged", "oldState"), childClass: Class.SELF, dataSource: null, emit_dataSourceChanged: createEvent("dataSourceChanged", "oldDataSource"), dataSourceRA_: null, dataSourceMap_: null, destroyDataSourceMember: true, parentNode: null, emit_parentChanged: createEvent("parentChanged", "oldParentNode"), nextSibling: null, previousSibling: null, firstChild: null, lastChild: null, sorting: nullGetter, sortingDesc: false, emit_sortingChanged: createEvent("sortingChanged", "oldSorting", "oldSortingDesc"), groupingClass: null, grouping: null, emit_groupingChanged: createEvent("groupingChanged", "oldGrouping"), groupNode: null, groupId: NaN, satellite: NULL_SATELLITE, emit_satelliteChanged: createEvent("satelliteChanged", "name", "oldSatellite"), ownerSatelliteName: null, emit_ownerSatelliteNameChanged: createEvent("ownerSatelliteNameChanged", "name", "oldName"), owner: null, emit_ownerChanged: createEvent("ownerChanged", "oldOwner"), init: function () { DataObject.prototype.init.call(this); var childNodes = this.childNodes; var dataSource = this.dataSource; if (childNodes) this.childNodes = null; if (dataSource) this.dataSource = null; var grouping = this.grouping; if (grouping) { this.grouping = null; this.setGrouping(grouping); } if (this.childClass) { this.childNodes = []; if (dataSource) { this.setDataSource(dataSource); } else { if (childNodes) this.setChildNodes(childNodes); } } var satellites = this.satellite; if (satellites !== NULL_SATELLITE) { this.satellite = NULL_SATELLITE; applySatellites(this, satellites); } var owner = this.owner; if (owner) { this.owner = null; this.setOwner(owner); } }, setChildNodesState: function (state, data) { var stateCode = String(state); var oldState = this.childNodesState; if (!STATE.values[stateCode]) throw new Error("Wrong state value"); if (oldState != stateCode || oldState.data != data) { this.childNodesState = Object(stateCode); this.childNodesState.data = data; this.emit_childNodesStateChanged(oldState); } }, appendChild: function (newChild) { }, insertBefore: function (newChild, refChild) { }, removeChild: function (oldChild) { }, replaceChild: function (newChild, oldChild) { }, clear: function (alive) { }, setChildNodes: function (nodes) { }, setGrouping: function (grouping, alive) { }, setSorting: function (sorting, desc) { }, setDataSource: function (dataSource) { }, setOwner: function (owner) { if (!owner || owner instanceof AbstractNode == false) owner = null; if (owner && this.parentNode) throw EXCEPTION_PARENTNODE_OWNER_CONFLICT; var oldOwner = this.owner; if (oldOwner !== owner) { var listenHandler = this.listen.owner; if (oldOwner) { if (this.ownerSatelliteName && oldOwner.satellite[AUTO] && this.ownerSatelliteName in oldOwner.satellite[AUTO]) { basis.dev.warn(namespace + ": auto-satellite can't change it's owner"); return; } if (listenHandler) oldOwner.removeHandler(listenHandler, this); if (this.ownerSatelliteName) { this.owner = null; oldOwner.setSatellite(this.ownerSatelliteName, null); } } if (owner && listenHandler) owner.addHandler(listenHandler, this); this.owner = owner; this.emit_ownerChanged(oldOwner); if (this.autoDelegate == DELEGATE.OWNER || this.autoDelegate === DELEGATE.ANY) this.setDelegate(owner); } }, setSatellite: function (name, satellite, autoSet) { var oldSatellite = this.satellite[name] || null; var auto = this.satellite[AUTO]; var autoConfig = auto && auto[name]; var preserveAuto = autoSet && autoConfig; if (preserveAuto) { satellite = autoConfig.instance; if (satellite && autoConfig.config.instance) delete autoConfig.config.instance.setOwner; } else { satellite = processSatelliteConfig(satellite); if (satellite && satellite.owner === this && auto && satellite.ownerSatelliteName && auto[satellite.ownerSatelliteName]) { basis.dev.warn(namespace + ": auto-create satellite can't change name inside owner"); return; } if (autoConfig) { delete auto[name]; if (autoConfig.config.instance) autoConfig.config.instance.removeHandler(AUTO_SATELLITE_INSTANCE_HANDLER, autoConfig); if (autoConfig.config.handler) this.removeHandler(autoConfig.config.handler, autoConfig); } } if (oldSatellite !== satellite) { var satelliteListen = this.listen.satellite; var satellitePersonalListen = this.listen["satellite:" + name]; var destroySatellite; if (oldSatellite) { delete this.satellite[name]; var oldSatelliteName = oldSatellite.ownerSatelliteName; if (oldSatelliteName != null) { oldSatellite.ownerSatelliteName = null; oldSatellite.emit_ownerSatelliteNameChanged(oldSatelliteName); } if (autoConfig && oldSatellite.destroy === warnOnAutoSatelliteDestoy) { destroySatellite = oldSatellite; } else { if (satelliteListen) oldSatellite.removeHandler(satelliteListen, this); if (satellitePersonalListen) oldSatellite.removeHandler(satellitePersonalListen, this); oldSatellite.setOwner(null); } if (preserveAuto && !satellite && autoConfig.config.instance) autoConfig.config.instance.setOwner = warnOnAutoSatelliteOwnerChange; } if (satellite) { if (satellite instanceof AbstractNode == false) { var autoConfig = { owner: this, name: name, config: satellite, factoryType: null, factory: null, instance: null, instanceRA_: null, existsRA_: null }; if (satellite.handler) this.addHandler(satellite.handler, autoConfig); if (satellite.instance) { satellite.instance.addHandler(AUTO_SATELLITE_INSTANCE_HANDLER, autoConfig); satellite.instance.setOwner = warnOnAutoSatelliteOwnerChange; } if (!auto) { if (this.satellite === NULL_SATELLITE) this.satellite = {}; auto = this.satellite[AUTO] = {}; } auto[name] = autoConfig; SATELLITE_UPDATE.call(autoConfig, this); if (!autoConfig.instance && oldSatellite) this.emit_satelliteChanged(name, oldSatellite); if (destroySatellite) { delete destroySatellite.destroy; destroySatellite.destroy(); } return; } if (satellite.owner !== this) { if (autoConfig && autoConfig.config.delegate) { var autoDelegate = satellite.autoDelegate; satellite.autoDelegate = false; satellite.setOwner(this); satellite.autoDelegate = autoDelegate; } else satellite.setOwner(this); if (satellite.owner !== this) { this.setSatellite(name, null); return; } if (satelliteListen) satellite.addHandler(satelliteListen, this); if (satellitePersonalListen) satellite.addHandler(satellitePersonalListen, this); } else { if (satellite.ownerSatelliteName) { delete this.satellite[satellite.ownerSatelliteName]; this.emit_satelliteChanged(satellite.ownerSatelliteName, satellite); } } if (this.satellite == NULL_SATELLITE) this.satellite = {}; this.satellite[name] = satellite; var oldSatelliteName = satellite.ownerSatelliteName; if (oldSatelliteName != name) { satellite.ownerSatelliteName = name; satellite.emit_ownerSatelliteNameChanged(oldSatelliteName); } } this.emit_satelliteChanged(name, oldSatellite); if (destroySatellite) { delete destroySatellite.destroy; destroySatellite.destroy(); } } }, getChildNodesDataset: function () { return childNodesDatasetMap[this.basisObjectId] || new ChildNodesDataset({ sourceNode: this }); }, getSatellitesDataset: function () { return satellitesDatasetMap[this.basisObjectId] || new SatellitesDataset({ sourceNode: this }); }, destroy: function () { DataObject.prototype.destroy.call(this); if (this.dataSource || this.dataSourceRA_) { this.setDataSource(); } else { if (this.firstChild) this.clear(); } if (this.parentNode) this.parentNode.removeChild(this); if (this.grouping) { this.grouping.setOwner(); this.grouping = null; } if (this.owner) this.setOwner(); var satellites = this.satellite; if (satellites !== NULL_SATELLITE) { var auto = satellites[AUTO]; delete satellites[AUTO]; for (var name in auto) { if (auto[name].config.instance && !auto[name].instance) auto[name].config.instance.destroy(); if (auto[name].existsRA_) resolveValue(auto[name], null, null, "existsRA_"); if (auto[name].instanceRA_) resolveValue(auto[name], null, null, "instanceRA_"); } for (var name in satellites) { var satellite = satellites[name]; satellite.owner = null; satellite.ownerSatelliteName = null; if (satellite.destroy === warnOnAutoSatelliteDestoy) delete satellite.destroy; satellite.destroy(); } this.satellite = null; } this.childNodes = null; } }); var resolveAbstractNode = createResolveFunction(AbstractNode); var PartitionNode = Class(AbstractNode, { className: namespace + ".PartitionNode", autoDestroyIfEmpty: false, nodes: null, first: null, last: null, init: function () { this.nodes = []; AbstractNode.prototype.init.call(this); }, insert: function (newNode, refNode) { var nodes = this.nodes; var pos = refNode ? nodes.indexOf(refNode) : -1; if (pos == -1) { nodes.push(newNode); this.last = newNode; } else nodes.splice(pos, 0, newNode); this.first = nodes[0]; newNode.groupNode = this; this.emit_childNodesModified({ inserted: [newNode] }); }, remove: function (oldNode) { var nodes = this.nodes; if (arrayRemove(nodes, oldNode)) { this.first = nodes[0] || null; this.last = nodes[nodes.length - 1] || null; oldNode.groupNode = null; this.emit_childNodesModified({ deleted: [oldNode] }); } if (!this.first && this.autoDestroyIfEmpty) this.destroy(); }, clear: function () { if (!this.first) return; var nodes = this.nodes; for (var i = nodes.length; i-- > 0;) nodes[i].groupNode = null; this.nodes = []; this.first = null; this.last = null; this.emit_childNodesModified({ deleted: nodes }); if (this.autoDestroyIfEmpty) this.destroy(); }, destroy: function () { AbstractNode.prototype.destroy.call(this); this.nodes = null; this.first = null; this.last = null; } }); var DOMMIXIN_DATASOURCE_HANDLER = { itemsChanged: function (dataSource, delta) { var newDelta = {}; var deleted = []; if (delta.deleted) { newDelta.deleted = deleted; if (this.childNodes.length == delta.deleted.length) { deleted = arrayFrom(this.childNodes); for (var i = 0, child; child = deleted[i]; i++) unlockDataSourceItemNode(child); this.dataSourceMap_ = null; this.clear(true); this.dataSourceMap_ = {}; } else { for (var i = 0, item; item = delta.deleted[i]; i++) { var delegateId = item.basisObjectId; var oldChild = this.dataSourceMap_[delegateId]; unlockDataSourceItemNode(oldChild); delete this.dataSourceMap_[delegateId]; this.removeChild(oldChild); deleted.push(oldChild); } } } if (delta.inserted) { newDelta.inserted = []; for (var i = 0, item; item = delta.inserted[i]; i++) { var newChild = createChildByFactory(this, { delegate: item }); lockDataSourceItemNode(newChild); this.dataSourceMap_[item.basisObjectId] = newChild; newDelta.inserted.push(newChild); if (this.firstChild) this.insertBefore(newChild); } } if (!this.firstChild) this.setChildNodes(newDelta.inserted); else this.emit_childNodesModified(newDelta); if (this.destroyDataSourceMember && deleted.length) for (var i = 0, item; item = deleted[i]; i++) item.destroy(); }, stateChanged: function (dataSource) { this.setChildNodesState(dataSource.state, dataSource.state.data); }, destroy: function () { if (!this.dataSourceRA_) this.setDataSource(); } }; function fastChildNodesOrder(node, order) { var lastIndex = order.length - 1; node.childNodes = order; node.firstChild = order[0] || null; node.lastChild = order[lastIndex] || null; for (var orderNode, i = lastIndex; orderNode = order[i]; i--) { orderNode.nextSibling = order[i + 1] || null; orderNode.previousSibling = order[i - 1] || null; node.insertBefore(orderNode, orderNode.nextSibling); } } function fastChildNodesGroupOrder(node, order) { for (var i = 0, child; child = order[i]; i++) child.groupNode.nodes.push(child); var groups = [node.grouping.nullGroup].concat(node.grouping.childNodes); var result = []; for (var i = 0, group; group = groups[i]; i++) { var nodes = group.nodes; group.first = nodes[0] || null; group.last = nodes[nodes.length - 1] || null; result.push.apply(result, nodes); group.emit_childNodesModified({ inserted: nodes }); } return result; } function createChildByFactory(node, config) { var child; if (typeof node.childFactory == "function") { child = node.childFactory(config); if (child instanceof node.childClass) { var info = basis.dev.getInfo(config); if (info) for (var key in info) basis.dev.setInfo(child, key, info[key]); return child; } } if (!child) throw EXCEPTION_NULL_CHILD; basis.dev.warn(EXCEPTION_BAD_CHILD_CLASS + " (expected " + (node.childClass && node.childClass.className) + " but " + (child && child.constructor && child.constructor.className) + ")"); throw EXCEPTION_BAD_CHILD_CLASS; } var DomMixin = { childClass: AbstractNode, childFactory: null, listen: { dataSource: DOMMIXIN_DATASOURCE_HANDLER }, getChild: function (value, getter) { return basis.array.search(this.childNodes, value, getter); }, getChildByName: function (name) { return this.getChild(name, "name"); }, appendChild: function (newChild) { return this.insertBefore(newChild); }, insertBefore: function (newChild, refChild) { if (!this.childClass) throw EXCEPTION_NO_CHILDCLASS; if (newChild.firstChild) { var cursor = this; while (cursor = cursor.parentNode) { if (cursor === newChild) throw EXCEPTION_CANT_INSERT; } } var isChildClassInstance = newChild && newChild instanceof this.childClass; if (this.dataSource) { if (!isChildClassInstance || !newChild.delegate || this.dataSourceMap_[newChild.delegate.basisObjectId] !== newChild) throw EXCEPTION_DATASOURCE_CONFLICT; } else { if (this.dataSourceRA_) throw EXCEPTION_DATASOURCEADAPTER_CONFLICT; } if (!isChildClassInstance) newChild = createChildByFactory(this, newChild instanceof DataObject ? { delegate: newChild } : newChild); if (newChild.owner) throw EXCEPTION_PARENTNODE_OWNER_CONFLICT; var isInside = newChild.parentNode === this; var childNodes = this.childNodes; var grouping = this.grouping; var groupNodes; var currentNewChildGroup = newChild.groupNode; var group = null; var sorting = this.sorting; var sortingDesc; var correctSortPos = false; var newChildValue; var pos = -1; var nextSibling; var prevSibling; if (isInside) { nextSibling = newChild.nextSibling; prevSibling = newChild.previousSibling; } if (sorting !== nullGetter) { refChild = null; sortingDesc = this.sortingDesc; newChildValue = sorting(newChild); if (newChildValue == null) newChildValue = -Infinity; else if (typeof newChildValue != "number" || newChildValue !== newChildValue) newChildValue = String(newChildValue); if (isInside) { if (newChildValue === newChild.sortingValue) { correctSortPos = true; } else { if (sortingDesc) { correctSortPos = (!nextSibling || typeof nextSibling.sortingValue <= typeof newChildValue && nextSibling.sortingValue <= newChildValue) && (!prevSibling || typeof prevSibling.sortingValue >= typeof newChildValue && prevSibling.sortingValue >= newChildValue); } else { correctSortPos = (!nextSibling || typeof nextSibling.sortingValue >= typeof newChildValue && nextSibling.sortingValue >= newChildValue) && (!prevSibling || typeof prevSibling.sortingValue <= typeof newChildValue && prevSibling.sortingValue <= newChildValue); } if (correctSortPos) newChild.sortingValue = newChildValue; } } } if (grouping) { var cursor; group = grouping.getGroupNode(newChild, true); groupNodes = group.nodes; if (currentNewChildGroup === group) if (correctSortPos || sorting === nullGetter && nextSibling === refChild) return newChild; if (sorting !== nullGetter) { if (currentNewChildGroup === group && correctSortPos) { if (nextSibling && nextSibling.groupNode === group) pos = groupNodes.indexOf(nextSibling); else pos = groupNodes.length; } else { pos = binarySearchPos(groupNodes, newChildValue, getSortingValue, sortingDesc); newChild.sortingValue = newChildValue; } } else { if (refChild && refChild.groupNode === group) pos = groupNodes.indexOf(refChild); else pos = groupNodes.length; } if (pos < groupNodes.length) { refChild = groupNodes[pos]; } else { if (group.last) { refChild = group.last.nextSibling; } else { cursor = group; refChild = null; while (cursor = cursor.nextSibling) if (refChild = cursor.first) break; } } if (newChild === refChild || isInside && nextSibling === refChild) { if (currentNewChildGroup !== group) { if (currentNewChildGroup) currentNewChildGroup.remove(newChild); group.insert(newChild, refChild); } return newChild; } pos = -1; } else { if (sorting !== nullGetter) { if (correctSortPos) return newChild; pos = binarySearchPos(childNodes, newChildValue, getSortingValue, sortingDesc, this.lll); refChild = childNodes[pos]; newChild.sortingValue = newChildValue; if (newChild === refChild || isInside && nextSibling === refChild) return newChild; } else { if (refChild && refChild.parentNode !== this) throw EXCEPTION_NODE_NOT_FOUND; if (isInside) { if (nextSibling === refChild) return newChild; if (newChild === refChild) throw EXCEPTION_CANT_INSERT; } } } if (isInside) { if (nextSibling) { nextSibling.previousSibling = prevSibling; newChild.nextSibling = null; } else this.lastChild = prevSibling; if (prevSibling) { prevSibling.nextSibling = nextSibling; newChild.previousSibling = null; } else this.firstChild = nextSibling; if (pos == -1) arrayRemove(childNodes, newChild); else { var oldPos = childNodes.indexOf(newChild); childNodes.splice(oldPos, 1); pos -= oldPos < pos; } if (currentNewChildGroup) { currentNewChildGroup.remove(newChild); currentNewChildGroup = null; } } else { if (newChild.parentNode) newChild.parentNode.removeChild(newChild); } if (currentNewChildGroup != group) group.insert(newChild, refChild); if (refChild) { if (pos == -1) pos = childNodes.indexOf(refChild); if (pos == -1) throw EXCEPTION_NODE_NOT_FOUND; newChild.nextSibling = refChild; childNodes.splice(pos, 0, newChild); } else { pos = childNodes.length; childNodes.push(newChild); refChild = { previousSibling: this.lastChild }; this.lastChild = newChild; } newChild.parentNode = this; newChild.previousSibling = refChild.previousSibling; if (pos == 0) this.firstChild = newChild; else refChild.previousSibling.nextSibling = newChild; refChild.previousSibling = newChild; if (!isInside) { updateNodeContextSelection(newChild, newChild.contextSelection, this.selection || this.contextSelection, true); updateNodeDisableContext(newChild, this.disabled || this.contextDisabled); if ((newChild.underMatch_ || this.matchFunction) && newChild.match) newChild.match(this.matchFunction); if (newChild.autoDelegate == DELEGATE.PARENT || newChild.autoDelegate === DELEGATE.ANY) newChild.setDelegate(this); newChild.emit_parentChanged(null); if (!this.dataSource) this.emit_childNodesModified({ inserted: [newChild] }); if (newChild.listen.parentNode) this.addHandler(newChild.listen.parentNode, newChild); } return newChild; }, removeChild: function (oldChild) { if (!oldChild || oldChild.parentNode !== this) throw EXCEPTION_NODE_NOT_FOUND; if (oldChild instanceof this.childClass == false) throw EXCEPTION_BAD_CHILD_CLASS; if (this.dataSource) { if (!oldChild.delegate || this.dataSourceMap_[oldChild.delegate.basisObjectId]) throw EXCEPTION_DATASOURCE_CONFLICT; } else { if (this.dataSourceRA_) throw EXCEPTION_DATASOURCEADAPTER_CONFLICT; } var pos = this.childNodes.indexOf(oldChild); if (pos == -1) throw EXCEPTION_NODE_NOT_FOUND; this.childNodes.splice(pos, 1); oldChild.parentNode = null; if (oldChild.nextSibling) oldChild.nextSibling.previousSibling = oldChild.previousSibling; else this.lastChild = oldChild.previousSibling; if (oldChild.previousSibling) oldChild.previousSibling.nextSibling = oldChild.nextSibling; else this.firstChild = oldChild.nextSibling; oldChild.nextSibling = null; oldChild.previousSibling = null; if (oldChild.listen.parentNode) this.removeHandler(oldChild.listen.parentNode, oldChild); updateNodeContextSelection(oldChild, oldChild.contextSelection, null, true); if (oldChild.groupNode) oldChild.groupNode.remove(oldChild); oldChild.emit_parentChanged(this); if (!this.dataSource) this.emit_childNodesModified({ deleted: [oldChild] }); if (oldChild.autoDelegate == DELEGATE.PARENT || oldChild.autoDelegate === DELEGATE.ANY) oldChild.setDelegate(); return oldChild; }, replaceChild: function (newChild, oldChild) { if (this.dataSource) throw EXCEPTION_DATASOURCE_CONFLICT; if (this.dataSourceRA_) throw EXCEPTION_DATASOURCEADAPTER_CONFLICT; if (oldChild == null || oldChild.parentNode !== this) throw EXCEPTION_NODE_NOT_FOUND; this.insertBefore(newChild, oldChild); return this.removeChild(oldChild); }, clear: function (alive) { if (this.dataSource && this.dataSourceMap_ && this.dataSource.itemCount) throw EXCEPTION_DATASOURCE_CONFLICT; if (!this.firstChild) return; if (alive) updateNodeContextSelection(this, this.selection || this.contextSelection, null, false, true); var childNodes = this.childNodes; this.firstChild = null; this.lastChild = null; this.childNodes = []; this.emit_childNodesModified({ deleted: childNodes }); for (var i = childNodes.length; i-- > 0;) { var child = childNodes[i]; if (child.listen.parentNode) child.parentNode.removeHandler(child.listen.parentNode, child); child.parentNode = null; child.groupNode = null; if (alive) { child.nextSibling = null; child.previousSibling = null; child.emit_parentChanged(this); if (child.autoDelegate == DELEGATE.PARENT || child.autoDelegate === DELEGATE.ANY) child.setDelegate(); } else child.destroy(); } if (this.grouping) { for (var childNodes = this.grouping.childNodes, i = childNodes.length - 1, group; group = childNodes[i]; i--) group.clear(); } }, setChildNodes: function (newChildNodes, keepAlive) { if (!this.dataSource && !this.dataSourceRA_) this.clear(keepAlive); if (newChildNodes) { if ("length" in newChildNodes == false) newChildNodes = [newChildNodes]; if (newChildNodes.length) { var tmp = this.emit_childNodesModified; this.emit_childNodesModified = $undef; for (var i = 0, len = newChildNodes.length; i < len; i++) this.insertBefore(newChildNodes[i]); this.emit_childNodesModified = tmp; this.emit_childNodesModified({ inserted: this.childNodes }); } } }, setDataSource: function (dataSource) { if (!this.childClass) throw EXCEPTION_NO_CHILDCLASS; dataSource = resolveDataset(this, this.setDataSource, dataSource, "dataSourceRA_"); if (this.dataSource !== dataSource) { var oldDataSource = this.dataSource; var dataSourceMap = this.dataSourceMap_ || {}; var listenHandler = this.listen.dataSource; var inserted; var deleted; if (oldDataSource) { if (listenHandler) oldDataSource.removeHandler(listenHandler, this); if (dataSource) { inserted = dataSource.getItems().filter(function (item) { return !oldDataSource.has(item); }); deleted = oldDataSource.getItems().filter(function (item) { return !dataSource.has(item); }); } else { deleted = oldDataSource.getItems(); } } else { if (dataSource) inserted = dataSource.getItems(); } if (!oldDataSource || !dataSource) { if (this.firstChild) { if (oldDataSource) for (var i = 0, child; child = this.childNodes[i]; i++) unlockDataSourceItemNode(child); this.dataSource = null; this.clear(oldDataSource && !this.destroyDataSourceMember); } } else { if (oldDataSource && deleted.length && listenHandler) listenHandler.itemsChanged.call(this, oldDataSource, { deleted: deleted }); } this.dataSource = dataSource; if (dataSource) { this.dataSourceMap_ = dataSourceMap; this.setChildNodesState(dataSource.state, dataSource.state.data); if (listenHandler) { dataSource.addHandler(listenHandler, this); if (inserted.length) listenHandler.itemsChanged.call(this, dataSource, { inserted: inserted }); } } else { this.dataSourceMap_ = null; this.setChildNodesState(STATE.UNDEFINED); } this.emit_dataSourceChanged(oldDataSource); } }, setGrouping: function (grouping, alive) { if (typeof grouping == "function" || typeof grouping == "string") grouping = { rule: grouping }; if (grouping instanceof GroupingNode == false) { grouping = grouping && typeof grouping == "object" ? new this.groupingClass(grouping) : null; } if (this.grouping !== grouping) { var oldGrouping = this.grouping; var order; if (oldGrouping) { this.grouping = null; if (!grouping) { if (this.firstChild) { if (this.sorting !== nullGetter) order = sortChildNodes(this); else order = this.childNodes; oldGrouping.nullGroup.clear(); var groups = oldGrouping.childNodes.slice(0); for (var i = 0; i < groups.length; i++) groups[i].clear(); fastChildNodesOrder(this, order); } } oldGrouping.setOwner(); } if (grouping) { this.grouping = grouping; grouping.setOwner(this); if (this.firstChild) { if (this.sorting !== nullGetter) order = sortChildNodes(this); else order = this.childNodes; for (var i = 0, child; child = order[i]; i++) child.groupNode = this.grouping.getGroupNode(child, true); order = fastChildNodesGroupOrder(this, order); fastChildNodesOrder(this, order); } } this.emit_groupingChanged(oldGrouping); if (oldGrouping && !alive) oldGrouping.destroy(); } }, setSorting: function (sorting, sortingDesc) { sorting = getter(sorting); sortingDesc = !!sortingDesc; if (this.sorting !== sorting || this.sortingDesc != !!sortingDesc) { var oldSorting = this.sorting; var oldSortingDesc = this.sortingDesc; this.sorting = sorting; this.sortingDesc = !!sortingDesc; if (sorting !== nullGetter && this.firstChild) { var order = []; var nodes; for (var node = this.firstChild; node; node = node.nextSibling) { var newChildValue = sorting(node); if (newChildValue == null) newChildValue = -Infinity; else if (typeof newChildValue != "number" || newChildValue !== newChildValue) newChildValue = String(newChildValue); node.sortingValue = newChildValue; } if (this.grouping) { var groups = [this.grouping.nullGroup].concat(this.grouping.childNodes); for (var i = 0, group; group = groups[i]; i++) { nodes = group.nodes = sortChildNodes({ childNodes: group.nodes, sortingDesc: this.sortingDesc }); group.first = nodes[0] || null; group.last = nodes[nodes.length - 1] || null; order.push.apply(order, nodes); } } else { order = sortChildNodes(this); } fastChildNodesOrder(this, order); } this.emit_sortingChanged(oldSorting, oldSortingDesc); } }, setMatchFunction: function (matchFunction) { if (this.matchFunction != matchFunction) { var oldMatchFunction = this.matchFunction; this.matchFunction = matchFunction; for (var node = this.lastChild; node; node = node.previousSibling) node.match(matchFunction); this.emit_matchFunctionChanged(oldMatchFunction); } } }; var Node = Class(AbstractNode, DomMixin, { className: namespace + ".Node", propertyDescriptors: { disabled: "disable enable", contextDisabled: false, selected: "select unselect", contextSelection: false, selection: "selectionChanged", matched: "match unmatch", matchFunction: "matchFunctionChanged" }, emit_satelliteChanged: function (name, oldSatellite) { AbstractNode.prototype.emit_satelliteChanged.call(this, name, oldSatellite); if (this.satellite[name] instanceof Node) updateNodeDisableContext(this.satellite[name], this.disabled || this.contextDisabled); }, contextDisabled: false, disabled: false, disabledRA_: null, emit_enable: createEvent("enable") && function () { for (var child = this.firstChild; child; child = child.nextSibling) updateNodeDisableContext(child, false); events.enable.call(this); }, emit_disable: createEvent("disable") && function () { for (var child = this.firstChild; child; child = child.nextSibling) updateNodeDisableContext(child, true); events.disable.call(this); }, selection: null, emit_selectionChanged: createEvent("selectionChanged", "oldSelection"), contextSelection: null, selected: false, selectedRA_: null, emit_select: createEvent("select"), emit_unselect: createEvent("unselect"), matched: true, emit_match: createEvent("match"), emit_unmatch: createEvent("unmatch"), matchFunction: null, emit_matchFunctionChanged: createEvent("matchFunctionChanged", "oldMatchFunction"), listen: { owner: { enable: function () { updateNodeDisableContext(this, false); }, disable: function () { updateNodeDisableContext(this, true); } }, selection: { destroy: function () { this.setSelection(); } } }, init: function () { var disabled = this.disabled; this.disabled = false; var selection = this.selection; if (selection) { this.selection = null; this.setSelection(selection, true); } AbstractNode.prototype.init.call(this); if (disabled) { disabled = !!resolveValue(this, this.setDisabled, disabled, "disabledRA_"); if (disabled) { this.disabled = disabled; for (var child = this.firstChild; child; child = child.nextSibling) updateNodeDisableContext(child, true); } } if (this.selected) this.selected = !!resolveValue(this, this.setSelected, this.selected, "selectedRA_"); }, setSelection: function (selection, silent) { var oldSelection = this.selection; if (selection instanceof Selection === false) selection = selection ? new Selection(selection) : null; if (oldSelection !== selection) { updateNodeContextSelection(this, oldSelection || this.contextSelection, selection || this.contextSelection, false, true); if (this.listen.selection) { if (oldSelection) oldSelection.removeHandler(this.listen.selection, this); if (selection) selection.addHandler(this.listen.selection, this); } this.selection = selection; if (!silent) this.emit_selectionChanged(oldSelection); return true; } }, setSelected: function (selected, multiple) { var selection = this.contextSelection; selected = !!resolveValue(this, this.setSelected, selected, "selectedRA_"); if (this.selected && selection) { if (this.selectedRA_) { if (selection.has(this)) { this.selected = false; selection.remove(this); this.selected = true; } } else { if (!selection.has(this)) selection.add(this); } } if (selected !== this.selected) { if (this.selectedRA_) { this.selected = selected; if (selected) this.emit_select(); else this.emit_unselect(); } else { if (selected) { if (selection) { if (multiple) selection.add(this); else selection.set(this); } else { this.selected = true; this.emit_select(); } } else { if (selection) { selection.remove(this); } else { this.selected = false; this.emit_unselect(); } } } return true; } else { if (!this.selectedRA_ && selected && selection) { if (multiple) selection.remove(this); else selection.set(this); } } return false; }, select: function (multiple) { if (this.selectedRA_) { basis.dev.warn("`selected` property is under bb-value and can't be changed by `select()` method. Use `setSelected()` instead."); return false; } return this.setSelected(true, multiple); }, unselect: function () { if (this.selectedRA_) { basis.dev.warn("`selected` property is under bb-value and can't be changed by `unselect()` method. Use `setSelected()` instead."); return false; } return this.setSelected(false); }, setDisabled: function (disabled) { disabled = !!resolveValue(this, this.setDisabled, disabled, "disabledRA_"); if (this.disabled !== disabled) { this.disabled = disabled; if (!this.contextDisabled) if (disabled) this.emit_disable(); else this.emit_enable(); return true; } return false; }, disable: function () { if (this.disabledRA_) { basis.dev.warn("`disabled` property is under bb-value and can't be changed by `disable()` method. Use `setDisabled()` instead."); return false; } return this.setDisabled(true); }, enable: function () { if (this.disabledRA_) { basis.dev.warn("`disabled` property is under bb-value and can't be changed by `enable()` method. Use `setDisabled()` instead."); return false; } return this.setDisabled(false); }, isDisabled: function () { return this.disabled || this.contextDisabled; }, match: function (func) { if (typeof func != "function") func = null; if (this.underMatch_ && !func) this.underMatch_(this, true); this.underMatch_ = func; var matched = !func || func(this); if (this.matched != matched) { this.matched = matched; if (matched) this.emit_match(); else this.emit_unmatch(); } }, destroy: function () { if (this.disabledRA_) resolveValue(this, null, null, "disabledRA_"); if (this.selectedRA_) resolveValue(this, null, null, "selectedRA_"); this.contextSelection = null; if (this.selection) this.setSelection(); AbstractNode.prototype.destroy.call(this); } }); var GroupingNode = Class(AbstractNode, DomMixin, { className: namespace + ".GroupingNode", emit_childNodesModified: function (delta) { events.childNodesModified.call(this, delta); var array; if (array = delta.inserted) { for (var i = 0, child; child = array[i++];) { child.groupId_ = child.delegate ? child.delegate.basisObjectId : child.data.id; this.map_[child.groupId_] = child; } if (this.dataSource && this.nullGroup.first) { var parentNode = this.owner; var nodes = arrayFrom(this.nullGroup.nodes); for (var i = nodes.length; i-- > 0;) parentNode.insertBefore(nodes[i], nodes[i].nextSibling); } } }, emit_ownerChanged: function (oldOwner) { if (oldOwner && oldOwner.grouping === this) oldOwner.setGrouping(null, true); if (this.owner && this.owner.grouping !== this) this.owner.setGrouping(this); events.ownerChanged.call(this, oldOwner); if (!this.owner && this.autoDestroyWithNoOwner) this.destroy(); }, map_: null, nullGroup: null, autoDestroyWithNoOwner: true, autoDestroyEmptyGroups: true, rule: nullGetter, childClass: PartitionNode, childFactory: function (config) { return new this.childClass(complete({ autoDestroyIfEmpty: this.dataSource ? false : this.autoDestroyEmptyGroups }, config)); }, init: function () { this.map_ = {}; this.nullGroup = new PartitionNode(); AbstractNode.prototype.init.call(this); }, getGroupNode: function (node, autocreate) { var groupRef = this.rule(node); var isDelegate = groupRef instanceof DataObject; var group = this.map_[isDelegate ? groupRef.basisObjectId : groupRef]; if (this.dataSource) autocreate = false; if (!group && autocreate) { group = this.appendChild(isDelegate ? groupRef : { data: { id: groupRef, title: groupRef } }); } return group || this.nullGroup; }, setDataSource: function (dataSource) { var curDataSource = this.dataSource; DomMixin.setDataSource.call(this, dataSource); var owner = this.owner; if (owner && this.dataSource !== curDataSource) { var nodes = arrayFrom(owner.childNodes); for (var i = nodes.length - 1; i >= 0; i--) owner.insertBefore(nodes[i], nodes[i + 1]); } }, insertBefore: function (newChild, refChild) { newChild = DomMixin.insertBefore.call(this, newChild, refChild); var firstNode = newChild.first; if (firstNode) { var parent = firstNode.parentNode; var lastNode = newChild.last; var beforePrev; var beforeNext; var afterPrev; var afterNext = null; var cursor = newChild; while (cursor = cursor.nextSibling) { if (afterNext = cursor.first) break; } afterPrev = afterNext ? afterNext.previousSibling : parent.lastChild; beforePrev = firstNode.previousSibling; beforeNext = lastNode.nextSibling; if (beforeNext !== afterNext) { var parentChildNodes = parent.childNodes; var nodes = newChild.nodes; var nodesCount = nodes.length; if (beforePrev) beforePrev.nextSibling = beforeNext; if (beforeNext) beforeNext.previousSibling = beforePrev; if (afterPrev) afterPrev.nextSibling = firstNode; if (afterNext) afterNext.previousSibling = lastNode; firstNode.previousSibling = afterPrev; lastNode.nextSibling = afterNext; var firstPos = parentChildNodes.indexOf(firstNode); var afterNextPos = afterNext ? parentChildNodes.indexOf(afterNext) : parentChildNodes.length; if (afterNextPos > firstPos) afterNextPos -= nodesCount; parentChildNodes.splice(firstPos, nodesCount); parentChildNodes.splice.apply(parentChildNodes, [ afterNextPos, 0 ].concat(nodes)); if (!afterPrev || !beforePrev) parent.firstChild = parentChildNodes[0]; if (!afterNext || !beforeNext) parent.lastChild = parentChildNodes[parentChildNodes.length - 1]; if (firstNode instanceof PartitionNode) for (var i = nodesCount, insertBefore = afterNext; i-- > 0;) { parent.insertBefore(nodes[i], insertBefore); insertBefore = nodes[i]; } } } return newChild; }, removeChild: function (oldChild) { if (oldChild = DomMixin.removeChild.call(this, oldChild)) { delete this.map_[oldChild.groupId_]; for (var i = 0, node; node = oldChild.nodes[i]; i++) node.parentNode.insertBefore(node); } return oldChild; }, clear: function (alive) { var nodes = []; var getGroupNode = this.getGroupNode; var nullGroup = this.nullGroup; this.getGroupNode = function () { return nullGroup; }; for (var group = this.firstChild; group; group = group.nextSibling) nodes.push.apply(nodes, group.nodes); for (var i = 0, child; child = nodes[i]; i++) child.parentNode.insertBefore(child); this.getGroupNode = getGroupNode; DomMixin.clear.call(this, alive); this.map_ = {}; }, destroy: function () { this.autoDestroyWithNoOwner = false; AbstractNode.prototype.destroy.call(this); this.nullGroup.destroy(); this.nullGroup = null; this.map_ = null; } }); AbstractNode.prototype.groupingClass = GroupingNode; var CHILDNODESDATASET_HANDLER = { childNodesModified: function (sender, delta) { var memberMap = this.members_; var newDelta = {}; var node; var insertCount = 0; var deleteCount = 0; var inserted = delta.inserted; var deleted = delta.deleted; if (inserted && inserted.length) { newDelta.inserted = inserted; while (node = inserted[insertCount]) { memberMap[node.basisObjectId] = node; insertCount++; } } if (deleted && deleted.length) { newDelta.deleted = deleted; while (node = deleted[deleteCount]) { delete memberMap[node.basisObjectId]; deleteCount++; } } if (insertCount || deleteCount) this.emit_itemsChanged(newDelta); }, destroy: function () { this.destroy(); } }; var SATELLITEDATASET_HANDLER = { satelliteChanged: function (sender, name, oldSatellite) { var delta = {}; if (sender.satellite[name]) { delta.inserted = [sender.satellite[name]]; } if (oldSatellite) { delta.deleted = [oldSatellite]; } this.emit_itemsChanged(delta); }, destroy: function () { this.destroy(); } }; var ChildNodesDataset = Class(ReadOnlyDataset, { className: namespace + ".ChildNodesDataset", sourceNode: null, init: function () { ReadOnlyDataset.prototype.init.call(this); var sourceNode = this.sourceNode; childNodesDatasetMap[sourceNode.basisObjectId] = this; if (sourceNode.firstChild) CHILDNODESDATASET_HANDLER.childNodesModified.call(this, sourceNode, { inserted: sourceNode.childNodes }); sourceNode.addHandler(CHILDNODESDATASET_HANDLER, this); }, destroy: function () { this.sourceNode.removeHandler(CHILDNODESDATASET_HANDLER, this); delete childNodesDatasetMap[this.sourceNode.basisObjectId]; ReadOnlyDataset.prototype.destroy.call(this); } }); var SatellitesDataset = basis.Class(ReadOnlyDataset, { className: ".SatellitesDataset", sourceNode: null, init: function () { ReadOnlyDataset.prototype.init.call(this); var sourceNode = this.sourceNode; satellitesDatasetMap[sourceNode.basisObjectId] = this; var satellites = []; for (var satelliteName in sourceNode.satellite) if (sourceNode.satellite.hasOwnProperty(satelliteName)) { var node = sourceNode.satellite[satelliteName]; if (node instanceof AbstractNode) satellites.push(node); } if (satellites.length) this.emit_itemsChanged({ inserted: satellites }); sourceNode.addHandler(SATELLITEDATASET_HANDLER, this); }, destroy: function () { this.sourceNode.removeHandler(SATELLITEDATASET_HANDLER, this); delete satellitesDatasetMap[this.sourceNode.basisObjectId]; ReadOnlyDataset.prototype.destroy.call(this); } }); var Selection = Class(Dataset, { className: namespace + ".Selection", multiple: false, emit_itemsChanged: function (delta) { var array; Dataset.prototype.emit_itemsChanged.call(this, delta); if (array = delta.deleted) for (var i = 0, node; node = array[i]; i++) { if (node.selected && node.contextSelection === this) { node.selected = false; node.emit_unselect(); } } if (array = delta.inserted) for (var i = 0, node; node = array[i]; i++) { if (!node.selected && node.contextSelection === this) { node.selected = true; node.emit_select(); } } }, add: function (nodes) { if (!nodes) return; if (!this.multiple && this.itemCount) return this.set(nodes); if (!Array.isArray(nodes)) nodes = [nodes]; nodes = nodes.filter(this.filter, this); if (!this.multiple && nodes.length > 1) { basis.dev.warn(namespace + ".Selection#add() can't accept more than one node as not in multiple mode"); nodes = [nodes[0]]; } if (nodes.length) return Dataset.prototype.add.call(this, nodes); }, set: function (nodes) { if (!nodes) return this.clear(); if (!Array.isArray(nodes)) nodes = [nodes]; nodes = nodes.filter(this.filter, this); if (!this.multiple && nodes.length > 1) { basis.dev.warn(namespace + ".Selection#set() can't accept more than one node as not in multiple mode"); nodes = [nodes[0]]; } if (nodes.length) return Dataset.prototype.set.call(this, nodes); else return this.clear(); }, filter: function (node) { return node instanceof Node && !node.selectedRA_ && node.contextSelection === this; } }); module.exports = { DELEGATE: DELEGATE, AbstractNode: AbstractNode, Node: Node, GroupingNode: GroupingNode, PartitionNode: PartitionNode, ChildNodesDataset: ChildNodesDataset, SatellitesDataset: SatellitesDataset, Selection: Selection, nullSelection: new ReadOnlyDataset() }; }, "g.js": function (exports, module, basis, global, __filename, __dirname, require, resource, asset) { var namespace = "basis.data"; var Class = basis.Class; var sliceArray = Array.prototype.slice; var values = basis.object.values; var $self = basis.fn.$self; var STATE = basis.require("./h.js"); var SUBSCRIPTION = basis.require("./i.js"); var resolvers = basis.require("./j.js"); var createResolveFunction = resolvers.createResolveFunction; var resolveValue = resolvers.resolveValue; var ResolveAdapter = resolvers.ResolveAdapter; var BBResolveAdapter = resolvers.BBResolveAdapter; var DEFAULT_CHANGE_ADAPTER_HANDLER = resolvers.DEFAULT_CHANGE_ADAPTER_HANDLER; var DEFAULT_DESTROY_ADAPTER_HANDLER = resolvers.DEFAULT_DESTROY_ADAPTER_HANDLER; var basisEvent = basis.require("./3.js"); var Emitter = basisEvent.Emitter; var createEvent = basisEvent.create; var createEventHandler = basisEvent.createHandler; var events = basisEvent.events; var AbstractData = basis.require("./1i.js"); var NULL_OBJECT = {}; var EMPTY_ARRAY = []; var FACTORY = basis.FACTORY; var PROXY = basis.PROXY; SUBSCRIPTION.addProperty("delegate"); SUBSCRIPTION.addProperty("target"); SUBSCRIPTION.addProperty("dataset"); SUBSCRIPTION.addProperty("value", "change"); var isEqual = function (a, b) { return a === b; }; var PROXY_SUPPORT = typeof Proxy == "function" && typeof WeakMap == "function"; var devWrap = function (value) { return value; }; var devUnwrap = function (value) { return value; }; if (PROXY_SUPPORT) { var devWrapMap = new WeakMap(); var devWrap = function (value) { value = devWrapMap.has(value) ? devWrapMap.get(value) : value; var result = new Proxy(value, {}); devWrapMap.set(result, value); return result; }; devUnwrap = function (value) { return value && devWrapMap.has(value) ? devWrapMap.get(value) : value; }; isEqual = function (a, b) { return devUnwrap(a) === devUnwrap(b); }; } var GETTER_ID = basis.getter.ID; var VALUE_EMMITER_HANDLER = { destroy: function (object) { this.value.unlink(object, this.fn); } }; var VALUE_EMMITER_DESTROY_HANDLER = { destroy: function () { this.set(null); } }; var computeFunctions = {}; var valueSetters = {}; var valueSyncAs = function (value) { Value.prototype.set.call(this, value); }; var valueSyncPipe = function (newValue, oldValue) { if (oldValue instanceof Emitter) oldValue.removeHandler(this.pipeHandler, this); else oldValue = null; if (newValue instanceof Emitter) newValue.addHandler(this.pipeHandler, this); else newValue = null; if (newValue !== oldValue) Value.prototype.set.call(this, newValue); }; var Value = Class(AbstractData, { className: namespace + ".Value", propertyDescriptors: { value: "change", bindingBridge: false, initValue: false, locked: false, proxy: false, setNullOnEmitterDestroy: false }, subscribeTo: SUBSCRIPTION.VALUE, emit_change: createEvent("change", "oldValue") && function (oldValue) { events.change.call(this, oldValue); var cursor = this; while (cursor = cursor.links_) cursor.fn.call(cursor.context, this.value, oldValue); }, value: null, initValue: null, proxy: null, locked: 0, lockedValue_: null, links_: null, deferred_: null, pipes_: null, setNullOnEmitterDestroy: true, bindingBridge: { attach: function (host, callback, context, onDestroy) { host.link(context, callback, true, onDestroy); }, detach: function (host, callback, context) { host.unlink(context, callback); }, get: function (host) { return host.value; } }, init: function () { AbstractData.prototype.init.call(this); if (this.proxy) this.value = this.proxy(this.value); if (this.setNullOnEmitterDestroy && this.value instanceof Emitter) this.value.addHandler(VALUE_EMMITER_DESTROY_HANDLER, this); this.initValue = this.value; }, set: function (value) { var oldValue = this.value; var newValue = this.proxy ? this.proxy(value) : value; var changed = newValue !== oldValue; if (changed) { if (this.setNullOnEmitterDestroy) { if (oldValue instanceof Emitter) oldValue.removeHandler(VALUE_EMMITER_DESTROY_HANDLER, this); if (newValue instanceof Emitter) newValue.addHandler(VALUE_EMMITER_DESTROY_HANDLER, this); } this.value = newValue; if (!this.locked) this.emit_change(oldValue); } return changed; }, reset: function () { this.set(this.initValue); }, isLocked: function () { return this.locked > 0; }, lock: function () { this.locked++; if (this.locked == 1) this.lockedValue_ = this.value; }, unlock: function () { if (this.locked) { this.locked--; if (!this.locked) { var lockedValue = this.lockedValue_; this.lockedValue_ = null; if (this.value !== lockedValue) this.emit_change(lockedValue); } } }, compute: function (events, fn) { if (!fn) { fn = events; events = null; } if (!fn) fn = $self; var hostValue = this; var handler = createEventHandler(events, function (object) { Value.prototype.set.call(this, fn(object, hostValue.value)); }); var fnId = fn[GETTER_ID] || String(fn); var getComputeValueId = handler.events.concat(fnId, this.basisObjectId).join("_"); var getComputeValue = computeFunctions[getComputeValueId]; if (!getComputeValue) { var computeMap = {}; handler.destroy = function (object) { delete computeMap[object.basisObjectId]; this.destroy(); }; this.addHandler({ change: function () { for (var key in computeMap) { var pair = computeMap[key]; Value.prototype.set.call(pair.value, fn(pair.object, this.value)); } }, destroy: function () { for (var key in computeMap) { var pair = computeMap[key]; pair.object.removeHandler(handler, pair.value); pair.value.destroy(); } computeMap = null; hostValue = null; } }); getComputeValue = computeFunctions[getComputeValueId] = function (object) { if (object instanceof Emitter == false) basis.dev.warn("basis.data.Value#compute: object should be an instanceof basis.event.Emitter"); var objectId = object.basisObjectId; var pair = computeMap[objectId]; var value = fn(object, hostValue.value); if (!pair) { var computeValue = new ReadOnlyValue({ value: value }); basis.dev.setInfo(computeValue, "sourceInfo", { type: "Value#compute", source: [ object, hostValue ], events: events, transform: fn }); object.addHandler(handler, computeValue); pair = computeMap[objectId] = { value: computeValue, object: object }; } else { Value.prototype.set.call(pair.value, value); } return pair.value; }; } return chainValueFactory(getComputeValue); }, pipe: function (events, getter) { var pipeHandler = createEventHandler(events, valueFromSetProxy); var getterId = getter[GETTER_ID] || String(getter); var id = pipeHandler.events.join("_") + "_" + getterId; var pipes = this.pipes_; var pipeValue; if (!pipes) pipes = this.pipes_ = {}; else pipeValue = pipes[id]; if (!pipeValue) { pipeValue = new PipeValue({ source: this, pipeId: id, pipeHandler: pipeHandler }); pipeValue.proxy = basis.getter(getter); if (this.value instanceof Emitter) { pipeValue.value = pipeValue.proxy(this.value); this.value.addHandler(pipeHandler, pipeValue); } pipes[id] = pipeValue; this.link(pipeValue, valueSyncPipe, true, pipeValue.destroy); basis.dev.setInfo(pipeValue, "sourceInfo", { type: "Value#pipe", source: this, events: events, transform: pipeValue.proxy }); } else pipeValue = devWrap(pipeValue); return pipeValue; }, as: function (fn) { if (arguments.length > 1) basis.dev.warn("basis.data.Value#as() doesn't accept deferred flag as second parameter anymore. Use value.as(fn).deferred() instead."); if (!fn || fn === $self) return this; if (typeof fn == "string") fn = basis.getter(fn); if (this.links_) { var cursor = this; var fnId = fn[GETTER_ID] || String(fn); while (cursor = cursor.links_) { var context = cursor.context; if (context instanceof ReadOnlyValue && context.proxy && (context.proxy[GETTER_ID] || String(context.proxy)) == fnId) { context = devWrap(context); return context; } } } var result = new ReadOnlyValue({ proxy: fn, value: this.value }); basis.dev.setInfo(result, "sourceInfo", { type: "Value#as", source: this, sourceTarget: this.value, transform: fn }); if (fn.retarget) { result.proxy = function (value) { value = fn(value); basis.dev.patchInfo(result, "sourceInfo", { sourceTarget: value }); return value; }; result.proxy[GETTER_ID] = fn[GETTER_ID]; } this.link(result, valueSyncAs, true, result.destroy); return result; }, query: function (path) { return Value.query(this, "value." + path); }, deferred: function () { if (arguments.length > 0) basis.dev.warn("basis.data.Value#deferred() doesn't accept parameters anymore. Use value.as(fn).deferred() instead."); if (!this.deferred_) { this.deferred_ = new DeferredValue({ source: this, value: this.value }); basis.dev.setInfo(this.deferred_, "sourceInfo", { type: "Value#deferred", source: this }); } return this.deferred_; }, link: function (context, fn, noApply, onDestroy) { if (typeof fn != "function") { var property = String(fn); fn = valueSetters[property]; if (!fn) fn = valueSetters[property] = function (value) { this[property] = value; }; } var cursor = this; while (cursor = cursor.links_) if (cursor.context === context && cursor.fn === fn) { basis.dev.warn(this.constructor.className + "#link: Duplicate link pair context-fn"); break; } this.links_ = { value: this, context: context, fn: fn, destroy: onDestroy || null, links_: this.links_ }; if (context instanceof Emitter) context.addHandler(VALUE_EMMITER_HANDLER, this.links_); if (!noApply) fn.call(context, this.value); return context; }, unlink: function (context, fn) { var cursor = this; var prev; while (prev = cursor, cursor = cursor.links_) if (cursor.context === context && (!fn || cursor.fn === fn)) { cursor.fn = basis.fn.$undef; prev.links_ = cursor.links_; if (cursor.context instanceof Emitter) cursor.context.removeHandler(VALUE_EMMITER_HANDLER, cursor); } }, destroy: function () { AbstractData.prototype.destroy.call(this); if (this.setNullOnEmitterDestroy && this.value instanceof Emitter) this.value.removeHandler(VALUE_EMMITER_DESTROY_HANDLER, this); var cursor = this.links_; this.links_ = null; while (cursor) { if (cursor.context instanceof Emitter) cursor.context.removeHandler(VALUE_EMMITER_HANDLER, cursor); if (cursor.destroy) cursor.destroy.call(cursor.context); cursor = cursor.links_; } this.proxy = null; this.initValue = null; this.value = null; this.lockedValue_ = null; this.deferred_ = null; this.pipes_ = null; } }); var ReadOnlyValue = Class(Value, { className: namespace + ".ReadOnlyValue", setNullOnEmitterDestroy: false, set: basis.fn.$false }); var deferredSchedule = basis.asap.schedule(function (value) { value.unlock(); }); var DEFERRED_HANDLER = { change: function (source) { if (!this.isLocked()) { this.lock(); deferredSchedule.add(this); } Value.prototype.set.call(this, source.value); }, destroy: function () { this.destroy(); } }; var DeferredValue = Class(ReadOnlyValue, { className: namespace + ".DeferredValue", source: null, init: function () { ReadOnlyValue.prototype.init.call(this); this.source.addHandler(DEFERRED_HANDLER, this); }, deferred: function () { return this; }, destroy: function () { deferredSchedule.remove(this); this.source = null; ReadOnlyValue.prototype.destroy.call(this); } }); var PipeValue = Class(ReadOnlyValue, { className: namespace + ".PipeValue", source: null, pipeId: null, pipeHandler: null, destroy: function () { var source = this.source; var sourceValue = source.value; if (sourceValue instanceof Emitter) sourceValue.removeHandler(this.pipeHandler, this); source.pipes_[this.pipeId] = null; this.source = null; this.pipeHandler = null; ReadOnlyValue.prototype.destroy.call(this); } }); var valueFromMap = {}; var valueFromSetProxy = function (sender) { Value.prototype.set.call(this, sender); }; Value.from = function (obj, events, getter) { var result; if (!obj) return null; if (obj instanceof Emitter) { if (!getter) { getter = events; events = null; } if (!getter) getter = $self; var handler = createEventHandler(events, valueFromSetProxy); var getterId = getter[GETTER_ID] || String(getter); var id = handler.events.concat(getterId, obj.basisObjectId).join("_"); result = valueFromMap[id]; if (!result) { result = valueFromMap[id] = new ReadOnlyValue({ proxy: basis.getter(getter), value: obj, emit_destroy: function () { if (id in valueFromMap) { delete valueFromMap[id]; obj.removeHandler(handler, this); } ReadOnlyValue.prototype.emit_destroy.call(this); } }); basis.dev.setInfo(result, "sourceInfo", { type: "Value.from", source: obj, events: events, transform: result.proxy }); handler.destroy = function () { if (id in valueFromMap) { delete valueFromMap[id]; this.destroy(); } }; obj.addHandler(handler, result); } else result = devWrap(result); } if (!result) { var id = obj.basisObjectId; var bindingBridge = obj.bindingBridge; if (id && bindingBridge) { result = valueFromMap[id]; if (!result) { result = valueFromMap[id] = new ReadOnlyValue({ value: bindingBridge.get(obj), handler: { destroy: function () { valueFromMap[id] = null; bindingBridge.detach(obj, Value.prototype.set, result); } } }); bindingBridge.attach(obj, Value.prototype.set, result, result.destroy); } else result = devWrap(result); } } if (!result) throw new Error("Bad object type"); return result; }; var UNDEFINED_VALUE = new ReadOnlyValue({ value: undefined }); var queryAsFunctionCache = {}; var queryNestedFunctionCache = {}; function getQueryPathFragment(target, path, index) { var pathFragment = path[index]; var isStatic = false; if (/^<static>/.test(pathFragment)) { isStatic = true; pathFragment = pathFragment.substr(8); } var descriptor = target.propertyDescriptors[pathFragment]; var events = descriptor ? descriptor.events : null; if (descriptor && descriptor.isPrivate) { isStatic = true; events = null; var warnMessage = "Property can't be accessed via query: "; basis.dev.warn(warnMessage + path.join(".") + "\n" + basis.string.repeat(" ", warnMessage.length + path.slice(0, index).join(".").length) + basis.string.repeat("^", pathFragment.length)); } if (descriptor && descriptor.isStatic) isStatic = true; if (events) { if (isStatic) { events = null; var warnMessage = "<static> was applied for property that has events: "; basis.dev.warn(warnMessage + path.join(".") + "\n" + basis.string.repeat(" ", warnMessage.length + path.slice(0, index).join(".").length) + basis.string.repeat("^", "<static>".length) + "\n" + "Propably is't a bug and <static> should be removed from path"); } else { if (descriptor && descriptor.nested && index < path.length - 1) { var path0 = pathFragment; var path1 = path[++index]; var fullPath = path0 + "." + path1; if (Array.isArray(descriptor.nested) && descriptor.nested.indexOf(path1) == -1) { var warnMessage = "Property can't to be observable: "; basis.dev.warn(warnMessage + path.join(".") + "\n" + basis.string.repeat(" ", warnMessage.length + path.slice(0, index).join(".").length + 1) + basis.string.repeat("^", path1.length) + "\n" + "Owner has a limited set of observable properties: " + descriptor.nested.join(", ")); return; } pathFragment = queryNestedFunctionCache[fullPath]; if (!pathFragment) { pathFragment = function (object) { object = object && object[path0]; return object ? object[path1] : undefined; }; pathFragment.getDevSource = function () { return basis.getter(fullPath); }; pathFragment = queryNestedFunctionCache[fullPath] = basis.getter(pathFragment); } } } } else { if (!isStatic) { var warnMessage = "No events found for property: "; basis.dev.warn(warnMessage + path.join(".") + "\n" + basis.string.repeat(" ", warnMessage.length + path.slice(0, index).join(".").length) + basis.string.repeat("^", pathFragment.length) + "\n" + "If a property never changes use `<static>` before property name, i.e. " + path.slice(0, index).join(".") + (index ? "." : "") + "<static>" + path.slice(index).join(".")); return; } } return { getter: pathFragment, rest: path.slice(index + 1).join("."), events: events || null }; } function getQueryPathFunction(path) { var result = queryAsFunctionCache[path]; if (!result) { var fn = function (target) { if (target instanceof Emitter) return Value.query(target, path); }; fn.getDevSource = Function("return function(target){\n" + " if (target instanceof Emitter)\n" + " return Value.query(target, \"" + path + "\");\n" + "};"); basis.dev.setInfo(fn, "loc", null); result = queryAsFunctionCache[path] = basis.getter(fn); result.retarget = true; } return result; } Value.query = function (target, path) { if (arguments.length == 1) { path = target; return chainValueFactory(function (target) { return Value.query(target, path); }); } if (target instanceof Emitter == false) throw new Error("Bad target type"); if (typeof path != "string") throw new Error("Path should be a string"); var pathFragment = getQueryPathFragment(target, path.split("."), 0); var result; if (!pathFragment) return UNDEFINED_VALUE; result = Value.from(target, pathFragment.events, pathFragment.getter); if (pathFragment.rest) result = result.as(getQueryPathFunction(pathFragment.rest)).pipe("change", "value"); return result; }; function chainValueFactory(fn) { fn = basis.dev.patchFactory(fn); fn.factory = FACTORY; fn.deferred = valueDeferredFactory; fn.compute = valueComputeFactory; fn.query = valueQueryFactory; fn.pipe = valuePipeFactory; fn.as = valueAsFactory; return fn; } function valueDeferredFactory() { var factory = this; return chainValueFactory(function (value) { value = factory(value); return value ? value.deferred() : value; }); } function valueComputeFactory(events, getter) { var factory = this; return chainValueFactory(function (sourceValue) { var value = factory(sourceValue); return value ? value.compute(events, getter)(sourceValue) : value; }); } function valueAsFactory(getter) { var factory = this; return chainValueFactory(function (value) { value = factory(value); return value ? value.as(getter) : value; }); } function valuePipeFactory(events, getter) { var factory = this; return chainValueFactory(function (value) { value = factory(value); return value ? value.pipe(events, getter) : value; }); } function valueQueryFactory(path) { var factory = this; return chainValueFactory(function (value) { value = factory(value); return value ? value.query(path) : value; }); } Value.factory = function (events, getter) { return chainValueFactory(function factory(object) { return Value.from(object, events, getter); }); }; Value.state = function (source) { return source instanceof AbstractData ? Value.from(source, "stateChanged", "state") : STATE.UNDEFINED; }; Value.stateFactory = function (events, getter) { return Value.factory(events, getter).pipe("stateChanged", "state").as(function (state) { return state || STATE.UNDEFINED; }); }; var INIT_DATA = {}; function isConnected(a, b) { while (b && b !== a && b !== b.delegate) b = b.delegate; return b === a; } function applyDelegateChanges(object, oldRoot, oldTarget) { var delegate = object.delegate; if (delegate) { object.root = delegate.root; object.target = delegate.target; object.data = delegate.data; object.state = delegate.state; } if (!isEqual(object.root, oldRoot)) { var rootListenHandler = object.listen.root; if (rootListenHandler) { if (oldRoot && !isEqual(oldRoot, object)) oldRoot.removeHandler(rootListenHandler, object); if (object.root && !isEqual(object.root, object)) object.root.addHandler(rootListenHandler, object); } object.emit_rootChanged(oldRoot); } if (!isEqual(object.target, oldTarget)) { var targetListenHandler = object.listen.target; if (targetListenHandler) { if (oldTarget && !isEqual(oldTarget, object)) oldTarget.removeHandler(targetListenHandler, object); if (object.target && !isEqual(object.target, object)) object.target.addHandler(targetListenHandler, object); } object.emit_targetChanged(oldTarget); } var cursor = object.delegates_; while (cursor) { if (cursor.delegate) applyDelegateChanges(cursor.delegate, oldRoot, oldTarget); cursor = cursor.next; } } var DataObject = Class(AbstractData, { className: namespace + ".Object", propertyDescriptors: { delegate: "delegateChanged", target: "targetChanged", root: "rootChanged", data: { nested: true, events: "update" } }, subscribeTo: SUBSCRIPTION.DELEGATE + SUBSCRIPTION.TARGET, data: null, emit_update: createEvent("update", "delta") && function (delta) { var cursor = this.delegates_; events.update.call(this, delta); while (cursor) { if (cursor.delegate) cursor.delegate.emit_update(delta); cursor = cursor.next; } }, emit_stateChanged: function (oldState) { var cursor = this.delegates_; AbstractData.prototype.emit_stateChanged.call(this, oldState); while (cursor) { if (cursor.delegate) { cursor.delegate.state = this.state; cursor.delegate.emit_stateChanged(oldState); } cursor = cursor.next; } }, delegate: null, delegateRA_: null, delegates_: null, debug_delegates: function () { var cursor = this.delegates_; var result = []; while (cursor) { result.push(cursor.delegate); cursor = cursor.next; } return result; }, emit_delegateChanged: createEvent("delegateChanged", "oldDelegate"), target: null, emit_targetChanged: createEvent("targetChanged", "oldTarget"), root: null, emit_rootChanged: createEvent("rootChanged", "oldRoot"), init: function () { this.root = this; AbstractData.prototype.init.call(this); var delegate = this.delegate; var data = this.data; if (delegate) { this.delegate = null; this.target = null; this.data = INIT_DATA; this.setDelegate(delegate); if (this.data === INIT_DATA) this.data = data || {}; } else { if (!data) this.data = {}; if (this.target !== null) this.target = this; } }, setSyncAction: function (syncAction) { if (syncAction && this.delegate) basis.dev.warn(this.constructor.syncAction + " instance has a delegate and syncAction - it may produce conflics with data & state"); AbstractData.prototype.setSyncAction.call(this, syncAction); }, setDelegate: function (newDelegate) { newDelegate = resolveObject(this, this.setDelegate, newDelegate, "delegateRA_"); if (newDelegate && newDelegate instanceof DataObject) { if (newDelegate.delegate && isConnected(this, newDelegate)) { basis.dev.warn("New delegate has already connected to object. Delegate assignment has been ignored.", this, newDelegate); return false; } } else { newDelegate = null; } if (!isEqual(this.delegate, newDelegate)) { var oldState = this.state; var oldData = this.data; var oldDelegate = this.delegate; var oldTarget = this.target; var oldRoot = this.root; var delegateListenHandler = this.listen.delegate; var dataChanged = false; var delta; if (oldDelegate) { if (delegateListenHandler) oldDelegate.removeHandler(delegateListenHandler, this); var cursor = oldDelegate.delegates_; var prev = oldDelegate; while (cursor) { if (isEqual(cursor.delegate, this)) { cursor.delegate = null; if (isEqual(prev, oldDelegate)) oldDelegate.delegates_ = cursor.next; else prev.next = cursor.next; break; } prev = cursor; cursor = cursor.next; } } if (newDelegate) { this.delegate = newDelegate; if (delegateListenHandler) newDelegate.addHandler(delegateListenHandler, this); newDelegate.delegates_ = { delegate: this, next: newDelegate.delegates_ }; if (this.data !== INIT_DATA) { delta = {}; for (var key in newDelegate.data) if (key in oldData === false) { dataChanged = true; delta[key] = undefined; } for (var key in oldData) if (oldData[key] !== newDelegate.data[key]) { dataChanged = true; delta[key] = oldData[key]; } } } else { this.delegate = null; this.target = null; this.root = this; this.data = {}; for (var key in oldData) this.data[key] = oldData[key]; } applyDelegateChanges(this, oldRoot, oldTarget); if (dataChanged) this.emit_update(delta); if (delta && oldState !== this.state && (String(oldState) != this.state || oldState.data !== this.state.data)) this.emit_stateChanged(oldState); this.emit_delegateChanged(oldDelegate); return true; } return false; }, setState: function (state, data) { if (this.delegate) return this.root.setState(state, data); else return AbstractData.prototype.setState.call(this, state, data); }, update: function (data) { if (this.delegate) return this.root.update(data); if (data) { var delta = {}; var changed = false; for (var prop in data) if (this.data[prop] !== data[prop]) { changed = true; delta[prop] = this.data[prop]; this.data[prop] = data[prop]; } if (changed) { this.emit_update(delta); return delta; } } return false; }, destroy: function () { AbstractData.prototype.destroy.call(this); var cursor = this.delegates_; this.delegates_ = null; while (cursor) { cursor.delegate.setDelegate(); cursor = cursor.next; } if (this.delegate) this.setDelegate(); if (this.delegateRA_) resolveObject(this, false, false, "delegateRA_"); this.data = NULL_OBJECT; this.root = null; this.target = null; } }); var resolveObject = createResolveFunction(DataObject); var Slot = Class(DataObject, { className: namespace + ".Slot" }); var KEYOBJECTMAP_MEMBER_HANDLER = { destroy: function () { delete this.map[this.id]; } }; var KeyObjectMap = Class(AbstractData, { className: namespace + ".KeyObjectMap", itemClass: DataObject, keyGetter: basis.getter($self), autoDestroyMembers: true, map_: null, extendConstructor_: true, init: function () { this.map_ = {}; AbstractData.prototype.init.call(this); }, resolve: function (object) { return this.get(this.keyGetter(object), object); }, create: function (key) { var itemConfig; if (key instanceof DataObject) itemConfig = { delegate: key }; else itemConfig = { data: { id: key, title: key } }; return new this.itemClass(itemConfig); }, get: function (key, autocreate) { var itemId = key instanceof DataObject ? key.basisObjectId : key; var itemInfo = this.map_[itemId]; if (!itemInfo && autocreate) { itemInfo = this.map_[itemId] = { map: this.map_, id: itemId, item: this.create(key, autocreate) }; itemInfo.item.addHandler(KEYOBJECTMAP_MEMBER_HANDLER, itemInfo); } if (itemInfo) return itemInfo.item; }, destroy: function () { AbstractData.prototype.destroy.call(this); var map = this.map_; this.map_ = null; for (var itemId in map) { var itemInfo = map[itemId]; if (this.autoDestroyMembers) itemInfo.item.destroy(); else itemInfo.item.removeHandler(KEYOBJECTMAP_MEMBER_HANDLER, itemInfo); } } }); function getDelta(inserted, deleted) { var delta = {}; var result; if (inserted && inserted.length) result = delta.inserted = inserted; if (deleted && deleted.length) result = delta.deleted = deleted; if (result) return delta; } function getDatasetDelta(a, b) { if (!a || !a.itemCount) { if (b && b.itemCount) return { inserted: b.getItems() }; } else { if (!b || !b.itemCount) { if (a.itemCount) return { deleted: a.getItems() }; } else { var inserted = []; var deleted = []; for (var key in a.items_) { var item = a.items_[key]; if (item.basisObjectId in b.items_ == false) deleted.push(item); } for (var key in b.items_) { var item = b.items_[key]; if (item.basisObjectId in a.items_ == false) inserted.push(item); } return getDelta(inserted, deleted); } } } var DatasetWrapper = Class(DataObject, { className: namespace + ".DatasetWrapper", propertyDescriptors: { dataset: "datasetChanged", itemCount: "itemsChanged", "pick()": "itemsChanged", "getItems()": "itemsChanged" }, active: PROXY, subscribeTo: DataObject.prototype.subscribeTo + SUBSCRIPTION.DATASET, listen: { dataset: { itemsChanged: function (dataset, delta) { this.itemCount = dataset.itemCount; this.emit_itemsChanged(delta); }, destroy: function () { this.setDataset(); } } }, dataset: null, datasetRA_: null, emit_datasetChanged: createEvent("datasetChanged", "oldDataset"), emit_itemsChanged: createEvent("itemsChanged", "delta"), init: function () { DataObject.prototype.init.call(this); var dataset = this.dataset; if (dataset) { this.dataset = null; this.setDataset(dataset); } }, setDataset: function (dataset) { dataset = resolveDataset(this, this.setDataset, dataset, "datasetRA_"); if (this.dataset !== dataset) { var listenHandler = this.listen.dataset; var oldDataset = this.dataset; var delta; if (listenHandler) { if (oldDataset) oldDataset.removeHandler(listenHandler, this); if (dataset) dataset.addHandler(listenHandler, this); } this.itemCount = dataset ? dataset.itemCount : 0; this.dataset = dataset; if (delta = getDatasetDelta(oldDataset, dataset)) this.emit_itemsChanged(delta); this.emit_datasetChanged(oldDataset); } }, has: function (object) { return this.dataset ? this.dataset.has(object) : null; }, getItems: function () { return this.dataset ? this.dataset.getItems() : []; }, getValues: function (getter) { return this.dataset ? this.dataset.getValues(getter) : []; }, pick: function () { return this.dataset ? this.dataset.pick() : null; }, top: function (count) { return this.dataset ? this.dataset.top(count) : []; }, forEach: function (fn) { if (this.dataset) return this.dataset.forEach(fn); }, destroy: function () { if (this.dataset || this.datasetRA_) this.setDataset(); DataObject.prototype.destroy.call(this); } }); var ReadOnlyDataset = Class(AbstractData, { className: namespace + ".ReadOnlyDataset", propertyDescriptors: { "itemCount": "itemsChanged", "pick()": "itemsChanged", "getItems()": "itemsChanged" }, itemCount: 0, items_: null, members_: null, cache_: null, emit_itemsChanged: createEvent("itemsChanged", "delta") && function (delta) { var items; var insertCount = 0; var deleteCount = 0; var object; if (items = delta.inserted) { while (object = items[insertCount]) { this.items_[object.basisObjectId] = object; insertCount++; } } if (items = delta.deleted) { while (object = items[deleteCount]) { delete this.items_[object.basisObjectId]; deleteCount++; } } this.itemCount += insertCount - deleteCount; this.cache_ = insertCount == this.itemCount ? delta.inserted : null; events.itemsChanged.call(this, delta); }, init: function () { AbstractData.prototype.init.call(this); this.members_ = {}; this.items_ = {}; }, has: function (object) { return !!(object && this.items_[object.basisObjectId]); }, getItems: function () { if (!this.cache_) this.cache_ = values(this.items_); return this.cache_; }, getValues: function (getter) { return this.getItems().map(basis.getter(getter || $self)); }, pick: function () { for (var objectId in this.items_) return this.items_[objectId]; return null; }, top: function (count) { var result = []; if (count) for (var objectId in this.items_) if (result.push(this.items_[objectId]) >= count) break; return result; }, forEach: function (fn) { var items = this.getItems(); for (var i = 0; i < items.length; i++) fn(items[i]); }, destroy: function () { Dataset.preventAccumulations(this); AbstractData.prototype.destroy.call(this); this.cache_ = EMPTY_ARRAY; this.itemCount = 0; this.members_ = null; this.items_ = null; } }); var Dataset = Class(ReadOnlyDataset, { className: namespace + ".Dataset", listen: { item: { destroy: function (object) { this.remove([object]); } } }, init: function () { ReadOnlyDataset.prototype.init.call(this); var items = this.items; if (items) { this.items = null; this.set(items); } }, add: function (items) { var memberMap = this.members_; var listenHandler = this.listen.item; var inserted = []; var delta; if (items && !Array.isArray(items)) items = [items]; for (var i = 0; i < items.length; i++) { var object = items[i]; if (object instanceof DataObject) { var objectId = object.basisObjectId; if (!memberMap[objectId]) { memberMap[objectId] = object; if (listenHandler) object.addHandler(listenHandler, this); inserted.push(object); } } else { basis.dev.warn("Wrong data type: value should be an instance of basis.data.Object"); } } if (inserted.length) { this.emit_itemsChanged(delta = { inserted: inserted }); } return delta; }, remove: function (items) { var memberMap = this.members_; var listenHandler = this.listen.item; var deleted = []; var delta; if (items && !Array.isArray(items)) items = [items]; for (var i = 0; i < items.length; i++) { var object = items[i]; if (object instanceof DataObject) { var objectId = object.basisObjectId; if (memberMap[objectId]) { if (listenHandler) object.removeHandler(listenHandler, this); delete memberMap[objectId]; deleted.push(object); } } else { basis.dev.warn("Wrong data type: value should be an instance of basis.data.Object"); } } if (deleted.length) { this.emit_itemsChanged(delta = { deleted: deleted }); } return delta; }, set: function (items) { if (!this.itemCount) return this.add(items); if (!items || !items.length) return this.clear(); var memberMap = this.members_; var listenHandler = this.listen.item; var exists = {}; var deleted = []; var inserted = []; var object; var objectId; var delta; for (var i = 0; i < items.length; i++) { object = items[i]; if (object instanceof DataObject) { objectId = object.basisObjectId; exists[objectId] = object; if (!memberMap[objectId]) { memberMap[objectId] = object; if (listenHandler) object.addHandler(listenHandler, this); inserted.push(object); } } else { basis.dev.warn("Wrong data type: value should be an instance of basis.data.Object"); } } for (var objectId in memberMap) { if (!exists[objectId]) { object = memberMap[objectId]; if (listenHandler) object.removeHandler(listenHandler, this); delete memberMap[objectId]; deleted.push(object); } } if (delta = getDelta(inserted, deleted)) this.emit_itemsChanged(delta); return delta; }, sync: function (items) { basis.dev.warn("basis.data.Dataset#sync() method is deprecated, use basis.data.Dataset#setAndDestroyRemoved() instead."); return this.setAndDestroyRemoved(items); }, setAndDestroyRemoved: function (items) { var delta = this.set(items) || {}; var deleted = delta.deleted; Dataset.setAccumulateState(true); if (deleted) for (var i = 0, object; object = deleted[i]; i++) object.destroy(); Dataset.setAccumulateState(false); return delta.inserted; }, clear: function () { Dataset.flushChanges(this); var deleted = this.getItems(); var listenHandler = this.listen.item; var delta; if (deleted.length) { if (listenHandler) for (var i = 0; i < deleted.length; i++) deleted[i].removeHandler(listenHandler, this); this.emit_itemsChanged(delta = { deleted: deleted }); this.members_ = {}; } return delta; }, destroy: function () { this.clear(); ReadOnlyDataset.prototype.destroy.call(this); } }); var DATASETWRAPPER_ADAPTER_HANDLER = { datasetChanged: DEFAULT_CHANGE_ADAPTER_HANDLER, destroy: DEFAULT_DESTROY_ADAPTER_HANDLER }; function resolveAdapterProxy() { this.fn.call(this.context, this.source); } function resolveDataset(context, fn, source, property, factoryContext) { var oldAdapter = context[property] || null; var newAdapter = null; if (fn !== resolveAdapterProxy && typeof source == "function") source = source.call(factoryContext || context, factoryContext || context); if (source) { var adapter = newAdapter = oldAdapter && oldAdapter.source === source ? oldAdapter : null; if (source instanceof DatasetWrapper) { newAdapter = adapter || new ResolveAdapter(context, fn, source, DATASETWRAPPER_ADAPTER_HANDLER); source = source.dataset; } else if (source.bindingBridge) { newAdapter = adapter || new BBResolveAdapter(context, fn, source, DEFAULT_CHANGE_ADAPTER_HANDLER); source = resolveDataset(newAdapter, resolveAdapterProxy, source.value, "next"); } } if (source instanceof ReadOnlyDataset == false) source = null; if (property && oldAdapter !== newAdapter) { var cursor = oldAdapter; while (cursor) { var adapter = cursor; adapter.detach(); cursor = adapter.next; adapter.next = null; } if (newAdapter) newAdapter.attach(DEFAULT_DESTROY_ADAPTER_HANDLER); context[property] = newAdapter; } return source; } (function () { var PREVENT_ACCUMULATIONS = {}; var proto = ReadOnlyDataset.prototype; var eventCache = {}; var setStateCount = 0; var urgentTimer; var realEvent; function flushCache(cache) { realEvent.call(cache.dataset, cache); } function flushAllDataset() { function processEntry(datasetId) { var entry = eventCacheCopy[datasetId]; if (entry) { eventCacheCopy[datasetId] = null; if (entry !== PREVENT_ACCUMULATIONS) flushCache(entry); } } var eventCacheCopy = eventCache; var realEvent = proto.emit_itemsChanged; proto.emit_itemsChanged = function (delta) { processEntry(this.basisObjectId); realEvent.call(this, delta); }; eventCache = {}; for (var datasetId in eventCacheCopy) processEntry(datasetId); proto.emit_itemsChanged = realEvent; } function storeDatasetDelta(delta) { var dataset = this; var datasetId = dataset.basisObjectId; var inserted = delta.inserted; var deleted = delta.deleted; var cache = eventCache[datasetId]; if (inserted && deleted || cache && cache.mixed) { if (cache) { eventCache[datasetId] = null; flushCache(cache); } realEvent.call(dataset, delta); return; } if (cache) { var mode = inserted ? "inserted" : "deleted"; var array = cache[mode]; if (!array) { var inCacheMode = inserted ? "deleted" : "inserted"; var inCache = cache[inCacheMode]; var inCacheMap = {}; var deltaItems = inserted || deleted; var newInCacheItems = []; var inCacheRemoves = 0; for (var i = 0; i < inCache.length; i++) inCacheMap[inCache[i].basisObjectId] = i; for (var i = 0; i < deltaItems.length; i++) { var id = deltaItems[i].basisObjectId; if (id in inCacheMap == false) { newInCacheItems.push(deltaItems[i]); } else { if (!inCacheRemoves) inCache = sliceArray.call(inCache); inCacheRemoves++; inCache[inCacheMap[id]] = null; } } if (inCacheRemoves) { if (inCacheRemoves < inCache.length) { inCache = inCache.filter(Boolean); } else { inCache = null; } cache[inCacheMode] = inCache; } if (!newInCacheItems.length) { newInCacheItems = null; if (!inCache) eventCache[datasetId] = null; } else { cache[mode] = newInCacheItems; if (inCache) cache.mixed = true; } } else array.push.apply(array, inserted || deleted); return; } eventCache[datasetId] = { inserted: inserted, deleted: deleted, dataset: dataset, mixed: false }; } function urgentFlush() { urgentTimer = null; if (setStateCount) { basis.dev.warn("(debug) Urgent flush dataset changes"); setStateCount = 0; setAccumulateStateOff(); } } function setAccumulateStateOff() { proto.emit_itemsChanged = realEvent; flushAllDataset(); } Dataset.flushChanges = function (dataset) { var cache = eventCache[dataset.basisObjectId]; if (cache) flushCache(cache); eventCache[dataset.basisObjectId] = null; }; Dataset.preventAccumulations = function (dataset) { var cache = eventCache[dataset.basisObjectId]; if (cache && cache !== PREVENT_ACCUMULATIONS) realEvent.call(cache.dataset, cache); eventCache[dataset.basisObjectId] = PREVENT_ACCUMULATIONS; }; Dataset.setAccumulateState = function (state) { if (state) { if (setStateCount == 0) { realEvent = proto.emit_itemsChanged; proto.emit_itemsChanged = storeDatasetDelta; if (!urgentTimer) urgentTimer = basis.setImmediate(urgentFlush); } setStateCount++; } else { setStateCount -= setStateCount > 0; if (setStateCount == 0) setAccumulateStateOff(); } }; }()); function wrapData(data) { if (Array.isArray(data)) return data.map(function (item) { return { data: item }; }); else return { data: data }; } function wrapObject(data) { if (!data || data.constructor !== Object) data = { value: data }; return new DataObject({ data: data }); } function wrap(value, retObject) { var wrapper = retObject ? wrapObject : wrapData; return Array.isArray(value) ? value.map(wrapper) : wrapper(value); } module.exports = { STATE: STATE, SUBSCRIPTION: SUBSCRIPTION, AbstractData: AbstractData, Value: Value, ReadOnlyValue: ReadOnlyValue, DeferredValue: DeferredValue, PipeValue: PipeValue, Object: DataObject, Slot: Slot, KeyObjectMap: KeyObjectMap, ReadOnlyDataset: ReadOnlyDataset, Dataset: Dataset, DatasetWrapper: DatasetWrapper, devWrap: devWrap, devUnwrap: devUnwrap, isEqual: isEqual, chainValueFactory: chainValueFactory, isConnected: isConnected, getDatasetDelta: getDatasetDelta, ResolveAdapter: ResolveAdapter, createResolveFunction: createResolveFunction, resolveValue: resolveValue, resolveObject: resolveObject, resolveDataset: resolveDataset, wrapData: wrapData, wrapObject: wrapObject, wrap: wrap }; }, "h.js": function (exports, module, basis, global, __filename, __dirname, require, resource, asset) { var hasOwnProperty = Object.prototype.hasOwnProperty; var values = basis.object.values; var STATE_EXISTS = {}; var STATE = { priority: [], values: {}, add: function (state, order) { var name = state; var value = state.toLowerCase(); STATE[name] = value; STATE_EXISTS[value] = name; this.values[value] = name; if (order) order = this.priority.indexOf(order); else order = -1; if (order == -1) this.priority.push(value); else this.priority.splice(order, 0, value); }, getList: function () { return values(STATE_EXISTS); }, isValid: function (value) { return hasOwnProperty.call(STATE_EXISTS, value); } }; STATE.add("READY"); STATE.add("DEPRECATED"); STATE.add("UNDEFINED"); STATE.add("ERROR"); STATE.add("PROCESSING"); module.exports = STATE; }, "i.js": function (exports, module, basis, global, __filename, __dirname, require, resource, asset) { var subscriptionConfig = {}; var subscriptionSeed = 1; var maskConfig = {}; function mixFunctions(fnA, fnB) { return function () { fnA.apply(this, arguments); fnB.apply(this, arguments); }; } var SUBSCRIPTION = { NONE: 0, ALL: 0, add: function (name, handler, action) { subscriptionConfig[subscriptionSeed] = { handler: handler, action: action }; SUBSCRIPTION[name] = subscriptionSeed; SUBSCRIPTION.ALL |= subscriptionSeed; subscriptionSeed <<= 1; }, addProperty: function (propertyName, eventName) { var handler = {}; handler[eventName || propertyName + "Changed"] = function (object, oldValue) { if (oldValue) SUBSCRIPTION.unlink(propertyName, object, oldValue); if (object[propertyName]) SUBSCRIPTION.link(propertyName, object, object[propertyName]); }; this.add(propertyName.toUpperCase(), handler, function (fn, object) { if (object[propertyName]) fn(propertyName, object, object[propertyName]); }); }, getMaskConfig: function (mask) { var config = maskConfig[mask]; if (!config) { var actions = []; var handler = {}; var idx = 1; config = maskConfig[mask] = { actions: actions, handler: handler }; while (mask) { if (mask & 1) { var cfg = subscriptionConfig[idx]; actions.push(cfg.action); for (var key in cfg.handler) handler[key] = handler[key] ? mixFunctions(handler[key], cfg.handler[key]) : cfg.handler[key]; } idx <<= 1; mask >>= 1; } } return config; }, link: function (type, from, to) { var subscriberId = type + from.basisObjectId; var subscribers = to.subscribers_; if (!subscribers) subscribers = to.subscribers_ = {}; if (!subscribers[subscriberId]) { subscribers[subscriberId] = from; var count = to.subscriberCount += 1; if (count == 1) to.emit_subscribersChanged(+1); } else { basis.dev.warn("Attempt to add duplicate subscription"); } }, unlink: function (type, from, to) { var subscriberId = type + from.basisObjectId; var subscribers = to.subscribers_; if (subscribers && subscribers[subscriberId]) { delete subscribers[subscriberId]; var count = to.subscriberCount -= 1; if (count == 0) { to.emit_subscribersChanged(-1); to.subscribers_ = null; } } else { basis.dev.warn("Trying remove non-exists subscription"); } }, subscribe: function (object, mask) { var config = this.getMaskConfig(mask); for (var i = 0, action; action = config.actions[i]; i++) action(SUBSCRIPTION.link, object); object.addHandler(config.handler); }, unsubscribe: function (object, mask) { var config = this.getMaskConfig(mask); for (var i = 0, action; action = config.actions[i++];) action(SUBSCRIPTION.unlink, object); object.removeHandler(config.handler); }, changeSubscription: function (object, oldSubscriptionType, newSubscriptionType) { var delta = oldSubscriptionType ^ newSubscriptionType; if (delta) { var curConfig = SUBSCRIPTION.getMaskConfig(oldSubscriptionType); var newConfig = SUBSCRIPTION.getMaskConfig(newSubscriptionType); object.removeHandler(curConfig.handler); object.addHandler(newConfig.handler); var idx = 1; while (delta) { if (delta & 1) { var cfg = subscriptionConfig[idx]; if (oldSubscriptionType & idx) cfg.action(SUBSCRIPTION.unlink, object); else cfg.action(SUBSCRIPTION.link, object); } idx <<= 1; delta >>= 1; } } } }; module.exports = SUBSCRIPTION; }, "j.js": function (exports, module, basis, global, __filename, __dirname, require, resource, asset) { var NULL_OBJECT = {}; function resolveAdapterProxy() { this.fn.call(this.context, this.source); } var ResolveAdapter = function (context, fn, source, handler) { this.context = context; this.fn = fn; this.source = source; this.handler = handler; }; ResolveAdapter.prototype = { context: null, fn: null, source: null, handler: null, next: null, attach: function () { this.source.addHandler(this.handler, this); }, detach: function () { this.source.removeHandler(this.handler, this); } }; var BBResolveAdapter = function () { ResolveAdapter.apply(this, arguments); }; BBResolveAdapter.prototype = new ResolveAdapter(); BBResolveAdapter.prototype.attach = function (destroyCallback) { this.source.bindingBridge.attach(this.source, this.handler, this, destroyCallback); }; BBResolveAdapter.prototype.detach = function () { this.source.bindingBridge.detach(this.source, this.handler, this); }; var DEFAULT_CHANGE_ADAPTER_HANDLER = function () { this.fn.call(this.context, this.source); }; var DEFAULT_DESTROY_ADAPTER_HANDLER = function () { this.fn.call(this.context, null); }; var RESOLVEVALUE_DESTROY_ADAPTER_HANDLER = function () { this.fn.call(this.context, resolveValue(NULL_OBJECT, null, this.source.bindingBridge.get(this.source))); }; function createResolveFunction(Class) { return function resolve(context, fn, source, property, factoryContext) { var oldAdapter = context[property] || null; var newAdapter = null; if (fn !== resolveAdapterProxy && typeof source == "function") source = source.call(factoryContext || context, factoryContext || context); if (source && source.bindingBridge) { if (!oldAdapter || oldAdapter.source !== source) newAdapter = new BBResolveAdapter(context, fn, source, DEFAULT_CHANGE_ADAPTER_HANDLER); else newAdapter = oldAdapter; source = resolve(newAdapter, resolveAdapterProxy, source.bindingBridge.get(source), "next"); } if (source instanceof Class == false) source = null; if (property && oldAdapter !== newAdapter) { var cursor = oldAdapter; while (cursor) { var adapter = cursor; adapter.detach(); cursor = adapter.next; adapter.next = null; } if (newAdapter) newAdapter.attach(DEFAULT_DESTROY_ADAPTER_HANDLER); context[property] = newAdapter; } return source; }; } function resolveValue(context, fn, source, property, factoryContext) { var oldAdapter = context[property] || null; var newAdapter = null; if (source && fn !== resolveAdapterProxy && basis.fn.isFactory(source)) source = source.call(factoryContext || context, factoryContext || context); if (source && source.bindingBridge) { if (!oldAdapter || oldAdapter.source !== source) newAdapter = new BBResolveAdapter(context, fn, source, DEFAULT_CHANGE_ADAPTER_HANDLER); else newAdapter = oldAdapter; source = resolveValue(newAdapter, resolveAdapterProxy, source.bindingBridge.get(source), "next"); } if (property && oldAdapter !== newAdapter) { var cursor = oldAdapter; while (cursor) { var adapter = cursor; adapter.detach(); cursor = adapter.next; adapter.next = null; } if (newAdapter) newAdapter.attach(RESOLVEVALUE_DESTROY_ADAPTER_HANDLER); context[property] = newAdapter; } return source; } module.exports = { DEFAULT_CHANGE_ADAPTER_HANDLER: DEFAULT_CHANGE_ADAPTER_HANDLER, DEFAULT_DESTROY_ADAPTER_HANDLER: DEFAULT_DESTROY_ADAPTER_HANDLER, ResolveAdapter: ResolveAdapter, BBResolveAdapter: BBResolveAdapter, createResolveFunction: createResolveFunction, resolveValue: resolveValue }; }, "1i.js": function (exports, module, basis, global, __filename, __dirname, require, resource, asset) { var basisEvent = basis.require("./3.js"); var Emitter = basisEvent.Emitter; var createEvent = basisEvent.create; var STATE = basis.require("./h.js"); var SUBSCRIPTION = basis.require("./i.js"); var resolveValue = basis.require("./j.js").resolveValue; var PROXY = basis.PROXY; var ABSTRACTDATA_ACTIVE_SYNC_HANDLER = { subscribersChanged: function (host) { this.set(host.subscriberCount > 0); } }; function callSyncAction(object) { var syncResult = object.syncAction(); if (syncResult && typeof syncResult.then == "function") { var syncAction = object.syncAction; if (object.state != STATE.PROCESSING) object.setState(STATE.PROCESSING); syncResult.then(function () { if (object.syncAction === syncAction && object.state == STATE.PROCESSING) object.setState(STATE.READY); }, function (e) { if (object.syncAction === syncAction && object.state == STATE.PROCESSING) object.setState(STATE.ERROR, e); }); } } var AbstractData = Emitter.subclass({ className: "basis.data.AbstractData", propertyDescriptors: { state: "stateChanged", active: "activeChanged", subscriberCount: "subscribersChanged", subscribeTo: false, syncAction: false, syncEvents: false }, state: STATE.UNDEFINED, stateRA_: null, emit_stateChanged: createEvent("stateChanged", "oldState"), active: false, activeRA_: null, emit_activeChanged: createEvent("activeChanged"), subscribeTo: SUBSCRIPTION.NONE, subscriberCount: 0, subscribers_: null, emit_subscribersChanged: createEvent("subscribersChanged", "delta"), syncEvents: basis.Class.oneFunctionProperty(function () { if (this.isSyncRequired()) callSyncAction(this); }, { stateChanged: true, subscribersChanged: true }), syncAction: null, init: function () { Emitter.prototype.init.call(this); if (this.active) { if (this.active === PROXY) { this.active = new basis.Token(this.subscriberCount > 0); this.addHandler(ABSTRACTDATA_ACTIVE_SYNC_HANDLER, this.active); } this.active = !!resolveValue(this, this.setActive, this.active, "activeRA_"); if (this.active) this.addHandler(SUBSCRIPTION.getMaskConfig(this.subscribeTo).handler); } if (this.state != STATE.UNDEFINED) { var state = this.state; if (typeof this.state != "string") state = resolveValue(this, this.setState, state, "stateRA_"); if (state && !STATE.isValid(state)) { basis.dev.error("Wrong value for state (value has been ignored and state set to STATE.UNDEFINED)", state); state = false; } this.state = state || STATE.UNDEFINED; } var syncAction = this.syncAction; if (syncAction) { this.syncAction = null; this.setSyncAction(syncAction); } }, setState: function (state, data) { state = resolveValue(this, this.setState, state, "stateRA_") || STATE.UNDEFINED; var stateCode = String(state); if (!STATE.isValid(stateCode)) { basis.dev.error("Wrong value for state (value has been ignored)", stateCode); return false; } if (this.stateRA_ && data === undefined) data = state.data; if (this.state != stateCode || this.state.data != data) { var oldState = this.state; this.state = Object(stateCode); this.state.data = data; this.emit_stateChanged(oldState); return true; } return false; }, deprecate: function () { if (this.state != STATE.PROCESSING) this.setState(STATE.DEPRECATED); }, setActive: function (isActive) { var proxyToken = this.activeRA_ && this.activeRA_.proxyToken; if (isActive === PROXY) { if (!proxyToken) { proxyToken = new basis.Token(this.subscriberCount > 0); this.addHandler(ABSTRACTDATA_ACTIVE_SYNC_HANDLER, proxyToken); } isActive = proxyToken; } else { if (proxyToken && isActive !== proxyToken) { this.removeHandler(ABSTRACTDATA_ACTIVE_SYNC_HANDLER, proxyToken); proxyToken = null; } } isActive = !!resolveValue(this, this.setActive, isActive, "activeRA_"); if (proxyToken && this.activeRA_) this.activeRA_.proxyToken = proxyToken; if (this.active != isActive) { this.active = isActive; this.emit_activeChanged(); if (isActive) SUBSCRIPTION.subscribe(this, this.subscribeTo); else SUBSCRIPTION.unsubscribe(this, this.subscribeTo); return true; } return false; }, setSubscription: function (subscriptionType) { var curSubscriptionType = this.subscribeTo; var newSubscriptionType = subscriptionType & SUBSCRIPTION.ALL; var delta = curSubscriptionType ^ newSubscriptionType; if (delta) { this.subscribeTo = newSubscriptionType; if (this.active) SUBSCRIPTION.changeSubscription(this, curSubscriptionType, newSubscriptionType); return true; } return false; }, isSyncRequired: function () { return this.subscriberCount > 0 && (this.state == STATE.UNDEFINED || this.state == STATE.DEPRECATED); }, setSyncAction: function (syncAction) { var oldAction = this.syncAction; if (typeof syncAction != "function") syncAction = null; this.syncAction = syncAction; if (syncAction) { if (!oldAction) this.addHandler(this.syncEvents); if (this.isSyncRequired()) callSyncAction(this); } else { if (oldAction) this.removeHandler(this.syncEvents); } }, destroy: function () { Emitter.prototype.destroy.call(this); if (this.active) { var config = SUBSCRIPTION.getMaskConfig(this.subscribeTo); for (var i = 0, action; action = config.actions[i]; i++) action(SUBSCRIPTION.unlink, this); } if (this.activeRA_) resolveValue(this, false, false, "activeRA_"); if (this.stateRA_) resolveValue(this, false, false, "stateRA_"); this.state = STATE.UNDEFINED; } }); module.exports = AbstractData; }, "k.js": function (exports, module, basis, global, __filename, __dirname, require, resource, asset) { var namespace = "basis.dragdrop"; var document = global.document; var cleaner = basis.cleaner; var eventUtils = basis.require("./e.js"); var addGlobalHandler = eventUtils.addGlobalHandler; var removeGlobalHandler = eventUtils.removeGlobalHandler; var basisEvent = basis.require("./3.js"); var Emitter = basisEvent.Emitter; var createEvent = basisEvent.create; var getComputedStyle = basis.require("./l.js").get; var basisLayout = basis.require("./m.js"); var getBoundingRect = basisLayout.getBoundingRect; var getViewportRect = basisLayout.getViewportRect; var SELECTSTART_SUPPORTED = eventUtils.getEventInfo("selectstart").supported; var dragging; var dragElement; var dragData; function resolveElement(value) { return typeof value == "string" ? document.getElementById(value) : value; } function startDrag(event) { if (dragElement || this.ignoreTarget(event.sender, event)) return; var viewport = getViewportRect(event.sender); if (event.mouseX < viewport.left || event.mouseX > viewport.right || event.mouseY < viewport.top || event.mouseY > viewport.bottom) return; dragElement = this; dragData = { initX: event.mouseX, initY: event.mouseY, deltaX: 0, minDeltaX: -Infinity, maxDeltaX: Infinity, deltaY: 0, minDeltaY: -Infinity, maxDeltaY: Infinity }; addGlobalHandler("mousedown", stopDrag); addGlobalHandler("touchstart", stopDrag); addGlobalHandler("mousemove", onDrag); addGlobalHandler("touchmove", onDrag); addGlobalHandler("mouseup", stopDrag); addGlobalHandler("touchend", stopDrag); if (SELECTSTART_SUPPORTED) addGlobalHandler("selectstart", eventUtils.kill); event.preventDefault(); this.prepareDrag(dragData, event); } function onDrag(event) { var deltaX = event.mouseX - dragData.initX; var deltaY = event.mouseY - dragData.initY; if (!dragging) { if (!dragElement.startRule(deltaX, deltaY)) return; dragging = true; dragElement.emit_start(dragData, event); } if (dragElement.axisX) dragData.deltaX = dragElement.axisXproxy(basis.number.fit(deltaX, dragData.minDeltaX, dragData.maxDeltaX)); if (dragElement.axisY) dragData.deltaY = dragElement.axisYproxy(basis.number.fit(deltaY, dragData.minDeltaY, dragData.maxDeltaY)); dragElement.emit_drag(dragData, event); } function stopDrag(event) { removeGlobalHandler("mousedown", stopDrag); removeGlobalHandler("touchstart", stopDrag); removeGlobalHandler("mousemove", onDrag); removeGlobalHandler("touchmove", onDrag); removeGlobalHandler("mouseup", stopDrag); removeGlobalHandler("touchend", stopDrag); if (SELECTSTART_SUPPORTED) removeGlobalHandler("selectstart", eventUtils.kill); var element = dragElement; var data = dragData; dragElement = null; dragData = null; if (dragging) { dragging = false; element.emit_over(data, event); } event.die(); } var DragDropElement = Emitter.subclass({ className: namespace + ".DragDropElement", element: null, trigger: null, baseElement: null, axisX: true, axisY: true, axisXproxy: basis.fn.$self, axisYproxy: basis.fn.$self, prepareDrag: basis.fn.$undef, startRule: basis.fn.$true, ignoreTarget: function (target) { return /^(INPUT|TEXTAREA|SELECT|BUTTON)$/.test(target.tagName); }, emit_start: createEvent("start"), emit_drag: createEvent("drag"), emit_over: createEvent("over"), init: function () { Emitter.prototype.init.call(this); var element = this.element; var trigger = this.trigger; this.element = null; this.trigger = null; this.setElement(element, trigger); this.setBase(this.baseElement); cleaner.add(this); }, setElement: function (element, trigger) { this.element = resolveElement(element); trigger = resolveElement(trigger) || this.element; if (this.trigger !== trigger) { if (this.trigger) { eventUtils.removeHandler(this.trigger, "mousedown", startDrag, this); eventUtils.removeHandler(this.trigger, "touchstart", startDrag, this); } this.trigger = trigger; if (this.trigger) { eventUtils.addHandler(this.trigger, "mousedown", startDrag, this); eventUtils.addHandler(this.trigger, "touchstart", startDrag, this); } } }, setBase: function (baseElement) { this.baseElement = resolveElement(baseElement); }, getBase: function () { if (getComputedStyle(this.element, "position") == "fixed") return global; if (this.baseElement) return this.baseElement; return document.compatMode == "CSS1Compat" ? document.documentElement : document.body; }, isDragging: function () { return dragElement === this; }, start: function (event) { if (!this.isDragging()) startDrag.call(this, event); }, stop: function () { if (this.isDragging()) stopDrag(); }, destroy: function () { this.stop(); cleaner.remove(this); Emitter.prototype.destroy.call(this); this.setElement(); this.setBase(); } }); var DeltaWriter = basis.Class(null, { className: namespace + ".DeltaWriter", property: null, invert: false, format: basis.fn.$self, init: function (element) { if (typeof this.property == "function") this.property = this.property(element); if (typeof this.invert == "function") this.invert = this.invert(this.property); this.value = this.read(element); }, read: function (element) { return element[this.property]; }, write: function (element, formattedValue) { element[this.property] = formattedValue; }, applyDelta: function (element, delta) { if (this.invert) delta = -delta; this.write(element, this.format(this.value + delta, delta)); } }); var StyleDeltaWriter = DeltaWriter.subclass({ className: namespace + ".StyleDeltaWriter", format: function (value) { return value + "px"; }, read: function (element) { return parseFloat(getComputedStyle(element, this.property)) || 0; }, write: function (element, formattedValue) { element.style[this.property] = formattedValue; } }); var StylePositionX = StyleDeltaWriter.subclass({ className: namespace + ".StylePositionX", property: function (element) { return getComputedStyle(element, "left") == "auto" && getComputedStyle(element, "right") != "auto" ? "right" : "left"; }, invert: function (property) { return property == "right"; } }); var StylePositionY = StyleDeltaWriter.subclass({ className: namespace + ".StylePositionY", property: function (element) { return getComputedStyle(element, "top") == "auto" && getComputedStyle(element, "bottom") != "auto" ? "bottom" : "top"; }, invert: function (property) { return property == "bottom"; } }); var MoveableElement = DragDropElement.subclass({ className: namespace + ".MoveableElement", fixTop: true, fixRight: true, fixBottom: true, fixLeft: true, axisX: StylePositionX, axisY: StylePositionY, emit_start: function (dragData, event) { var element = this.element; if (element) { var viewport = getViewportRect(this.getBase()); var box = getBoundingRect(element); dragData.element = element; if (this.axisX) { dragData.axisX = new this.axisX(element); if (this.fixLeft) dragData.minDeltaX = viewport.left - box.left; if (this.fixRight) dragData.maxDeltaX = viewport.right - box.right; } if (this.axisY) { dragData.axisY = new this.axisY(element); if (this.fixTop) dragData.minDeltaY = viewport.top - box.top; if (this.fixBottom) dragData.maxDeltaY = viewport.bottom - box.bottom; } } DragDropElement.prototype.emit_start.call(this, dragData, event); }, emit_drag: function (dragData, event) { if (!dragData.element) return; if (dragData.axisX) dragData.axisX.applyDelta(dragData.element, dragData.deltaX); if (dragData.axisY) dragData.axisY.applyDelta(dragData.element, dragData.deltaY); DragDropElement.prototype.emit_drag.call(this, dragData, event); } }); module.exports = { DragDropElement: DragDropElement, MoveableElement: MoveableElement, DeltaWriter: DeltaWriter, StyleDeltaWriter: StyleDeltaWriter }; }, "l.js": function (exports, module, basis, global, __filename, __dirname, require, resource, asset) { var document = global.document; var computedStyle; if ("getComputedStyle" in global) { var GETCOMPUTEDSTYLE_BUGGY = { top: true, bottom: true, left: true, right: true, height: true, width: true }; var testForBuggyProperties = basis.fn.runOnce(function () { var testElement = document.createElement("div"); testElement.setAttribute("style", "position:absolute;top:auto!important"); basis.doc.body.add(testElement); if (global.getComputedStyle(testElement).top == "auto") GETCOMPUTEDSTYLE_BUGGY = {}; basis.doc.remove(testElement); }); computedStyle = function (element, styleProp) { var style = global.getComputedStyle(element); var res; if (style) { if (styleProp in GETCOMPUTEDSTYLE_BUGGY) testForBuggyProperties(); if (GETCOMPUTEDSTYLE_BUGGY[styleProp] && style.position != "static") { var display = element.style.display; element.style.display = "none"; res = style.getPropertyValue(styleProp); element.style.display = display; } else { res = style.getPropertyValue(styleProp); } return res; } }; } else { var VALUE_UNIT = /^-?(\d*\.)?\d+([a-z]+|%)?$/i; var IS_PIXEL = /\dpx$/i; var getPixelValue = function (element, value) { if (IS_PIXEL.test(value)) return parseInt(value, 10) + "px"; var style = element.style; var runtimeStyle = element.runtimeStyle; var left = style.left; var runtimeLeft = runtimeStyle.left; runtimeStyle.left = element.currentStyle.left; style.left = value || 0; value = style.pixelLeft; style.left = left; runtimeStyle.left = runtimeLeft; return value + "px"; }; computedStyle = function (element, styleProp) { var style = element.currentStyle; if (style) { var value = style[styleProp == "float" ? "styleFloat" : basis.string.camelize(styleProp)]; var unit = (value || "").match(VALUE_UNIT); if (unit && unit[2] && unit[2] != "px") value = getPixelValue(element, value); return value; } }; } module.exports = { get: computedStyle }; }, "m.js": function (exports, module, basis, global, __filename, __dirname, require, resource, asset) { var document = global.document; var documentElement = document.documentElement; var getComputedStyle = basis.require("./l.js").get; var standartsMode = document.compatMode == "CSS1Compat"; function getOffsetParent(node) { var offsetParent = node.offsetParent || documentElement; while (offsetParent && offsetParent !== documentElement && getComputedStyle(offsetParent, "position") == "static") offsetParent = offsetParent.offsetParent; return offsetParent || documentElement; } function getOffset(element) { var top = 0; var left = 0; if (element && element.getBoundingClientRect) { var relRect = element.getBoundingClientRect(); top = -relRect.top; left = -relRect.left; } else { if (standartsMode) { top = global.pageYOffset || documentElement.scrollTop; left = global.pageXOffset || documentElement.scrollLeft; } else { var body = document.body; if (element !== body) { top = body.scrollTop - body.clientTop; left = body.scrollLeft - body.clientLeft; } } } return { left: left, top: top }; } function getTopLeftPoint(element, relElement) { var left = 0; var top = 0; var offset = getOffset(relElement); if (element && element.getBoundingClientRect) { var box = element.getBoundingClientRect(); top = box.top; left = box.left; } return { top: top + offset.top, left: left + offset.left }; } function getBoundingRect(element, relElement) { var top = 0; var left = 0; var right = 0; var bottom = 0; var offset = getOffset(relElement); if (element && element.getBoundingClientRect) { var rect = element.getBoundingClientRect(); top = rect.top; left = rect.left; right = rect.right; bottom = rect.bottom; } return { top: top + offset.top, left: left + offset.left, right: right + offset.left, bottom: bottom + offset.top, width: right - left, height: bottom - top }; } function getViewportRect(element, relElement) { var topViewport = standartsMode ? document.documentElement : document.body; var point = element === topViewport && !relElement ? getOffset() : getTopLeftPoint(element, relElement); var top = point.top; var left = point.left; var width; var height; if (!element || element === global) { width = global.innerWidth || 0; height = global.innerHeight || 0; } else { top += element.clientTop; left += element.clientLeft; width = element.clientWidth; height = element.clientHeight; } return { top: top, left: left, right: left + width, bottom: top + height, width: width, height: height }; } module.exports = { getOffset: getOffset, getOffsetParent: getOffsetParent, getTopLeftPoint: getTopLeftPoint, getBoundingRect: getBoundingRect, getViewportRect: getViewportRect }; }, "n.js": function (exports, module, basis, global, __filename, __dirname, require, resource, asset) { module.exports = { getDelta: basis.require("./1j.js"), createRuleEvents: basis.require("./1k.js"), SourceDataset: basis.require("./1l.js"), Merge: basis.require("./1m.js"), Subtract: basis.require("./1n.js"), MapFilter: basis.require("./1o.js"), Split: basis.require("./1p.js"), Cloud: basis.require("./1r.js"), Extract: basis.require("./1s.js"), Filter: basis.require("./1t.js"), Slice: basis.require("./1u.js") }; }, "1j.js": function (exports, module, basis, global, __filename, __dirname, require, resource, asset) { module.exports = function getDelta(inserted, deleted) { var delta = {}; var result; if (inserted && inserted.length) result = delta.inserted = inserted; if (deleted && deleted.length) result = delta.deleted = deleted; if (result) return delta; }; }, "1k.js": function (exports, module, basis, global, __filename, __dirname, require, resource, asset) { var extend = basis.object.extend; var createEventHandler = basis.require("./3.js").createHandler; module.exports = function createRuleEvents(fn, events) { return function createRuleEventsExtend(events) { if (!events) return null; if (events.__extend__) return events; if (typeof events != "string" && !Array.isArray(events)) events = null; return extend(createEventHandler(events, fn), { __extend__: createRuleEventsExtend }); }(events); }; }, "1l.js": function (exports, module, basis, global, __filename, __dirname, require, resource, asset) { var createEvent = basis.require("./3.js").create; var resolveDataset = basis.require("./g.js").resolveDataset; var ReadOnlyDataset = basis.require("./g.js").ReadOnlyDataset; var setAccumulateState = basis.require("./g.js").Dataset.setAccumulateState; var SUBSCRIPTION = basis.require("./i.js"); SUBSCRIPTION.addProperty("source"); module.exports = ReadOnlyDataset.subclass({ className: "basis.data.dataset.SourceDataset", propertyDescriptors: { source: "sourceChanged", subtrahend: "subtrahendChanged" }, active: basis.PROXY, subscribeTo: SUBSCRIPTION.SOURCE, source: null, emit_sourceChanged: createEvent("sourceChanged", "oldSource"), sourceRA_: null, sourceMap_: null, listen: { source: { destroy: function () { if (!this.sourceRA_) this.setSource(); } } }, init: function () { var source = this.source; this.source = null; this.sourceMap_ = {}; ReadOnlyDataset.prototype.init.call(this); if (source) this.setSource(source); }, setSource: function (source) { source = resolveDataset(this, this.setSource, source, "sourceRA_"); if (this.source !== source) { var oldSource = this.source; var listenHandler = this.listen.source; var itemsChangedHandler = listenHandler && listenHandler.itemsChanged; this.source = null; setAccumulateState(true); if (oldSource) { if (listenHandler) oldSource.removeHandler(listenHandler, this); if (itemsChangedHandler) itemsChangedHandler.call(this, oldSource, { deleted: oldSource.getItems() }); } this.source = source; this.emit_sourceChanged(oldSource); basis.dev.patchInfo(this, "sourceInfo", { source: source }); if (source) { if (listenHandler) source.addHandler(listenHandler, this); if (itemsChangedHandler) itemsChangedHandler.call(this, source, { inserted: source.getItems() }); } setAccumulateState(false); } }, destroy: function () { this.setSource(); ReadOnlyDataset.prototype.destroy.call(this); this.sourceMap_ = null; } }); }, "1.js": function (exports, module, basis, global, __filename, __dirname, require, resource, asset) { basis.require("./2.js"); basis.require("./k.js"); basis.require("./n.js"); basis.require("./o.js"); basis.require("./p.js"); basis.require("./q.js"); basis.require("./r.js"); basis.require("./t.js"); basis.require("./v.js"); basis.require("./y.js"); basis.require("./10.js"); basis.require("./11.js"); global.basis = basis; }, "1n.js": function (exports, module, basis, global, __filename, __dirname, require, resource, asset) { var createEvent = basis.require("./3.js").create; var resolveDataset = basis.require("./g.js").resolveDataset; var ReadOnlyDataset = basis.require("./g.js").ReadOnlyDataset; var getDelta = basis.require("./1j.js"); var SUBSCRIPTION = basis.require("./i.js"); var Dataset = basis.require("./g.js").Dataset; SUBSCRIPTION.addProperty("minuend"); SUBSCRIPTION.addProperty("subtrahend"); var datasetAbsentFilter = function (item) { return !this.has(item); }; var SUBTRACTDATASET_MINUEND_HANDLER = { itemsChanged: function (dataset, delta) { if (!this.subtrahend) return; Dataset.flushChanges(this); var newDelta = getDelta(delta.inserted && delta.inserted.filter(datasetAbsentFilter, this.subtrahend), delta.deleted && delta.deleted.filter(this.has, this)); if (newDelta) this.emit_itemsChanged(newDelta); }, destroy: function () { if (!this.minuendRA_) this.setMinuend(null); } }; var SUBTRACTDATASET_SUBTRAHEND_HANDLER = { itemsChanged: function (dataset, delta) { if (!this.minuend) return; Dataset.flushChanges(this); var newDelta = getDelta(delta.deleted && delta.deleted.filter(this.minuend.has, this.minuend), delta.inserted && delta.inserted.filter(this.has, this)); if (newDelta) this.emit_itemsChanged(newDelta); }, destroy: function () { if (!this.subtrahendRA_) this.setSubtrahend(null); } }; module.exports = ReadOnlyDataset.subclass({ className: "basis.data.dataset.Subtract", propertyDescriptors: { minuend: "minuendChanged", subtrahend: "subtrahendChanged" }, active: basis.PROXY, subscribeTo: SUBSCRIPTION.MINUEND + SUBSCRIPTION.SUBTRAHEND, minuend: null, minuendRA_: null, emit_minuendChanged: createEvent("minuendChanged", "oldMinuend"), subtrahend: null, subtrahendRA_: null, emit_subtrahendChanged: createEvent("subtrahendChanged", "oldSubtrahend"), listen: { minuend: SUBTRACTDATASET_MINUEND_HANDLER, subtrahend: SUBTRACTDATASET_SUBTRAHEND_HANDLER }, init: function () { ReadOnlyDataset.prototype.init.call(this); var minuend = this.minuend; var subtrahend = this.subtrahend; this.minuend = null; this.subtrahend = null; if (minuend || subtrahend) this.setOperands(minuend, subtrahend); }, setOperands: function (minuend, subtrahend) { var delta; var operandsChanged = false; var oldMinuend = this.minuend; var oldSubtrahend = this.subtrahend; minuend = resolveDataset(this, this.setMinuend, minuend, "minuendRA_"); subtrahend = resolveDataset(this, this.setSubtrahend, subtrahend, "subtrahendRA_"); if (oldMinuend !== minuend) { operandsChanged = true; this.minuend = minuend; var listenHandler = this.listen.minuend; if (listenHandler) { if (oldMinuend) oldMinuend.removeHandler(listenHandler, this); if (minuend) minuend.addHandler(listenHandler, this); } this.emit_minuendChanged(oldMinuend); } if (oldSubtrahend !== subtrahend) { operandsChanged = true; this.subtrahend = subtrahend; var listenHandler = this.listen.subtrahend; if (listenHandler) { if (oldSubtrahend) oldSubtrahend.removeHandler(listenHandler, this); if (subtrahend) subtrahend.addHandler(listenHandler, this); } this.emit_subtrahendChanged(oldSubtrahend); } if (!operandsChanged) return false; basis.dev.setInfo(this, "sourceInfo", { type: "Subtract", source: [ minuend, subtrahend ] }); if (!minuend || !subtrahend) { if (this.itemCount) this.emit_itemsChanged(delta = { deleted: this.getItems() }); } else { var deleted = []; var inserted = []; for (var key in this.items_) if (!minuend.items_[key] || subtrahend.items_[key]) deleted.push(this.items_[key]); for (var key in minuend.items_) if (!this.items_[key] && !subtrahend.items_[key]) inserted.push(minuend.items_[key]); if (delta = getDelta(inserted, deleted)) this.emit_itemsChanged(delta); } return delta; }, setMinuend: function (minuend) { return this.setOperands(minuend, this.subtrahendRA_ ? this.subtrahendRA_.source : this.subtrahend); }, setSubtrahend: function (subtrahend) { return this.setOperands(this.minuendRA_ ? this.minuendRA_.source : this.minuend, subtrahend); }, destroy: function () { this.setOperands(); ReadOnlyDataset.prototype.destroy.call(this); } }); }, "1o.js": function (exports, module, basis, global, __filename, __dirname, require, resource, asset) { var $self = basis.fn.$self; var $true = basis.fn.$true; var $false = basis.fn.$false; var createEvent = basis.require("./3.js").create; var createRuleEvents = basis.require("./1k.js"); var getDelta = basis.require("./1j.js"); var DataObject = basis.require("./g.js").Object; var isEqual = basis.require("./g.js").isEqual; var setAccumulateState = basis.require("./g.js").Dataset.setAccumulateState; var SourceDataset = basis.require("./1l.js"); var MAPFILTER_SOURCEOBJECT_UPDATE = function (sourceObject) { var newMember = this.map ? this.map(sourceObject) : sourceObject; if (newMember instanceof DataObject == false || this.filter(newMember)) newMember = null; var sourceMap = this.sourceMap_[sourceObject.basisObjectId]; var curMember = sourceMap.member; if (!isEqual(curMember, newMember)) { var memberMap = this.members_; var delta; var inserted; var deleted; sourceMap.member = newMember; if (curMember) { var curMemberId = curMember.basisObjectId; if (this.removeMemberRef) this.removeMemberRef(curMember, sourceObject); if (--memberMap[curMemberId] == 0) { delete memberMap[curMemberId]; deleted = [curMember]; } } if (newMember) { var newMemberId = newMember.basisObjectId; if (this.addMemberRef) this.addMemberRef(newMember, sourceObject); if (memberMap[newMemberId]) { memberMap[newMemberId]++; } else { memberMap[newMemberId] = 1; inserted = [newMember]; } } if (delta = getDelta(inserted, deleted)) this.emit_itemsChanged(delta); } }; var MAPFILTER_SOURCE_HANDLER = { itemsChanged: function (source, delta) { var sourceMap = this.sourceMap_; var memberMap = this.members_; var inserted = []; var deleted = []; var sourceObject; var sourceObjectId; var member; var updateHandler = this.ruleEvents; setAccumulateState(true); if (delta.inserted) { for (var i = 0; sourceObject = delta.inserted[i]; i++) { member = this.map ? this.map(sourceObject) : sourceObject; if (member instanceof DataObject == false || this.filter(member)) member = null; if (updateHandler) sourceObject.addHandler(updateHandler, this); sourceMap[sourceObject.basisObjectId] = { sourceObject: sourceObject, member: member }; if (member) { var memberId = member.basisObjectId; if (memberMap[memberId]) { memberMap[memberId]++; } else { memberMap[memberId] = 1; inserted.push(member); } if (this.addMemberRef) this.addMemberRef(member, sourceObject); } } } if (delta.deleted) { for (var i = 0; sourceObject = delta.deleted[i]; i++) { sourceObjectId = sourceObject.basisObjectId; member = sourceMap[sourceObjectId].member; if (updateHandler) sourceObject.removeHandler(updateHandler, this); delete sourceMap[sourceObjectId]; if (member) { var memberId = member.basisObjectId; if (--memberMap[memberId] == 0) { delete memberMap[memberId]; deleted.push(member); } if (this.removeMemberRef) this.removeMemberRef(member, sourceObject); } } } setAccumulateState(false); if (delta = getDelta(inserted, deleted)) this.emit_itemsChanged(delta); } }; module.exports = SourceDataset.subclass({ className: "basis.data.dataset.MapFilter", propertyDescriptors: { rule: "ruleChanged", addMemberRef: false, removeMemberRef: false, ruleEvents: false }, map: $self, filter: $false, rule: basis.getter($true), emit_ruleChanged: createEvent("ruleChanged", "oldRule"), ruleEvents: createRuleEvents(MAPFILTER_SOURCEOBJECT_UPDATE, "update"), addMemberRef: null, removeMemberRef: null, listen: { source: MAPFILTER_SOURCE_HANDLER }, init: function () { SourceDataset.prototype.init.call(this); basis.dev.patchInfo(this, "sourceInfo", { type: this.constructor.className.split(".").pop(), transform: this.rule }); }, setMap: function (map) { if (typeof map != "function") map = $self; if (this.map !== map) { this.map = map; return this.applyRule(); } }, setFilter: function (filter) { if (typeof filter != "function") filter = $false; if (this.filter !== filter) { this.filter = filter; return this.applyRule(); } }, setRule: function (rule) { rule = basis.getter(rule || $true); if (this.rule !== rule) { var oldRule = this.rule; this.rule = rule; this.emit_ruleChanged(oldRule); basis.dev.patchInfo(this, "sourceInfo", { transform: this.rule }); return this.applyRule(); } }, applyRule: function () { var sourceMap = this.sourceMap_; var memberMap = this.members_; var curMember; var newMember; var curMemberId; var newMemberId; var sourceObject; var sourceObjectInfo; var inserted = []; var deleted = []; var delta; for (var sourceObjectId in sourceMap) { sourceObjectInfo = sourceMap[sourceObjectId]; sourceObject = sourceObjectInfo.sourceObject; curMember = sourceObjectInfo.member; newMember = this.map ? this.map(sourceObject) : sourceObject; if (newMember instanceof DataObject == false || this.filter(newMember)) newMember = null; if (!isEqual(curMember, newMember)) { sourceObjectInfo.member = newMember; if (curMember) { curMemberId = curMember.basisObjectId; if (this.removeMemberRef) this.removeMemberRef(curMember, sourceObject); memberMap[curMemberId]--; } if (newMember) { newMemberId = newMember.basisObjectId; if (this.addMemberRef) this.addMemberRef(newMember, sourceObject); if (newMemberId in memberMap) { memberMap[newMemberId]++; } else { memberMap[newMemberId] = 1; inserted.push(newMember); } } } } for (curMemberId in this.items_) if (memberMap[curMemberId] == 0) { delete memberMap[curMemberId]; deleted.push(this.items_[curMemberId]); } if (delta = getDelta(inserted, deleted)) this.emit_itemsChanged(delta); return delta; } }); }, "1p.js": function (exports, module, basis, global, __filename, __dirname, require, resource, asset) { var $undef = basis.fn.$undef; var ReadOnlyDataset = basis.require("./g.js").ReadOnlyDataset; var DatasetWrapper = basis.require("./g.js").DatasetWrapper; var KeyObjectMap = basis.require("./g.js").KeyObjectMap; var MapFilter = basis.require("./1o.js"); var createKeyMap = basis.require("./1q.js"); module.exports = MapFilter.subclass({ className: "basis.data.dataset.Split", subsetClass: ReadOnlyDataset, subsetWrapperClass: DatasetWrapper, keyMap: null, map: function (sourceObject) { return this.keyMap.resolve(sourceObject); }, rule: basis.getter($undef), setRule: function (rule) { rule = basis.getter(rule || $undef); if (this.rule !== rule) { var oldRule = this.rule; this.rule = rule; this.keyMap.keyGetter = rule; this.emit_ruleChanged(oldRule); return this.applyRule(); } }, addMemberRef: function (wrapper, sourceObject) { wrapper.dataset.emit_itemsChanged({ inserted: [sourceObject] }); }, removeMemberRef: function (wrapper, sourceObject) { wrapper.dataset.emit_itemsChanged({ deleted: [sourceObject] }); }, init: function () { if (!this.keyMap || this.keyMap instanceof KeyObjectMap == false) this.keyMap = createKeyMap(this.keyMap, this.rule, this.subsetWrapperClass, this.subsetClass); MapFilter.prototype.init.call(this); }, getSubset: function (data, autocreate) { return this.keyMap.get(data, autocreate); }, destroy: function () { MapFilter.prototype.destroy.call(this); this.keyMap.destroy(); this.keyMap = null; } }); }, "1q.js": function (exports, module, basis, global, __filename, __dirname, require, resource, asset) { var extend = basis.object.extend; var KeyObjectMap = basis.require("./g.js").KeyObjectMap; module.exports = function createKeyMap(config, keyGetter, ItemClass, SubsetClass) { return new KeyObjectMap(extend({ keyGetter: keyGetter, itemClass: ItemClass, create: function (key, object) { var datasetWrapper = KeyObjectMap.prototype.create.call(this, key, object); datasetWrapper.ruleValue = key; datasetWrapper.setDataset(new SubsetClass({ ruleValue: key })); return datasetWrapper; } }, config)); }; }, "1r.js": function (exports, module, basis, global, __filename, __dirname, require, resource, asset) { var $self = basis.fn.$self; var $undef = basis.fn.$undef; var ReadOnlyDataset = basis.require("./g.js").ReadOnlyDataset; var DatasetWrapper = basis.require("./g.js").DatasetWrapper; var KeyObjectMap = basis.require("./g.js").KeyObjectMap; var setAccumulateState = basis.require("./g.js").Dataset.setAccumulateState; var SourceDataset = basis.require("./1l.js"); var createKeyMap = basis.require("./1q.js"); var createRuleEvents = basis.require("./1k.js"); var getDelta = basis.require("./1j.js"); var CLOUD_SOURCEOBJECT_UPDATE = function (sourceObject) { var sourceMap = this.sourceMap_; var memberMap = this.members_; var sourceObjectId = sourceObject.basisObjectId; var oldList = sourceMap[sourceObjectId].list; var newList = sourceMap[sourceObjectId].list = {}; var list = this.rule(sourceObject); var delta; var inserted = []; var deleted = []; var subset; if (Array.isArray(list)) for (var j = 0; j < list.length; j++) { subset = this.keyMap.get(list[j], true); if (subset && !subset.has(sourceObject)) { subsetId = subset.basisObjectId; newList[subsetId] = subset; if (!oldList[subsetId]) { subset.dataset.emit_itemsChanged({ inserted: [sourceObject] }); if (!memberMap[subsetId]) { inserted.push(subset); memberMap[subsetId] = 1; } else memberMap[subsetId]++; } } } for (var subsetId in oldList) if (!newList[subsetId]) { var subset = oldList[subsetId]; subset.dataset.emit_itemsChanged({ deleted: [sourceObject] }); if (!--memberMap[subsetId]) { delete memberMap[subsetId]; deleted.push(subset); } } if (delta = getDelta(inserted, deleted)) this.emit_itemsChanged(delta); }; var CLOUD_SOURCE_HANDLER = { itemsChanged: function (dataset, delta) { var sourceMap = this.sourceMap_; var memberMap = this.members_; var updateHandler = this.ruleEvents; var array; var subset; var subsetId; var inserted = []; var deleted = []; setAccumulateState(true); if (array = delta.inserted) for (var i = 0, sourceObject; sourceObject = array[i]; i++) { var list = this.rule(sourceObject); var sourceObjectInfo = { object: sourceObject, list: {} }; sourceMap[sourceObject.basisObjectId] = sourceObjectInfo; if (Array.isArray(list)) for (var j = 0, dupFilter = {}; j < list.length; j++) { subset = this.keyMap.get(list[j], true); if (subset && !dupFilter[subset.basisObjectId]) { subsetId = subset.basisObjectId; dupFilter[subsetId] = true; sourceObjectInfo.list[subsetId] = subset; subset.dataset.emit_itemsChanged({ inserted: [sourceObject] }); if (!memberMap[subsetId]) { inserted.push(subset); memberMap[subsetId] = 1; } else memberMap[subsetId]++; } } if (updateHandler) sourceObject.addHandler(updateHandler, this); } if (array = delta.deleted) for (var i = 0, sourceObject; sourceObject = array[i]; i++) { var sourceObjectId = sourceObject.basisObjectId; var list = sourceMap[sourceObjectId].list; delete sourceMap[sourceObjectId]; for (var subsetId in list) { subset = list[subsetId]; subset.dataset.emit_itemsChanged({ deleted: [sourceObject] }); if (!--memberMap[subsetId]) { delete memberMap[subsetId]; deleted.push(subset); } } if (updateHandler) sourceObject.removeHandler(updateHandler, this); } setAccumulateState(false); if (delta = getDelta(inserted, deleted)) this.emit_itemsChanged(delta); } }; module.exports = SourceDataset.subclass({ className: "basis.data.dataset.Cloud", subsetClass: ReadOnlyDataset, subsetWrapperClass: DatasetWrapper, rule: basis.getter($undef), ruleEvents: createRuleEvents(CLOUD_SOURCEOBJECT_UPDATE, "update"), keyMap: null, map: $self, listen: { source: CLOUD_SOURCE_HANDLER }, init: function () { if (!this.keyMap || this.keyMap instanceof KeyObjectMap == false) this.keyMap = createKeyMap(this.keyMap, this.rule, this.subsetWrapperClass, this.subsetClass); SourceDataset.prototype.init.call(this); }, getSubset: function (data, autocreate) { return this.keyMap.get(data, autocreate); }, destroy: function () { SourceDataset.prototype.destroy.call(this); this.keyMap.destroy(); this.keyMap = null; } }); }, "1s.js": function (exports, module, basis, global, __filename, __dirname, require, resource, asset) { var values = basis.object.values; var $undef = basis.fn.$undef; var arrayFrom = basis.array.from; var createEvent = basis.require("./3.js").create; var DataObject = basis.require("./g.js").Object; var isEqual = basis.require("./g.js").isEqual; var ReadOnlyDataset = basis.require("./g.js").ReadOnlyDataset; var SourceDataset = basis.require("./1l.js"); var createRuleEvents = basis.require("./1k.js"); var getDelta = basis.require("./1j.js"); var EXTRACT_SOURCEOBJECT_UPDATE = function (sourceObject) { var sourceObjectInfo = this.sourceMap_[sourceObject.basisObjectId]; var newValue = this.rule(sourceObject) || null; var oldValue = sourceObjectInfo.value; var inserted; var deleted; var delta; if (isEqual(newValue, oldValue)) return; if (newValue instanceof DataObject || newValue instanceof ReadOnlyDataset) inserted = addToExtract(this, newValue, sourceObject); if (oldValue) deleted = removeFromExtract(this, oldValue, sourceObject); sourceObjectInfo.value = newValue; if (delta = getDelta(inserted, deleted)) this.emit_itemsChanged(delta); }; var EXTRACT_DATASET_ITEMSCHANGED = function (dataset, delta) { var inserted = delta.inserted; var deleted = delta.deleted; var delta; if (inserted) inserted = addToExtract(this, inserted, dataset); if (deleted) deleted = removeFromExtract(this, deleted, dataset); if (delta = getDelta(inserted, deleted)) this.emit_itemsChanged(delta); }; var EXTRACT_DATASET_HANDLER = { itemsChanged: EXTRACT_DATASET_ITEMSCHANGED, destroy: function (dataset) { var sourceMap = this.sourceMap_; for (var cursor = sourceMap[dataset.basisObjectId]; cursor = cursor.ref;) sourceMap[cursor.object.basisObjectId].value = null; delete sourceMap[dataset.basisObjectId]; } }; function hasExtractSourceRef(extract, object, marker) { var sourceObjectInfo = extract.sourceMap_[object.basisObjectId]; if (sourceObjectInfo && sourceObjectInfo.visited !== marker) { for (var cursor = sourceObjectInfo; cursor = cursor.ref;) if (cursor.object === extract.source) return true; sourceObjectInfo.visited = marker; for (var cursor = sourceObjectInfo; cursor = cursor.ref;) if (hasExtractSourceRef(extract, cursor.object, marker || {})) return true; } } function addToExtract(extract, items, ref) { var sourceMap = extract.sourceMap_; var members = extract.members_; var queue = arrayFrom(items); var inserted = []; for (var i = 0; i < queue.length; i++) { var item = queue[i]; var sourceObjectId = item.basisObjectId; if (!sourceObjectId) { ref = item.ref; item = item.object; sourceObjectId = item.basisObjectId; } var sourceObjectInfo = sourceMap[sourceObjectId]; if (sourceObjectInfo) { sourceObjectInfo.ref = { object: ref, ref: sourceObjectInfo.ref }; } else { sourceObjectInfo = sourceMap[sourceObjectId] = { source: item, ref: { object: ref, ref: null }, visited: null, value: null }; if (item instanceof DataObject) { var value = extract.rule(item) || null; if (value instanceof DataObject || value instanceof ReadOnlyDataset) { sourceObjectInfo.value = value; queue.push({ object: value, ref: item }); } members[sourceObjectId] = sourceObjectInfo; inserted.push(item); if (extract.ruleEvents) item.addHandler(extract.ruleEvents, extract); } else { item.addHandler(EXTRACT_DATASET_HANDLER, extract); for (var j = 0, datasetItems = item.getItems(); j < datasetItems.length; j++) queue.push({ object: datasetItems[j], ref: item }); } } } return inserted; } function removeFromExtract(extract, items, ref) { var sourceMap = extract.sourceMap_; var members = extract.members_; var queue = arrayFrom(items); var deleted = []; for (var i = 0; i < queue.length; i++) { var item = queue[i]; var sourceObjectId = item.basisObjectId; if (!sourceObjectId) { ref = item.ref; item = item.object; sourceObjectId = item.basisObjectId; } var sourceObjectInfo = sourceMap[sourceObjectId]; var sourceObjectValue = sourceObjectInfo.value; for (var cursor = sourceObjectInfo, prevCursor = sourceObjectInfo; cursor = cursor.ref;) { if (isEqual(cursor.object, ref)) { prevCursor.ref = cursor.ref; break; } prevCursor = cursor; } if (!sourceObjectInfo.ref) { if (item instanceof DataObject) { delete members[sourceObjectId]; deleted.push(item); if (extract.ruleEvents) item.removeHandler(extract.ruleEvents, extract); if (sourceObjectValue) queue.push({ object: sourceObjectValue, ref: item }); } else { item.removeHandler(EXTRACT_DATASET_HANDLER, extract); for (var j = 0, datasetItems = item.getItems(); j < datasetItems.length; j++) queue.push({ object: datasetItems[j], ref: item }); } delete sourceMap[sourceObjectId]; } else { if (sourceObjectValue && !hasExtractSourceRef(extract, item)) { sourceObjectInfo.value = null; queue.push({ object: sourceObjectValue, ref: item }); } } } return deleted; } module.exports = SourceDataset.subclass({ className: "basis.data.dataset.Extract", propertyDescriptors: { rule: "ruleChanged" }, rule: basis.getter($undef), emit_ruleChanged: createEvent("ruleChanged", "oldRule"), ruleEvents: createRuleEvents(EXTRACT_SOURCEOBJECT_UPDATE, "update"), listen: { source: { itemsChanged: EXTRACT_DATASET_ITEMSCHANGED } }, setRule: function (rule) { rule = basis.getter(rule || $undef); if (this.rule !== rule) { var oldRule = this.rule; this.rule = rule; this.emit_ruleChanged(oldRule); return this.applyRule(); } }, applyRule: function () { var insertedMap = {}; var deletedMap = {}; var delta; for (var key in this.sourceMap_) { var sourceObjectInfo = this.sourceMap_[key]; var sourceObject = sourceObjectInfo.source; if (sourceObject instanceof DataObject) { var newValue = this.rule(sourceObject) || null; var oldValue = sourceObjectInfo.value; if (isEqual(newValue, oldValue)) continue; if (newValue instanceof DataObject || newValue instanceof ReadOnlyDataset) { var inserted = addToExtract(this, newValue, sourceObject); for (var i = 0; i < inserted.length; i++) { var item = inserted[i]; var id = item.basisObjectId; if (deletedMap[id]) delete deletedMap[id]; else insertedMap[id] = item; } } if (oldValue) { var deleted = removeFromExtract(this, oldValue, sourceObject); for (var i = 0; i < deleted.length; i++) { var item = deleted[i]; var id = item.basisObjectId; if (insertedMap[id]) delete insertedMap[id]; else deletedMap[id] = item; } } sourceObjectInfo.value = newValue; } } if (delta = getDelta(values(insertedMap), values(deletedMap))) this.emit_itemsChanged(delta); return delta; } }); }, "1t.js": function (exports, module, basis, global, __filename, __dirname, require, resource, asset) { var MapFilter = basis.require("./1o.js"); module.exports = MapFilter.subclass({ className: "basis.data.dataset.Filter", filter: function (object) { return !this.rule(object); } }); }, "1u.js": function (exports, module, basis, global, __filename, __dirname, require, resource, asset) { var $true = basis.fn.$true; var values = basis.object.values; var objectSlice = basis.object.slice; var createEvent = basis.require("./3.js").create; var Value = basis.require("./g.js").Value; var createRuleEvents = basis.require("./1k.js"); var getDelta = basis.require("./1j.js"); var SourceDataset = basis.require("./1l.js"); function nanToUndefined(value) { return value !== value ? undefined : value; } function binarySearchPos(array, map) { if (!array.length) return 0; var value = map.value; var id = map.object.basisObjectId; var cmpValue; var cmpId; var pos; var item; var l = 0; var r = array.length - 1; do { pos = l + r >> 1; item = array[pos]; cmpValue = item.value; if (value < cmpValue) r = pos - 1; else if (value > cmpValue) l = pos + 1; else { cmpId = item.object.basisObjectId; if (id < cmpId) r = pos - 1; else if (id > cmpId) l = pos + 1; else return pos; } } while (l <= r); return pos + (cmpValue == value ? cmpId < id : cmpValue < value); } var SLICE_SOURCEOBJECT_UPDATE = function (sourceObject) { var sourceObjectInfo = this.sourceMap_[sourceObject.basisObjectId]; var newValue = nanToUndefined(this.rule(sourceObject)); var index = this.index_; if (newValue !== sourceObjectInfo.value) { var pos = binarySearchPos(index, sourceObjectInfo); var prev = index[pos - 1]; var next = index[pos + 1]; sourceObjectInfo.value = newValue; if (prev && (prev.value > newValue || prev.value == newValue && prev.object.basisObjectId > sourceObjectInfo.object.basisObjectId) || next && (next.value < newValue || next.value == newValue && next.object.basisObjectId < sourceObjectInfo.object.basisObjectId)) { index.splice(pos, 1); index.splice(binarySearchPos(index, sourceObjectInfo), 0, sourceObjectInfo); this.applyRule(); } } }; function sliceIndexSort(a, b) { return +(a.value > b.value) || -(a.value < b.value) || a.object.basisObjectId - b.object.basisObjectId; } var SLICE_SOURCE_HANDLER = { itemsChanged: function (source, delta) { var sourceMap = this.sourceMap_; var index = this.index_; var updateHandler = this.ruleEvents; var dropIndex = false; var buildIndex = false; var sourceObjectInfo; var inserted = delta.inserted; var deleted = delta.deleted; if (deleted) { if (deleted.length > index.length - deleted.length) { dropIndex = true; buildIndex = deleted.length != index.length; index.length = 0; } for (var i = 0, sourceObject; sourceObject = deleted[i]; i++) { if (!dropIndex) { sourceObjectInfo = sourceMap[sourceObject.basisObjectId]; index.splice(binarySearchPos(index, sourceObjectInfo), 1); } delete sourceMap[sourceObject.basisObjectId]; if (updateHandler) sourceObject.removeHandler(updateHandler, this); } if (buildIndex) for (var key in sourceMap) { sourceObjectInfo = sourceMap[key]; index.splice(binarySearchPos(index, sourceObjectInfo), 0, sourceObjectInfo); } } if (inserted) { buildIndex = !index.length; for (var i = 0, sourceObject; sourceObject = inserted[i]; i++) { sourceObjectInfo = { object: sourceObject, value: nanToUndefined(this.rule(sourceObject)) }; sourceMap[sourceObject.basisObjectId] = sourceObjectInfo; if (!buildIndex) index.splice(binarySearchPos(index, sourceObjectInfo), 0, sourceObjectInfo); else index.push(sourceObjectInfo); if (updateHandler) sourceObject.addHandler(updateHandler, this); } if (buildIndex) index.sort(sliceIndexSort); } this.applyRule(); } }; module.exports = SourceDataset.subclass({ className: "basis.data.dataset.Slice", propertyDescriptors: { limit: "rangeChanged", offset: "rangeChanged", orderDesc: "ruleChanged", rule: "ruleChanged" }, rule: basis.getter($true), emit_ruleChanged: createEvent("ruleChanged", "oldRule", "oldOrderDesc"), ruleEvents: createRuleEvents(SLICE_SOURCEOBJECT_UPDATE, "update"), index_: null, left_: null, right_: null, orderDesc: false, offset: 0, limit: 10, listen: { source: SLICE_SOURCE_HANDLER }, emit_rangeChanged: createEvent("rangeChanged", "oldOffset", "oldLimit"), init: function () { this.index_ = []; SourceDataset.prototype.init.call(this); }, setRange: function (offset, limit) { var oldOffset = this.offset; var oldLimit = this.limit; var delta = false; if (oldOffset != offset || oldLimit != limit) { this.offset = offset; this.limit = limit; delta = this.applyRule(); this.emit_rangeChanged(oldOffset, oldLimit); } return delta; }, setOffset: function (offset) { return this.setRange(offset, this.limit); }, setLimit: function (limit) { return this.setRange(this.offset, limit); }, setRule: function (rule, orderDesc) { rule = basis.getter(rule || $true); orderDesc = !!orderDesc; if (this.rule != rule || this.orderDesc != orderDesc) { var oldRule = this.rule; var oldOrderDesc = this.orderDesc; if (this.rule != rule) { var index = this.index_; for (var i = 0; i < index.length; i++) index[i].value = nanToUndefined(rule(index[i].object)); index.sort(sliceIndexSort); this.rule = rule; } this.orderDesc = orderDesc; this.rule = rule; this.emit_ruleChanged(oldRule, oldOrderDesc); return this.applyRule(); } }, applyRule: function () { var start = this.offset; var end = start + this.limit; if (this.orderDesc) { start = this.index_.length - end; end = start + this.limit; } var curSet = objectSlice(this.members_); var newSet = this.index_.slice(Math.max(0, start), Math.max(0, end)); var inserted = []; var delta; for (var i = 0, item; item = newSet[i]; i++) { var objectId = item.object.basisObjectId; if (curSet[objectId]) delete curSet[objectId]; else { inserted.push(item.object); this.members_[objectId] = item.object; } } for (var objectId in curSet) delete this.members_[objectId]; if (this.left_) for (var offset in this.left_) { var item = this.index_[this.orderDesc ? end + Number(offset) - 1 : start - Number(offset)]; this.left_[offset].set(item ? item.object : null); } if (this.right_) for (var offset in this.right_) { var item = this.index_[this.orderDesc ? start - Number(offset) : end + Number(offset) - 1]; this.right_[offset].set(item ? item.object : null); } if (delta = getDelta(inserted, values(curSet))) this.emit_itemsChanged(delta); return delta; }, left: function (offset) { offset = parseInt(offset, 10) || 0; if (!this.left_) this.left_ = {}; var value = this.left_[offset]; if (!value) { var start = this.offset; var end = start + this.limit; if (this.orderDesc) { start = this.index_.length - end; end = start + this.limit; } var item = this.index_[this.orderDesc ? end + offset - 1 : start - offset]; value = this.left_[offset] = new Value({ value: item ? item.object : null }); } return value; }, right: function (offset) { offset = parseInt(offset, 10) || 0; if (!this.right_) this.right_ = {}; var value = this.right_[offset]; if (!value) { var start = this.offset; var end = start + this.limit; if (this.orderDesc) { start = this.index_.length - end; end = start + this.limit; } var item = this.index_[this.orderDesc ? start - offset : end + offset - 1]; value = this.right_[offset] = new Value({ value: item ? item.object : null }); } return value; }, destroy: function () { SourceDataset.prototype.destroy.call(this); if (this.left_) { for (var offset in this.left_) this.left_[offset].destroy(); this.left_ = null; } if (this.right_) { for (var offset in this.right_) this.right_[offset].destroy(); this.right_ = null; } this.index_ = null; } }); }, "o.js": function (exports, module, basis, global, __filename, __dirname, require, resource, asset) { var ObjectSet = basis.require("./1v.js"); var Expression = basis.require("./1w.js"); module.exports = { ObjectSet: ObjectSet, Expression: Expression, expression: Expression.create }; }, "1v.js": function (exports, module, basis, global, __filename, __dirname, require, resource, asset) { var cleaner = basis.cleaner; var basisData = basis.require("./g.js"); var AbstractData = basisData.AbstractData; var Value = basisData.Value; var STATE = basisData.STATE; var OBJECTSET_STATE_PRIORITY = STATE.priority; var OBJECTSET_HANDLER = { stateChanged: function () { this.fire(false, true); }, update: function () { this.fire(true); }, change: function () { this.fire(true); }, destroy: function (object) { this.remove(object); } }; var updateQueue = basis.asap.schedule(function (object) { object.update(); }); module.exports = Value.subclass({ className: "basis.data.value.ObjectSet", objects: null, value: 0, valueChanged_: false, calculateValue: function () { return this.value + 1; }, calculateOnInit: false, statePriority: OBJECTSET_STATE_PRIORITY, stateChanged_: true, init: function () { Value.prototype.init.call(this); var objects = this.objects; this.objects = []; if (objects && Array.isArray(objects)) { this.lock(); this.add.apply(this, objects); this.unlock(); } this.valueChanged_ = this.stateChanged_ = !!this.calculateOnInit; this.update(); }, add: function () { for (var i = 0, len = arguments.length; i < len; i++) { var object = arguments[i]; if (object instanceof AbstractData) { if (basis.array.add(this.objects, object)) object.addHandler(OBJECTSET_HANDLER, this); } else { basis.dev.warn(this.constructor.className + "#add: Instance of AbstractData required"); } } this.fire(true, true); }, remove: function (object) { if (basis.array.remove(this.objects, object)) object.removeHandler(OBJECTSET_HANDLER, this); this.fire(true, true); }, clear: function () { for (var i = 0, object; object = this.objects[i]; i++) object.removeHandler(OBJECTSET_HANDLER, this); this.objects.length = 0; this.fire(true, true); }, fire: function (valueChanged, stateChanged) { if (!this.locked) { this.valueChanged_ = this.valueChanged_ || !!valueChanged; this.stateChanged_ = this.stateChanged_ || !!stateChanged; if (this.valueChanged_ || this.stateChanged_) updateQueue.add(this); } }, lock: function () { this.locked = true; }, unlock: function () { this.locked = false; }, update: function () { var valueChanged = this.valueChanged_; var stateChanged = this.stateChanged_; this.valueChanged_ = false; this.stateChanged_ = false; updateQueue.remove(this); if (!cleaner.globalDestroy) { if (valueChanged) this.set(this.calculateValue()); if (stateChanged) { var len = this.objects.length; if (!len) this.setState(STATE.UNDEFINED); else { var maxWeight = -2; var curObject; for (var i = 0; i < len; i++) { var object = this.objects[i]; var weight = this.statePriority.indexOf(String(object.state)); if (weight > maxWeight) { curObject = object; maxWeight = weight; } } if (curObject) this.setState(curObject.state, curObject.state.data); } } } }, destroy: function () { this.lock(); this.clear(); updateQueue.remove(this); Value.prototype.destroy.call(this); } }); }, "1w.js": function (exports, module, basis, global, __filename, __dirname, require, resource, asset) { var basisData = basis.require("./g.js"); var Value = basisData.Value; var ReadOnlyValue = basisData.ReadOnlyValue; var CLASSNAME = "basis.data.Expression"; var EXPRESSION_SKIP_INIT = {}; var EXPRESSION_BBVALUE_HANDLER = function () { schedule.add(this); }; var EXPRESSION_BBVALUE_DESTROY_HANDLER = function () { this.destroy(); }; var BBVALUE_GETTER = function (value) { return value.bindingBridge.get(value); }; var schedule = basis.asap.schedule(function (expression) { expression.update(); }); function initExpression() { var count = arguments.length - 1; var calc = arguments[count]; var values = new Array(count); if (typeof calc != "function") throw new Error(CLASSNAME + ": Last argument of constructor must be a function"); for (var i = 0; i < count; i++) { var value = values[i] = arguments[i]; if (!value.bindingBridge) throw new Error(CLASSNAME + ": bb-value required"); value.bindingBridge.attach(value, EXPRESSION_BBVALUE_HANDLER, this, EXPRESSION_BBVALUE_DESTROY_HANDLER); } this.calc_ = calc; this.values_ = values; this.update(); basis.dev.setInfo(this, "sourceInfo", { type: "Expression", source: values, transform: calc }); return this; } var Expression = ReadOnlyValue.subclass({ className: CLASSNAME, calc_: null, values_: null, extendConstructor_: false, init: function (skip) { ReadOnlyValue.prototype.init.call(this); if (skip === EXPRESSION_SKIP_INIT) return; initExpression.apply(this, arguments); }, update: function () { schedule.remove(this); Value.prototype.set.call(this, this.calc_.apply(null, this.values_.map(BBVALUE_GETTER))); }, destroy: function () { schedule.remove(this); for (var i = 0, value; value = this.values_[i]; i++) value.bindingBridge.detach(value, EXPRESSION_BBVALUE_HANDLER, this); ReadOnlyValue.prototype.destroy.call(this); } }); Expression.create = function createExpression() { return initExpression.apply(new Expression(EXPRESSION_SKIP_INIT), arguments); }; module.exports = Expression; }, "p.js": function (exports, module, basis, global, __filename, __dirname, require, resource, asset) { var Index = basis.require("./1x.js"); var VectorIndex = basis.require("./1y.js"); var IndexWrapper = basis.require("./1z.js"); var IndexMap = basis.require("./20.js"); var IndexedCalc = basis.require("./21.js"); var createIndexConstructor = basis.require("./22.js"); var Count = basis.require("./23.js"); var Sum = basis.require("./24.js"); var Avg = basis.require("./25.js"); var Min = basis.require("./26.js"); var Max = basis.require("./27.js"); var Distinct = basis.require("./28.js"); var count = createIndexConstructor(Count, basis.fn.$true); var sum = createIndexConstructor(Sum); var avg = createIndexConstructor(Avg); var min = createIndexConstructor(Min); var max = createIndexConstructor(Max); var distinct = createIndexConstructor(Distinct); function percentOfRange(events, getter) { var minIndex = IndexedCalc.getId("min"); var maxIndex = IndexedCalc.getId("max"); var indexes = {}; indexes[minIndex] = min(events, getter); indexes[maxIndex] = max(events, getter); getter = basis.getter(getter || events); return new IndexedCalc(indexes, function (data, indexes, object) { return (getter(object) - indexes[minIndex]) / (indexes[maxIndex] - indexes[minIndex]); }); } function percentOfMax(events, getter) { var maxIndex = IndexedCalc.getId("max"); var indexes = {}; indexes[maxIndex] = max(events, getter); getter = basis.getter(getter || events); return new IndexedCalc(indexes, function (data, indexes, object) { return getter(object) / indexes[maxIndex]; }); } function percentOfSum(events, getter) { var sumIndex = IndexedCalc.getId("sum"); var indexes = {}; indexes[sumIndex] = sum(events, getter); getter = basis.getter(getter || events); return new IndexedCalc(indexes, function (data, indexes, object) { return getter(object) / indexes[sumIndex]; }); } module.exports = { Index: Index, VectorIndex: VectorIndex, IndexWrapper: IndexWrapper, getDatasetIndex: Index.getDatasetIndex, removeDatasetIndex: Index.removeDatasetIndex, Count: Count, Sum: Sum, Avg: Avg, Min: Min, Max: Max, Distinct: Distinct, createIndexConstructor: createIndexConstructor, count: count, sum: sum, avg: avg, max: max, min: min, distinct: distinct, CalcIndexPreset: IndexedCalc, percentOfRange: percentOfRange, percentOfMax: percentOfMax, percentOfSum: percentOfSum, IndexMap: IndexMap }; }, "1x.js": function (exports, module, basis, global, __filename, __dirname, require, resource, asset) { var devWrap = basis.require("./g.js").devWrap; var Value = basis.require("./g.js").Value; var Index = Value.subclass({ className: "basis.data.index.Index", propertyDescriptors: { explicit: false, wrapperCount: false, updateEvents: false }, explicit: false, wrapperCount: 0, indexCache_: null, valueGetter: basis.fn.$null, updateEvents: {}, value: 0, setNullOnEmitterDestroy: false, init: function () { this.indexCache_ = {}; Value.prototype.init.call(this); }, add_: function (value) { }, remove_: function (value) { }, update_: function (newValue, oldValue) { }, normalize: function (value) { return Number(value) || 0; }, destroy: function () { Value.prototype.destroy.call(this); this.indexCache_ = null; } }); var datasetIndexes = {}; function applyIndexDelta(index, inserted, deleted) { var indexCache = index.indexCache_; var objectId; index.lock(); if (inserted) for (var i = 0, object; object = inserted[i++];) { var newValue = index.normalize(index.valueGetter(object)); indexCache[object.basisObjectId] = newValue; index.add_(newValue); } if (deleted) for (var i = 0, object; object = deleted[i++];) { objectId = object.basisObjectId; index.remove_(indexCache[objectId]); delete indexCache[objectId]; } index.unlock(); } var DATASET_INDEX_HANDLER = { destroy: function (object) { removeDatasetIndex(this, object); } }; var DATASET_WITH_INDEX_HANDLER = { itemsChanged: function (object, delta) { var array; if (array = delta.inserted) for (var i = 0; i < array.length; i++) array[i].addHandler(ITEM_INDEX_HANDLER, this); if (array = delta.deleted) for (var i = 0; i < array.length; i++) array[i].removeHandler(ITEM_INDEX_HANDLER, this); var indexes = datasetIndexes[this.basisObjectId]; for (var indexId in indexes) applyIndexDelta(indexes[indexId], delta.inserted, delta.deleted); }, destroy: function () { var indexes = datasetIndexes[this.basisObjectId]; for (var indexId in indexes) { var index = indexes[indexId]; removeDatasetIndex(this, index); index.destroy(); } } }; var ITEM_INDEX_HANDLER = { "*": function (event) { var eventType = event.type; var object = event.sender; var objectId = object.basisObjectId; var indexes = datasetIndexes[this.basisObjectId]; var oldValue; var newValue; var index; for (var indexId in indexes) { index = indexes[indexId]; if (index.updateEvents[eventType]) { oldValue = index.indexCache_[objectId]; newValue = index.normalize(index.valueGetter(object)); if (newValue !== oldValue) { index.update_(newValue, oldValue); index.indexCache_[objectId] = newValue; } } } } }; function getDatasetIndex(dataset, IndexClass) { if (!IndexClass || IndexClass.prototype instanceof Index === false) throw "IndexClass must be an instance of IndexClass"; var datasetId = dataset.basisObjectId; var indexes = datasetIndexes[datasetId]; if (!indexes) { indexes = datasetIndexes[datasetId] = {}; dataset.addHandler(DATASET_WITH_INDEX_HANDLER); DATASET_WITH_INDEX_HANDLER.itemsChanged.call(dataset, dataset, { inserted: dataset.getItems() }); } var indexId = IndexClass.indexId; var index = indexes[indexId]; if (!index) { index = new IndexClass(); index.addHandler(DATASET_INDEX_HANDLER, dataset); basis.dev.setInfo(index, "sourceInfo", { type: index.indexName, source: dataset, events: Object.keys(index.updateEvents), transform: index.valueGetter }); indexes[indexId] = index; applyIndexDelta(index, dataset.getItems()); } else index = devWrap(index); return index; } function removeDatasetIndex(dataset, index) { var indexes = datasetIndexes[dataset.basisObjectId]; if (indexes && indexes[index.indexId]) { delete indexes[index.indexId]; index.removeHandler(DATASET_INDEX_HANDLER, dataset); for (var index in indexes) return; dataset.removeHandler(DATASET_WITH_INDEX_HANDLER); DATASET_WITH_INDEX_HANDLER.itemsChanged.call(dataset, dataset, { deleted: dataset.getItems() }); delete datasetIndexes[dataset.basisObjectId]; } } ; Index.getDatasetIndex = getDatasetIndex; Index.removeDatasetIndex = removeDatasetIndex; module.exports = Index; }, "1y.js": function (exports, module, basis, global, __filename, __dirname, require, resource, asset) { var Index = basis.require("./1x.js"); function binarySearchPos(array, value) { if (!array.length) return 0; var pos; var cmpValue; var l = 0; var r = array.length - 1; do { pos = l + r >> 1; cmpValue = array[pos] || 0; if (value < cmpValue) r = pos - 1; else if (value > cmpValue) l = pos + 1; else return value == cmpValue ? pos : 0; } while (l <= r); return pos + (cmpValue < value); } module.exports = Index.subclass({ className: "basis.data.index.VectorIndex", vectorGetter: basis.fn.$null, vector_: null, value: undefined, init: function () { this.vector_ = []; Index.prototype.init.call(this); }, add_: function (value) { if (value !== null) { this.vector_.splice(binarySearchPos(this.vector_, value), 0, value); this.value = this.vectorGetter(this.vector_); } }, remove_: function (value) { if (value !== null) { this.vector_.splice(binarySearchPos(this.vector_, value), 1); this.value = this.vectorGetter(this.vector_); } }, update_: function (newValue, oldValue) { if (oldValue !== null) this.vector_.splice(binarySearchPos(this.vector_, oldValue), 1); if (newValue !== null) this.vector_.splice(binarySearchPos(this.vector_, newValue), 0, newValue); this.set(this.vectorGetter(this.vector_)); }, normalize: function (value) { return typeof value == "string" || typeof value == "number" ? value : null; }, destroy: function () { Index.prototype.destroy.call(this); this.vector_ = null; } }); }, "1z.js": function (exports, module, basis, global, __filename, __dirname, require, resource, asset) { var Value = basis.require("./g.js").Value; var Index = basis.require("./1x.js"); var resolveDataset = basis.require("./g.js").resolveDataset; var INDEXWRAPPER_HANDLER = { destroy: function () { Value.prototype.set.call(this, this.initValue); this.index = null; } }; module.exports = Value.subclass({ className: "basis.data.index.IndexWrapper", extendConstructor_: false, source: null, sourceRA_: null, dataset: null, indexConstructor: null, index: null, init: function (source, indexConstructor) { this.source = source; this.indexConstructor = indexConstructor; this.value = indexConstructor.prototype.value; Value.prototype.init.call(this); source.bindingBridge.attach(source, basis.fn.$undef, this, this.destroy); this.setDataset(source); }, setDataset: function (source) { var oldDataset = this.dataset; var newDataset = resolveDataset(this, this.setDataset, source, "sourceRA_"); if (newDataset !== oldDataset) { var index = this.index; if (index) { index.removeHandler(INDEXWRAPPER_HANDLER, this); index.wrapperCount -= 1; if (!index.wrapperCount && !index.explicit) index.destroy(); else index.unlink(this, Value.prototype.set); } if (newDataset) { index = Index.getDatasetIndex(newDataset, this.indexConstructor); index.wrapperCount += 1; index.link(this, Value.prototype.set); index.addHandler(INDEXWRAPPER_HANDLER, this); } else { index = null; Value.prototype.set.call(this, this.initValue); } basis.dev.patchInfo(this, "sourceInfo", { type: "IndexWrapper", source: index, sourceTarget: source }); this.dataset = newDataset; this.index = index; } }, set: function () { basis.dev.warn(this.className + ": value can't be set as IndexWrapper is read only"); }, destroy: function () { this.source.bindingBridge.detach(this.source, basis.fn.$undef, this); this.setDataset(); Value.prototype.destroy.call(this); this.source = null; this.indexConstructor = null; } }); }, "20.js": function (exports, module, basis, global, __filename, __dirname, require, resource, asset) { var iterate = basis.object.iterate; var Value = basis.require("./g.js").Value; var DataObject = basis.require("./g.js").Object; var SourceDataset = basis.require("./n.js").SourceDataset; var createRuleEvents = basis.require("./n.js").createRuleEvents; var Index = basis.require("./1x.js"); var IndexWrapper = basis.require("./1z.js"); var IndexedCalc = basis.require("./21.js"); var indexMapRecalcShedule = basis.asap.schedule(function (indexMap) { indexMap.recalc(); }); var INDEXMAP_SOURCE_HANDLER = { itemsChanged: function (sender, delta) { var deleted = []; var array; if (array = delta.inserted) for (var i = 0; i < array.length; i++) { var sourceObject = array[i]; var sourceObjectId = sourceObject.basisObjectId; this.awaitToAdd_[sourceObjectId] = sourceObject; this.scheduleRecalc(); } if (array = delta.deleted) for (var i = 0; i < array.length; i++) { var sourceObject = array[i]; var sourceObjectId = sourceObject.basisObjectId; var memberInfo = this.sourceMap_[sourceObjectId]; if (memberInfo) { var member = memberInfo.member; deleted.push(member); if (this.listen.member) member.removeHandler(this.listen.member, this); if (this.recalcEvents) sourceObject.removeHandler(this.recalcEvents, this); delete this.sourceMap_[sourceObjectId]; } else { delete this.awaitToAdd_[sourceObjectId]; } } if (deleted.length) { this.emit_itemsChanged({ deleted: deleted }); for (var i = 0; i < deleted.length; i++) { var member = deleted[i]; member.source = null; member.destroy(); } } } }; module.exports = SourceDataset.subclass({ className: "basis.data.index.IndexMap", calcs: null, copyDataFromSource: true, indexes: null, indexValues: null, indexUpdated: false, awaitToAdd_: null, itemClass: DataObject, listen: { source: INDEXMAP_SOURCE_HANDLER }, recalcEvents: createRuleEvents(function (sender) { this.sourceMap_[sender.basisObjectId].updated = true; this.scheduleRecalc(); }, "update"), init: function () { var indexes = this.indexes; var calcs = this.calcs; this.calcs = {}; this.indexes = {}; this.indexValues = {}; this.awaitToAdd_ = {}; SourceDataset.prototype.init.call(this); iterate(indexes, this.addIndex, this); for (var name in calcs) { var calcCfg = calcs[name]; if (calcCfg instanceof IndexedCalc) { iterate(calcCfg.indexes, this.addIndex, this); calcCfg = calcCfg.calc; } this.calcs[name] = calcCfg; } this.recalc(); }, addIndex: function (key, IndexClass) { if (!IndexClass || IndexClass.prototype instanceof Index === false) { basis.dev.warn("basis.data.IndexMap#addIndex(): `IndexClass` should be subclass of `basis.data.index.Index`"); return; } if (this.indexes[key]) { basis.dev.warn("basis.data.IndexMap#addIndex(): Index `" + key + "` already exists"); return; } var index = new IndexWrapper(Value.from(this, "sourceChanged", "source"), IndexClass); this.indexes[key] = index; this.indexValues[key] = index.value; index.link(this, function (value) { this.indexValues[key] = value; this.indexUpdated = true; this.scheduleRecalc(); }); }, removeIndex: function (key) { var index = this.indexes[key]; if (index) { delete this.indexes[key]; delete this.indexValues[key]; index.destroy(); } }, lock: function () { for (var indexId in this.indexes) this.indexes[indexId].lock(); }, unlock: function () { for (var indexId in this.indexes) this.indexes[indexId].unlock(); }, scheduleRecalc: function () { indexMapRecalcShedule.add(this); }, recalc: function () { for (var id in this.sourceMap_) this.calcMember(this.sourceMap_[id]); var inserted = []; var items = this.awaitToAdd_; this.awaitToAdd_ = {}; for (var id in items) { var sourceObject = items[id]; var data = {}; var member; for (var calcName in this.calcs) data[calcName] = this.calcs[calcName](sourceObject.data, this.indexValues, sourceObject); if (this.copyDataFromSource) for (var key in sourceObject.data) if (!this.calcs.hasOwnProperty(key)) data[key] = sourceObject.data[key]; member = new this.itemClass({ source: sourceObject, data: data, update: sourceObject.update.bind(sourceObject) }); if (this.listen.member) member.addHandler(this.listen.member, this); if (this.recalcEvents) sourceObject.addHandler(this.recalcEvents, this); this.sourceMap_[id] = { sourceObject: sourceObject, member: member, updated: false }; inserted.push(member); } if (inserted.length) this.emit_itemsChanged({ inserted: inserted }); this.indexUpdated = false; indexMapRecalcShedule.remove(this); }, calcMember: function (memberInfo) { var member = memberInfo.member; if (memberInfo.updated || this.indexUpdated) { var sourceObject = memberInfo.sourceObject; var delta = {}; var newValue; var oldValue; var update; for (var calcName in this.calcs) { newValue = this.calcs[calcName](sourceObject.data, this.indexValues, sourceObject); oldValue = member.data[calcName]; if (oldValue !== newValue && (newValue === newValue || oldValue === oldValue)) { delta[calcName] = newValue; update = true; } } if (this.copyDataFromSource) { for (var key in sourceObject.data) if (!this.calcs.hasOwnProperty(key)) { newValue = sourceObject.data[key]; oldValue = member.data[key]; if (oldValue !== newValue && (newValue === newValue || oldValue === oldValue)) { delta[key] = newValue; update = true; } } for (var key in member.data) if (!this.calcs.hasOwnProperty(key) && !sourceObject.data.hasOwnProperty(key)) { delta[key] = undefined; update = true; } } if (update) this.itemClass.prototype.update.call(member, delta); memberInfo.updated = false; } }, getMember: function (sourceObject) { var memberInfo = sourceObject && this.sourceMap_[sourceObject.basisObjectId]; return memberInfo ? memberInfo.member : null; }, destroy: function () { iterate(this.indexes, this.removeIndex, this); SourceDataset.prototype.destroy.call(this); indexMapRecalcShedule.remove(this); this.awaitToAdd_ = null; this.calcs = null; this.indexes = null; this.indexValues = null; } }); }, "21.js": function (exports, module, basis, global, __filename, __dirname, require, resource, asset) { var calcIndexPresetSeed = 1; var IndexedCalc = function (indexes, calc) { this.indexes = indexes; this.calc = calc; }; IndexedCalc.getId = function (prefix) { return prefix + "_calc-index-preset-" + basis.number.lead(calcIndexPresetSeed++, 4); }; module.exports = IndexedCalc; }, "22.js": function (exports, module, basis, global, __filename, __dirname, require, resource, asset) { var Class = basis.Class; var ReadOnlyDataset = basis.require("./g.js").ReadOnlyDataset; var DatasetWrapper = basis.require("./g.js").DatasetWrapper; var chainValueFactory = basis.require("./g.js").chainValueFactory; var Index = basis.require("./1x.js"); var IndexWrapper = basis.require("./1z.js"); var PREFIX = "basisjsIndexConstructor" + basis.genUID(); var constructors = {}; var SOURCE_INDEXWRAPPER_HANDLER = { destroy: function (indexWrapper) { indexWrapper.source[this.indexId] = null; } }; function getIndexConstructor(BaseClass, events, getter) { if (!Class.isClass(BaseClass) || !BaseClass.isSubclassOf(Index)) throw "Wrong class for index constructor"; getter = basis.getter(getter); events = events || "update"; if (typeof events != "string") throw "Events must be a event names space separated string"; events = events.trim().split(" ").sort(); var indexId = PREFIX + [ BaseClass.basisClassId_, getter[basis.getter.ID], events ].join("_"); var indexConstructor = constructors[indexId]; if (!indexConstructor) { var events_ = {}; for (var i = 0; i < events.length; i++) events_[events[i]] = true; indexConstructor = constructors[indexId] = BaseClass.subclass({ indexName: BaseClass.className.split(".").pop(), indexId: indexId, updateEvents: events_, valueGetter: getter }); indexConstructor.indexId = indexId; } return indexConstructor; } module.exports = function createIndexConstructor(IndexClass, defGetter) { return function create(source, events, getter) { if (basis.fn.isFactory(source)) { var factory = source; return chainValueFactory(function (target) { return create(factory(target), events, getter, true); }); } if (typeof source == "function" || typeof source == "string") { getter = events; events = source; source = null; } if (!getter) { getter = events; events = ""; } var indexConstructor = getIndexConstructor(IndexClass, events, getter || defGetter); if (!source) return indexConstructor; if (source instanceof ReadOnlyDataset || source instanceof DatasetWrapper) { var index = Index.getDatasetIndex(source, indexConstructor); index.explicit = true; return index; } if (source.bindingBridge) { var indexWrapper = source[indexConstructor.indexId]; if (!indexWrapper) { indexWrapper = new IndexWrapper(source, indexConstructor); source[indexConstructor.indexId] = indexWrapper; indexWrapper.addHandler(SOURCE_INDEXWRAPPER_HANDLER, indexConstructor); } return indexWrapper; } basis.dev.warn(IndexClass.className + ": wrong source value for index (should be instance of basis.data.ReadOnlyDataset, basis.data.DatasetWrapper or bb-value)"); return null; }; }; }, "23.js": function (exports, module, basis, global, __filename, __dirname, require, resource, asset) { var Index = basis.require("./1x.js"); module.exports = Index.subclass({ className: "basis.data.index.Count", valueGetter: basis.fn.$true, add_: function (value) { this.value += value; }, remove_: function (value) { this.value -= value; }, normalize: function (value) { return Boolean(value); }, update_: function (newValue, oldValue) { this.set(this.value - Boolean(oldValue) + Boolean(newValue)); } }); }, "24.js": function (exports, module, basis, global, __filename, __dirname, require, resource, asset) { var Index = basis.require("./1x.js"); module.exports = Index.subclass({ className: "basis.data.index.Sum", add_: function (value) { this.value += value; }, remove_: function (value) { this.value -= value; }, update_: function (newValue, oldValue) { this.set(this.value - oldValue + newValue); } }); }, "25.js": function (exports, module, basis, global, __filename, __dirname, require, resource, asset) { var Index = basis.require("./1x.js"); module.exports = Index.subclass({ className: "basis.data.index.Avg", sum_: 0, count_: 0, add_: function (value) { this.sum_ += value; this.count_ += 1; this.value = this.sum_ / this.count_; }, remove_: function (value) { this.sum_ -= value; this.count_ -= 1; this.value = this.count_ ? this.sum_ / this.count_ : 0; }, update_: function (newValue, oldValue) { this.sum_ += newValue - oldValue; this.set(this.sum_ / this.count_); } }); }, "26.js": function (exports, module, basis, global, __filename, __dirname, require, resource, asset) { var VectorIndex = basis.require("./1y.js"); module.exports = VectorIndex.subclass({ className: "basis.data.index.Min", vectorGetter: function (vector) { return vector[0]; } }); }, "27.js": function (exports, module, basis, global, __filename, __dirname, require, resource, asset) { var VectorIndex = basis.require("./1y.js"); module.exports = VectorIndex.subclass({ className: "basis.data.index.Max", vectorGetter: function (vector) { return vector[vector.length - 1]; } }); }, "28.js": function (exports, module, basis, global, __filename, __dirname, require, resource, asset) { var Index = basis.require("./1x.js"); module.exports = Index.subclass({ className: "basis.data.index.Distinct", map_: null, init: function () { this.map_ = {}; Index.prototype.init.call(this); }, add_: function (value) { if (!this.map_.hasOwnProperty(value)) this.map_[value] = 0; if (++this.map_[value] == 1) this.value += 1; }, remove_: function (value) { if (--this.map_[value] == 0) this.value -= 1; }, update_: function (newValue, oldValue) { var delta = 0; if (!this.map_.hasOwnProperty(newValue)) this.map_[newValue] = 0; if (++this.map_[newValue] == 1) delta += 1; if (--this.map_[oldValue] == 0) delta -= 1; if (delta) this.set(this.value + delta); }, normalize: String, destroy: function () { Index.prototype.destroy.call(this); this.map_ = null; } }); }, "q.js": function (exports, module, basis, global, __filename, __dirname, require, resource, asset) { var namespace = "basis.data.object"; var createEvent = basis.require("./3.js").create; var SUBSCRIPTION = basis.require("./g.js").SUBSCRIPTION; var DataObject = basis.require("./g.js").Object; var resolveObject = basis.require("./g.js").resolveObject; SUBSCRIPTION.add("OBJECTSOURCE", { sourceChanged: function (object, name, oldSource) { if (oldSource) SUBSCRIPTION.unlink("sources", object, oldSource); if (object.sources[name]) SUBSCRIPTION.link("sources", object, object.sources[name]); } }, function (action, object) { var sources = object.sources; for (var name in sources) action("sources", object, sources[name]); }); var MERGE_SOURCE_HANDLER = { update: function (sender, senderDelta) { var fields = this.host.fields; var data = {}; if (this.name == fields.defaultSource) { for (var key in senderDelta) if (key in fields.fieldSource == false) data[key] = sender.data[key]; } else { for (var key in senderDelta) { var mergeKey = fields.fromNames[this.name][key]; if (mergeKey && this.host.fields.fieldSource[mergeKey] == this.name) data[mergeKey] = sender.data[key]; } } for (var key in data) return this.host.update(data); }, destroy: function () { this.host.setSource(this.name, null); } }; function generateDataGetter(nameMap) { return new Function("data", "return {" + basis.object.iterate(nameMap, function (ownName, sourceName) { ownName = ownName.replace(/"/g, "\\\""); sourceName = sourceName.replace(/"/g, "\\\""); return "\"" + ownName + "\": data[\"" + sourceName + "\"]"; }) + "}"); } var fieldsExtend = function (fields) { var sources = {}; var toNames = {}; var fromNames = {}; var result = { defaultSource: false, fieldSource: {}, toNames: toNames, fromNames: fromNames, sources: sources, __extend__: fieldsExtend }; if (fields["*"]) result.defaultSource = fields["*"]; for (var field in fields) { var def = fields[field].split(":"); var sourceName = def.shift(); var sourceField = def.length ? def.join(":") : field; if (sourceName == result.defaultSource) { if (field != "*") basis.dev.warn("basis.data.object.Merge: source `" + sourceName + "` has already defined for any field (star rule), definition this source for `" + field + "` field is superfluous (ignored)."); continue; } if (sourceName == "-" && sourceField != field) { basis.dev.warn("basis.data.object.Merge: custom field name can't be used for own properties, definition `" + field + ": \"" + fields[field] + "\"` ignored."); continue; } if (!toNames[sourceName]) { toNames[sourceName] = {}; fromNames[sourceName] = {}; } toNames[sourceName][field] = sourceField; fromNames[sourceName][sourceField] = field; result.fieldSource[field] = sourceName; } for (var sourceName in toNames) sources[sourceName] = generateDataGetter(toNames[sourceName]); if (result.defaultSource) sources[result.defaultSource] = function (data) { var res = {}; for (var key in data) if (key in result.fieldSource == false) res[key] = data[key]; return res; }; return result; }; function resolveSetSource(source) { this.host.setSource(this.name, source); } var Merge = DataObject.subclass({ className: namespace + ".Merge", subscribeTo: DataObject.prototype.subscribeTo + SUBSCRIPTION.OBJECTSOURCE, propertyDescriptors: { sources: { nested: true, events: "sourceChanged" } }, fields: fieldsExtend({ "*": "-" }), sources: null, sourcesContext_: null, emit_sourceChanged: createEvent("sourceChanged", "name", "oldSource"), delta_: null, init: function () { var data = this.data; var sources = this.sources; if (this.delegate) basis.dev.warn(this.constructor.className + " can't has a delegate"); this.delegate = null; if (data && "-" in this.fields.sources) { if (this.fields.defaultSource !== "-") { this.data = this.fields.sources["-"](data); } else { this.data = {}; for (var key in data) { var name = this.fields.fieldSource[key] || this.fields.defaultSource; if (name == "-") this.data[key] = data[key]; } } } else { this.data = {}; } DataObject.prototype.init.call(this); this.sources = {}; this.sourcesContext_ = {}; if (sources) this.setSources(sources); }, update: function (data) { if (this.delta_) { for (var key in data) { var sourceName = this.fields.fieldSource[key] || this.fields.defaultSource; if (!sourceName) { basis.dev.warn("Unknown source for field `" + key + "`"); continue; } var sourceKey = sourceName != this.fields.defaultSource ? this.fields.toNames[sourceName][key] : key; var value = this.sources[sourceName].data[sourceKey]; if (value !== this.data[key]) { if (key in this.delta_ == false) { this.delta_[key] = this.data[key]; } else { if (this.delta_[key] === value) delete this.delta_[key]; } this.data[key] = value; } } return; } var sourceDelta; var delta = {}; this.delta_ = delta; for (var key in data) { var sourceName = this.fields.fieldSource[key] || this.fields.defaultSource; if (!sourceName) { basis.dev.warn("Unknown source for field `" + key + "`"); continue; } if (sourceName == "-") { delta[key] = this.data[key]; this.data[key] = data[key]; continue; } if (this.sources[sourceName]) { var sourceKey = sourceName != this.fields.defaultSource ? this.fields.toNames[sourceName][key] : key; if (this.sources[sourceName].data[sourceKey] !== data[key]) { if (!sourceDelta) sourceDelta = {}; if (sourceName in sourceDelta == false) sourceDelta[sourceName] = {}; sourceDelta[sourceName][sourceKey] = data[key]; } else { if (this.data[key] !== data[key]) { delta[key] = this.data[key]; this.data[key] = data[key]; } } } } if (sourceDelta) for (var sourceName in sourceDelta) this.sources[sourceName].update(sourceDelta[sourceName]); this.delta_ = null; for (var key in delta) { this.emit_update(delta); return delta; } return false; }, setDelegate: function () { basis.dev.warn(namespace + ".Merge can't has a delegate"); }, setSource: function (name, source) { var oldSource = this.sources[name]; if (name in this.fields.sources == false) { basis.dev.warn("basis.data.object.Merge#setSource: can't set source with name `" + name + "` as not specified by fields configuration"); return; } if (name == "-") return; if (name in this.sourcesContext_ == false) this.sourcesContext_[name] = { host: this, name: name, adapter: null }; source = resolveObject(this.sourcesContext_[name], resolveSetSource, source, "adapter", this); if (oldSource !== source) { var listenHandler = this.listen["source:" + name]; if (oldSource) { if (listenHandler) oldSource.removeHandler(listenHandler, this); oldSource.removeHandler(MERGE_SOURCE_HANDLER, this.sourcesContext_[name]); } this.sources[name] = source; if (source) { source.addHandler(MERGE_SOURCE_HANDLER, this.sourcesContext_[name]); if (listenHandler) source.addHandler(listenHandler, this); var newData = this.fields.sources[name](source.data); if (this.fields.defaultSource == name) for (var key in this.data) if (!this.fields.fieldSource.hasOwnProperty(key) && !newData.hasOwnProperty(key)) newData[key] = undefined; this.update(newData); } this.emit_sourceChanged(name, oldSource); } }, setSources: function (sources) { if (!sources) sources = {}; for (var name in this.fields.sources) this.setSource(name, sources[name]); for (var name in sources) if (name in this.fields.sources == false) basis.dev.warn("basis.data.object.Merge#setSource: can't set source with name `" + name + "` as not specified by fields configuration"); }, destroy: function () { this.setSources(); this.sources = null; this.sourcesContext_ = null; DataObject.prototype.destroy.call(this); } }); module.exports = { Merge: Merge }; }, "r.js": function (exports, module, basis, global, __filename, __dirname, require, resource, asset) { var namespace = "basis.entity"; var Class = basis.Class; var hasOwnProperty = Object.prototype.hasOwnProperty; var keys = basis.object.keys; var extend = basis.object.extend; var $self = basis.fn.$self; var arrayFrom = basis.array.from; var basisEvent = basis.require("./3.js"); var Emitter = basisEvent.Emitter; var createEvent = basisEvent.create; var basisData = basis.require("./g.js"); var DataObject = basisData.Object; var Slot = basisData.Slot; var Dataset = basisData.Dataset; var ReadOnlyDataset = basisData.ReadOnlyDataset; var basisDataset = basis.require("./n.js"); var Filter = basisDataset.Filter; var Split = basisDataset.Split; var setAccumulateState = Dataset.setAccumulateState; var basisType = basis.require("./s.js"); var defineType = basisType.defineType; var getTypeByName = basisType.getTypeByName; var getTypeByNameIfDefined = basisType.getTypeByNameIfDefined; var validateScheme = basisType.validate; var nullableArray = basisType.array.nullable; var nullableDate = basisType.date.nullable; var typeEnum = basisType["enum"]; var NULL_INFO = {}; var entityTypes = []; var isKeyType = { string: true, number: true }; var NumericId = function (value) { return value == null || isNaN(value) ? null : Number(value); }; var NumberId = function (value) { return value == null || isNaN(value) ? null : Number(value); }; var IntId = function (value) { return value == null || isNaN(value) ? null : parseInt(value, 10); }; var StringId = function (value) { return value == null ? null : String(value); }; var untitledNames = {}; function getUntitledName(name) { untitledNames[name] = untitledNames[name] || 0; return name + untitledNames[name]++; } var namedIndexes = {}; var Index = Class(null, { className: namespace + ".Index", items: null, init: function () { this.items = {}; }, get: function (value, checkType) { var item = hasOwnProperty.call(this.items, value) && this.items[value]; if (item && (!checkType || item.entityType === checkType)) return item; }, add: function (value, newItem) { if (newItem) { var curItem = this.get(value); if (!curItem) { this.items[value] = newItem; return true; } if (curItem !== newItem) throw "basis.entity: Value `" + value + "` for index is already occupied"; } }, remove: function (value, item) { if (this.items[value] === item) { delete this.items[value]; return true; } }, destroy: function () { this.items = null; } }); function CalculateField() { var names = arrayFrom(arguments); var calcFn = names.pop(); var foo = names[0]; var bar = names[1]; var baz = names[2]; var result; if (typeof calcFn != "function") throw "Last argument for calculate field constructor must be a function"; switch (names.length) { case 0: result = function () { return calcFn(); }; break; case 1: result = function (delta, data, oldValue) { if (foo in delta) return calcFn(data[foo]); return oldValue; }; break; case 2: result = function (delta, data, oldValue) { if (foo in delta || bar in delta) return calcFn(data[foo], data[bar]); return oldValue; }; break; case 3: result = function (delta, data, oldValue) { if (foo in delta || bar in delta || baz in delta) return calcFn(data[foo], data[bar], data[baz]); return oldValue; }; break; default: result = function (delta, data, oldValue) { var changed = false; var args = []; for (var i = 0, name; name = names[i]; i++) { changed = changed || name in delta; args.push(data[name]); } if (changed) return calcFn.apply(null, args); return oldValue; }; } result = Function("calcFn", "names", "return " + result.toString().replace(/(foo|bar|baz)/g, function (m, w) { return "\"" + names[w == "foo" ? 0 : w == "bar" ? 1 : 2] + "\""; }).replace(/\[\"([^"]+)\"\]/g, ".$1"))(calcFn, names); result.args = names; result.calc = result; return result; } function ConcatStringField(name) { if (arguments.length == 1) return function (delta, data, oldValue) { if (name in delta) return data[name] != null ? String(data[name]) : null; return oldValue; }; return CalculateField.apply(null, arrayFrom(arguments).concat(function () { for (var i = arguments.length - 1; i >= 0; i--) if (arguments[i] == null) return null; return Array.prototype.join.call(arguments, "-"); })); } function getDelta(inserted, deleted) { var delta = {}; var result; if (inserted && inserted.length) result = delta.inserted = inserted; if (deleted && deleted.length) result = delta.deleted = deleted; if (result) return delta; } function setAndDestroyRemoved(data) { var itemsToDelete = basis.object.slice(this.items_); var itemsToInsert = {}; var autoInserted = []; var inserted = []; var deleted = []; var delta; var entity; data = arrayFrom(data); setAccumulateState(true); for (var i = 0, item; item = data[i]; i++) { entity = this.wrapper(item); if (entity) { if (itemsToDelete[entity.basisObjectId]) itemsToDelete[entity.basisObjectId] = null; else itemsToInsert[entity.basisObjectId] = entity; } } setAccumulateState(false); for (var basisObjectId in itemsToInsert) if (this.items_[basisObjectId]) autoInserted.push(itemsToInsert[basisObjectId]); else inserted.push(itemsToInsert[basisObjectId]); for (var basisObjectId in itemsToDelete) if (itemsToDelete[basisObjectId]) deleted.push(itemsToDelete[basisObjectId]); if (delta = getDelta(inserted, deleted)) { if (this instanceof EntitySet) { var listenHandler = this.listen.item; if (listenHandler) { if (delta.inserted) for (var i = 0, item; item = delta.inserted[i]; i++) item.addHandler(listenHandler, this); if (delta.deleted) for (var i = 0, item; item = delta.deleted[i]; i++) item.removeHandler(listenHandler, this); } } this.emit_itemsChanged(delta); } if (deleted.length) { setAccumulateState(true); for (var i = 0, item; item = deleted[i]; i++) item.destroy(); setAccumulateState(false); } inserted = inserted.concat(autoInserted); return inserted.length ? inserted : null; } ; var EntitySetMixin = function (super_) { return { name: null, wrapper: $self, setAndDestroyRemoved: setAndDestroyRemoved, destroy: function () { super_.destroy.call(this); this.name = null; this.wrapper = null; } }; }; var WRAPPED_MARKER = "wrapped" + basis.genUID(); var ENTITYSET_WRAP_METHOD = function (superClass, method) { return function (data) { if (data && !Array.isArray(data)) data = [data]; var needToWrap = data && !data[WRAPPED_MARKER]; if (needToWrap) { if (this.localId) { var items = this.getItems().slice(); data = data.map(function (newItem) { for (var i = 0; i < items.length; i++) if (this.localId(newItem, items[i])) return this.wrapper(newItem, items[i]); newItem = this.wrapper(newItem); items.push(newItem); return newItem; }, this); } else { data = data.map(this.wrapper); } data[WRAPPED_MARKER] = true; } var delta = superClass.prototype[method].call(this, data); if (needToWrap) { data[WRAPPED_MARKER] = false; if (this.localId && delta && delta.deleted) { setAccumulateState(true); for (var i = 0, item; item = delta.deleted[i]; i++) if (item.root) item.destroy(); setAccumulateState(false); } } return delta; }; }; var ENTITYSET_INIT_METHOD = function (superClass, name) { return function () { if (!this.name) this.name = getUntitledName(name); superClass.prototype.init.call(this); }; }; var ReadOnlyEntitySet = Class(ReadOnlyDataset, EntitySetMixin, { className: namespace + ".ReadOnlyEntitySet", init: ENTITYSET_INIT_METHOD(ReadOnlyDataset, "ReadOnlyEntitySet") }); var EntitySet = Class(Dataset, EntitySetMixin, { className: namespace + ".EntitySet", init: ENTITYSET_INIT_METHOD(Dataset, "EntitySet"), add: ENTITYSET_WRAP_METHOD(Dataset, "add"), remove: ENTITYSET_WRAP_METHOD(Dataset, "remove"), set: ENTITYSET_WRAP_METHOD(Dataset, "set"), setAndDestroyRemoved: function (data) { if (this.localId) return this.set(data); if (!this.itemCount) return this.add(data); if (this.localId && (!data || !data.length)) this.clear(); return setAndDestroyRemoved.call(this, data); }, clear: function () { var delta = Dataset.prototype.clear.call(this); if (this.localId && delta && delta.deleted) { setAccumulateState(true); for (var i = 0, item; item = delta.deleted[i]; i++) item.destroy(); setAccumulateState(false); } return delta; } }); var EntityCollection = Class(Filter, EntitySetMixin, { className: namespace + ".EntityCollection", init: ENTITYSET_INIT_METHOD(Filter, "EntityCollection") }); var EntityGrouping = Class(Split, { className: namespace + ".EntityGrouping", name: null, subsetClass: ReadOnlyEntitySet, init: ENTITYSET_INIT_METHOD(Split, "EntityGrouping"), getSubset: function (object, autocreate) { var group = Split.prototype.getSubset.call(this, object, autocreate); if (group && group.dataset) group.dataset.wrapper = this.wrapper; return group; } }); var EntitySetWrapper = function (wrapper, name, options) { function createLocalId(id) { if (typeof id == "string") return function (data, item) { return data[id] == item.data[id]; }; if (typeof id == "function") return id; } if (this instanceof EntitySetWrapper) { if (!wrapper) wrapper = $self; if (!name || getTypeByNameIfDefined(name)) { if (getTypeByNameIfDefined(name)) basis.dev.warn(namespace + ": Duplicate entity set type name `" + this.name + "`, name ignored"); name = getUntitledName("UntitledEntitySetType"); } var entitySetType = new EntitySetConstructor({ entitySetClass: { className: namespace + ".EntitySet(" + (typeof wrapper == "string" ? wrapper : (wrapper.type || wrapper).name || "UnknownType") + ")", name: "Set of {" + (typeof wrapper == "string" ? wrapper : (wrapper.type || wrapper).name || "UnknownType") + "}", wrapper: wrapper, localId: createLocalId(options && options.localId) } }); var EntitySetClass = entitySetType.entitySetClass; var result = function (data, entitySet) { if (data != null) { if (entitySet instanceof EntitySet == false) entitySet = entitySetType.createEntitySet(); entitySet.set(data instanceof Dataset ? data.getItems() : arrayFrom(data)); return entitySet; } else return null; }; if (typeof wrapper == "string") EntitySetClass.prototype.wrapper = getTypeByName(wrapper, EntitySetClass.prototype, "wrapper"); defineType(name, result); extend(result, { type: entitySetType, typeName: name, toString: function () { return name + "()"; }, reader: function (data) { if (Array.isArray(data)) { var wrapper = EntitySetClass.prototype.wrapper; return data.map(wrapper.reader || wrapper); } return data; }, extendClass: function (source) { EntitySetClass.extend.call(EntitySetClass, source); return result; }, extendReader: function (extReader) { var reader = result.reader; result.reader = function (data) { if (Array.isArray(data)) extReader(data); return reader(data); }; return result; }, entitySetType: entitySetType, extend: function () { basis.dev.warn("basis.entity: EntitySetType.extend() is deprecated, use EntitySetType.extendClass() instead."); return EntitySetClass.extend.apply(EntitySetClass, arguments); } }); basis.dev.warnPropertyAccess(result, "entitySetType", entitySetType, "basis.entity: EntitySetType.entitySetType is deprecated, use EntitySetType.type instead."); return result; } }; EntitySetWrapper.className = namespace + ".EntitySetWrapper"; var EntitySetConstructor = Class(null, { className: namespace + ".EntitySetConstructor", entitySetClass: EntitySet, extendConstructor_: true, createEntitySet: function () { return new this.entitySetClass(); } }); var EntityTypeWrapper = function (config) { if (this instanceof EntityTypeWrapper) { var result; if (config.singleton) result = function (data) { var entity = entityType.get(); if (entity) { if (data) entity.update(data); entity = basisData.devWrap(entity); } else entity = new EntityClass(data || {}); return entity; }; else result = function (data, entity) { if (data != null) { if (!entity || entity.entityType !== entityType) entity = null; if (data === entity || data.entityType === entityType) return data; var idValue; var idField = entityType.idField; if (isKeyType[typeof data]) { if (!idField) { if (entityType.compositeKey) basis.dev.warn("basis.entity: Entity type `" + entityType.name + "` wrapper was invoked with " + typeof data + " value as index, but entity type index is composite and consists of [" + keys(entityType.idFields).join(", ") + "] fields"); else basis.dev.warn("basis.entity: Entity type `" + entityType.name + "` wrapper was invoked with " + typeof data + " value as index, but entity type has no index"); return; } if (entity = entityType.index.get(data, entityType)) return entity; idValue = data; data = {}; data[idField] = idValue; } else { if (entityType.compositeKey) idValue = entityType.compositeKey(data, data); if (idValue != null) entity = entityType.index.get(idValue, entityType); } if (entity && entity.entityType === entityType) { entity.update(data); entity = basisData.devWrap(entity); } else entity = new EntityClass(data); return entity; } }; var entityType = new EntityTypeConstructor(config || {}, result); var EntityClass = entityType.entityClass; var name = entityType.name; defineType(name, result); extend(result, { all: entityType.all, type: entityType, typeName: name, toString: function () { return name + "()"; }, get: function (data) { return entityType.get(data); }, getSlot: function (id, defaults) { return entityType.getSlot(id, defaults); }, reader: function (data) { return entityType.reader(data); }, readList: function (value, map) { if (!value) return []; if (!Array.isArray(value)) value = [value]; if (typeof map != "function") map = $self; for (var i = 0; i < value.length; i++) value[i] = result(result.reader(map(value[i], i))); return value; }, extendClass: function (source) { EntityClass.extend.call(EntityClass, source); return result; }, extendReader: function (extReader) { var reader = result.reader; result.reader = function (data) { if (data && typeof data == "object") extReader(data); return reader(data); }; return result; }, entityType: entityType, extend: function () { basis.dev.warn("basis.entity: EntityType.extend() is deprecated, use EntityType.extendClass() instead."); return EntityClass.extend.apply(EntityClass, arguments); } }); basis.dev.warnPropertyAccess(result, "entityType", entityType, "basis.entity: EntityType.entityType is deprecated, use EntityType.type instead."); return result; } }; EntityTypeWrapper.className = namespace + ".EntityTypeWrapper"; var fieldDestroyHandlers = {}; var dataBuilderFactory = {}; var calcFieldWrapper = function (value, oldValue) { basis.dev.warn("Calculate fields are readonly"); return oldValue; }; var warnCalcReadOnly = function (name) { basis.dev.warn("basis.entity: Attempt to set value for `" + name + "` field was ignored as field is calc (read only)"); }; function getDataBuilder(defaults, fields, calcs) { var args = ["has"]; var values = [hasOwnProperty]; var obj = []; args.push("warnCalcReadOnly"); values.push(warnCalcReadOnly); for (var key in defaults) if (hasOwnProperty.call(defaults, key)) { var escapedKey = "\"" + key.replace(/"/g, "\"") + "\""; if (hasOwnProperty.call(calcs, key)) { obj.push(escapedKey + ":" + "has.call(data," + escapedKey + ")" + "?" + "warnCalcReadOnly(" + escapedKey + ")" + ":" + "undefined"); continue; } var name = "v" + obj.length; var fname = "f" + obj.length; var defValue = defaults[key]; args.push(name, fname); values.push(defValue, fields[key]); var newValueArgument = "has.call(data," + escapedKey + ")" + "?" + "data[" + escapedKey + "]" + ":" + name + (typeof defValue == "function" ? "(data)" : ""); var oldValueArgument = defValue !== undefined && typeof defValue !== "function" ? "," + name : ""; obj.push(escapedKey + ":" + fname + "(" + newValueArgument + oldValueArgument + ")"); } var code = obj.sort().join(","); var fn = dataBuilderFactory[code]; if (!fn) fn = dataBuilderFactory[code] = new Function(args, "return function(data){" + "return {" + code + "};" + "};"); return fn.apply(null, values); } function addField(entityType, name, config) { if (typeof config == "string" || Array.isArray(config) || typeof config == "function" && config.calc !== config) { config = { type: config }; } else { config = config ? basis.object.slice(config) : {}; } if ("type" in config) { if (typeof config.type == "string") config.type = getTypeByName(config.type, entityType.fields, name); if (Array.isArray(config.type)) { var values = config.type.slice(); config.type = typeEnum(values); if (values.indexOf(config.defValue) == -1) config.defValue = config.type.DEFAULT_VALUE; } if (config.type === Array) { config.type = nullableArray; config.defValue = null; } if (config.type === Date) { config.type = nullableDate; config.defValue = null; } if (typeof config.type != "function") { basis.dev.warn("EntityType " + entityType.name + ": Field wrapper for `" + name + "` field is not a function. Field wrapper has been ignored. Wrapper: ", config.type); config.type = null; } } var wrapper = config.type || $self; if (config.id || config.index || [ NumericId, NumberId, IntId, StringId ].indexOf(wrapper) != -1) entityType.idFields[name] = config; if (config.calc) { addCalcField(entityType, name, config.calc); entityType.fields[name] = calcFieldWrapper; } else { entityType.fields[name] = wrapper; entityType.aliases[name] = name; } if (!("defValue" in config) && typeof config.type === "function" && "DEFAULT_VALUE" in config.type) config.defValue = config.type.DEFAULT_VALUE; if ("defValue" in config) entityType.defaults[name] = config.defValue; else if ("DEFAULT_VALUE" in wrapper) entityType.defaults[name] = wrapper.DEFAULT_VALUE; else entityType.defaults[name] = wrapper(); if (!fieldDestroyHandlers[name]) fieldDestroyHandlers[name] = { destroy: function () { this.set(name, null); } }; } function addFieldAlias(entityType, alias, name) { if (name in entityType.fields == false) { basis.dev.warn("basis.entity: Can't add alias `" + alias + "` for non-exists field `" + name + "`"); return; } if (name in entityType.calcMap) { basis.dev.warn("basis.entity: Can't add alias `" + alias + "` for calc field `" + name + "`"); return; } if (alias in entityType.aliases) { basis.dev.warn("basis.entity: Alias `" + alias + "` already exists"); return; } entityType.aliases[alias] = name; } function addCalcField(entityType, name, wrapper) { var calcs = entityType.calcs; var deps = entityType.deps; var calcArgs = wrapper.args || []; var calcConfig = { args: calcArgs, wrapper: wrapper }; var before = entityType.calcs.length; var after = 0; if (calcArgs) for (var i = 0, calc; calc = calcs[i]; i++) if (calcArgs.indexOf(calc.key) != -1) after = i + 1; if (name) { calcConfig.key = name; entityType.calcMap[name] = calcConfig; for (var i = 0, calc; calc = calcs[i]; i++) if (calc.args.indexOf(name) != -1) { before = i; break; } if (after > before) { basis.dev.warn("Can't add calculate field `" + name + "`, because recursion"); return; } deps[name] = calcArgs.reduce(function (res, ref) { var items = deps[ref] || [ref]; for (var i = 0; i < items.length; i++) basis.array.add(res, items[i]); return res; }, []); for (var ref in deps) { var idx = deps[ref].indexOf(name); if (idx != -1) Array.prototype.splice.apply(deps[ref], [ idx, 1 ].concat(deps[name])); } } else { before = after; } calcs.splice(Math.min(before, after), 0, calcConfig); } function getFieldGetter(name) { return function (real) { if (real && this.modified && name in this.modified) return this.modified[name]; return this.data[name]; }; } function getFieldSetter(name) { return function (value, rollback) { return this.set(name, value, rollback); }; } var EntityTypeConstructor = Class(null, { className: namespace + ".EntityType", wrapper: null, all: null, fields: null, idField: null, idFields: null, compositeKey: null, idProperty: null, defaults: null, calcs: null, calcMap: null, aliases: null, slots: null, singleton: false, index: null, indexes: null, entityClass: null, init: function (config, wrapper) { this.name = config.name; if (!this.name || getTypeByNameIfDefined(this.name)) { if (getTypeByNameIfDefined(this.name)) basis.dev.warn(namespace + ": Duplicate type name `" + this.name + "`, name ignored"); this.name = getUntitledName("UntitledEntityType"); } this.fields = {}; this.calcs = []; this.calcMap = {}; this.deps = {}; this.idFields = {}; this.defaults = {}; this.aliases = {}; this.slots = {}; var index = config.index; if (index) { if (index instanceof Index) this.index = index; else basis.dev.warn("index must be instanceof basis.entity.Index"); } this.wrapper = wrapper; if ("all" in config == false || config.all || config.singleton) { this.all = new ReadOnlyEntitySet(config.all); this.all.wrapper = wrapper; this.all.set = function (data) { if (Array.isArray(data)) data = data.map(function (item) { return item instanceof EntityClass === false ? wrapper.reader(item) : item; }); return setAndDestroyRemoved.call(this, data); }.bind(this.all); } this.singleton = !!config.singleton; if (this.singleton) { var singletonInstance; this.get = function () { return singletonInstance; }; this.all.addHandler({ itemsChanged: function (sender, delta) { singletonInstance = delta.inserted ? delta.inserted[0] : null; } }, this); } for (var key in config.fields) addField(this, key, config.fields[key]); for (var key in config.aliases) addFieldAlias(this, key, config.aliases[key]); if (config.constrains) config.constrains.forEach(function (item) { addCalcField(this, null, item); }, this); if (!this.calcs.length) this.calcs = null; var idFields = keys(this.idFields); var indexes = {}; if (idFields.length) { for (var field in this.idFields) { var fieldCfg = this.idFields[field]; var index = fieldCfg.index; var indexDescriptor; if (!index || index instanceof Index == false) { if (typeof index == "string") { if (index in namedIndexes == false) namedIndexes[index] = new Index(); index = namedIndexes[index]; } else { if (!this.index) this.index = new Index(); index = this.index; } } indexDescriptor = indexes[index.basisObjectId]; if (!indexDescriptor) indexDescriptor = indexes[index.basisObjectId] = { index: index, fields: [] }; indexDescriptor.fields.push(field); this.idFields[field] = indexDescriptor; } if (this.index && this.index.basisObjectId in indexes == false) { basis.dev.warn("basis.entity: entity index is not used for any field, index ignored"); this.index = null; } for (var id in indexes) { var indexDescriptor = indexes[id]; indexDescriptor.property = "__id__" + id; indexDescriptor.compositeKey = ConcatStringField.apply(null, indexDescriptor.fields); if (indexDescriptor.fields.length == 1) indexDescriptor.idField = indexDescriptor.fields[0]; } var indexesKeys = keys(indexes); var primaryIndex = indexes[this.index ? this.index.basisObjectId : indexesKeys[0]]; this.index = primaryIndex.index; this.idField = primaryIndex.idField; this.compositeKey = primaryIndex.compositeKey; this.idProperty = primaryIndex.property; this.indexes = indexes; } else { if (this.index) { basis.dev.warn("basis.entity: entity has no any id field, index ignored"); this.index = null; } } var initDelta = {}; for (var key in this.defaults) initDelta[key] = undefined; if (hasOwnProperty.call(config, "state")) basis.dev.warn("basis.entity: default instance state can't be defined via type config anymore, use Type.extendClass({ state: .. }) instead"); var EntityClass = createEntityClass(this, this.all, this.fields, this.slots); this.entityClass = EntityClass; EntityClass.extend({ entityType: this, type: wrapper, typeName: this.name, generateData: getDataBuilder(this.defaults, this.fields, this.calcMap), initDelta: initDelta }); for (var name in this.fields) { EntityClass.prototype["get_" + name] = getFieldGetter(name); if (this.fields[name] !== calcFieldWrapper) EntityClass.prototype["set_" + name] = getFieldSetter(name); } entityTypes.push(this); }, reader: function (data) { var result = {}; if (isKeyType[typeof data]) return this.idField ? data : null; if (!data || data == null) return null; for (var key in data) { var fieldKey = this.aliases[key]; if (fieldKey) { var reader = this.fields[fieldKey].reader; result[fieldKey] = reader ? reader(data[key]) : data[key]; } } return result; }, get: function (entityOrData) { var id = this.getId(entityOrData); if (this.index && id != null) return this.index.get(id, this); }, getId: function (entityOrData) { if (this.compositeKey && entityOrData != null) { if (isKeyType[typeof entityOrData]) return entityOrData; if (entityOrData && entityOrData.entityType === this) return entityOrData[this.idProperty]; if (entityOrData instanceof DataObject) entityOrData = entityOrData.data; if (this.compositeKey) return this.compositeKey(entityOrData, entityOrData); } }, getSlot: function (data) { var id = this.getId(data); if (id != null) { var slot = hasOwnProperty.call(this.slots, id) && this.slots[id]; if (!slot) { if (isKeyType[typeof data]) { var tmp = {}; if (this.idField) tmp[this.idField] = data; data = tmp; } slot = this.slots[id] = new Slot({ delegate: this.get(id) || null, data: data }); } return slot; } } }); function entityWarn(entity, message) { basis.dev.warn("[basis.entity " + entity.entityType.name + "#" + entity.basisObjectId + "] " + message, entity); } var BaseEntity = Class(DataObject, { className: namespace + ".BaseEntity", target: true, setDelegate: function () { }, extendConstructor_: false, fieldHandlers_: null, propertyDescriptors: { modified: { nested: true, events: "rollbackUpdate" } }, modified: null, emit_rollbackUpdate: createEvent("rollbackUpdate") }); var createEntityClass = function (entityType, all, fields, slots) { function calc(entity, delta, rollbackDelta) { var calcs = entityType.calcs; var data = entity.data; var updated = false; try { if (calcs) { for (var i = 0, calc; calc = calcs[i]; i++) { var key = calc.key; var oldValue = data[key]; var newValue = calc.wrapper(delta, data, oldValue); if (key && newValue !== oldValue) { delta[key] = oldValue; data[key] = newValue; updated = true; } } } for (var id in entityType.indexes) { var indexDescriptor = entityType.indexes[id]; var curId = entity[indexDescriptor.property]; var newId = curId; if (indexDescriptor.compositeKey) newId = indexDescriptor.compositeKey(delta, data, curId); if (newId !== curId) { updateIndex(indexDescriptor.index, entity, curId, newId); entity[indexDescriptor.property] = newId; } } return updated; } catch (e) { entityWarn(entity, "(rollback changes) Exception on field calcs: " + (e && e.message || e)); for (var key in delta) entity.data[key] = delta[key]; if (rollbackDelta && !entity.modified) entity.modified = rollbackDelta; } } function updateIndex(index, entity, curValue, newValue) { if (newValue != null) { index.add(newValue, entity); if (hasOwnProperty.call(slots, newValue)) slots[newValue].setDelegate(entity); } if (curValue != null) { index.remove(curValue, entity); if (hasOwnProperty.call(slots, curValue)) slots[curValue].setDelegate(); } } return Class(BaseEntity, { className: entityType.name, syncEvents: { update: true, stateChanged: true, subscribersChanged: true }, isSyncRequired: function () { return DataObject.prototype.isSyncRequired.call(this) && (!entityType.idProperty || this[entityType.idProperty] != null); }, init: function (data) { this.delegate = null; this.data = this.generateData(data); BaseEntity.prototype.init.call(this); for (var key in data) if (key in fields == false) entityWarn(this, "Field \"" + key + "\" is not defined, value has been ignored."); var value; for (var key in this.data) { value = this.data[key]; if (value && value !== this && value instanceof Emitter) { value.addHandler(fieldDestroyHandlers[key], this); if (!this.fieldHandlers_) this.fieldHandlers_ = {}; this.fieldHandlers_[key] = true; } } calc(this, this.initDelta); if (all) all.emit_itemsChanged({ inserted: [this] }); }, toString: function () { return "[object " + this.constructor.className + "(" + this.entityType.name + ")]"; }, getId: function () { return this[entityType.idProperty]; }, get: function (key, real) { if (real && this.modified && key in this.modified) return this.modified[key]; return this.data[key]; }, set: function (key, value, rollback, silent_) { var valueWrapper = fields[key]; if (!valueWrapper) { entityWarn(this, "Field \"" + key + "\" is not defined, value has been ignored."); return false; } var result; var rollbackData = this.modified; if (valueWrapper === nullableArray && rollbackData && key in rollbackData) value = nullableArray(value, rollbackData[key]); var newValue = valueWrapper(value, this.data[key]); var curValue = this.data[key]; var valueChanged = newValue !== curValue && (!newValue || !curValue || newValue.constructor !== Date || curValue.constructor !== Date || +newValue !== +curValue); if (valueChanged) updateField: { result = {}; if (!entityType.idFields[key]) { if (rollback) { if (!rollbackData) this.modified = rollbackData = {}; if (key in rollbackData === false) { result.rollback = { key: key, value: undefined }; rollbackData[key] = curValue; } else { if (rollbackData[key] === newValue) { result.rollback = { key: key, value: newValue }; delete rollbackData[key]; if (!keys(rollbackData).length) this.modified = null; } } } else { if (rollbackData && key in rollbackData) { if (rollbackData[key] !== newValue) { result.rollback = { key: key, value: rollbackData[key] }; rollbackData[key] = newValue; break updateField; } else return false; } } } this.data[key] = newValue; if (this.fieldHandlers_ && this.fieldHandlers_[key]) { curValue.removeHandler(fieldDestroyHandlers[key], this); this.fieldHandlers_[key] = false; } if (newValue && newValue !== this && newValue instanceof Emitter) { newValue.addHandler(fieldDestroyHandlers[key], this); if (!this.fieldHandlers_) this.fieldHandlers_ = {}; this.fieldHandlers_[key] = true; } result.key = key; result.value = curValue; result.delta = {}; result.delta[key] = curValue; } else { if (!rollback && rollbackData && key in rollbackData) { result = { rollback: { key: key, value: rollbackData[key] } }; delete rollbackData[key]; if (!keys(rollbackData).length) this.modified = null; } } if (!silent_ && result) { var update = result.key; var delta = result.delta || {}; var rollbackDelta; if (result.rollback) { rollbackDelta = {}; rollbackDelta[result.rollback.key] = result.rollback.value; } if (calc(this, delta, rollbackDelta)) update = true; if (update) { this.emit_update(delta); result.delta = delta; } if (rollbackDelta) this.emit_rollbackUpdate(rollbackDelta); } return result || false; }, update: function (data, rollback) { var update = false; var delta = {}; if (data) { var rollbackDelta; var setResult; for (var key in data) { if (setResult = this.set(key, data[key], rollback, true)) { if (setResult.key) { update = true; delta[setResult.key] = setResult.value; } if (setResult.rollback) { if (!rollbackDelta) rollbackDelta = {}; rollbackDelta[setResult.rollback.key] = setResult.rollback.value; } } } if (calc(this, delta, rollbackDelta)) update = true; if (update) this.emit_update(delta); if (rollbackDelta) this.emit_rollbackUpdate(rollbackDelta); } return update ? delta : false; }, read: function (data) { return this.update(this.type.reader(data)); }, generateData: function () { return {}; }, reset: function () { this.update(this.generateData({})); }, clear: function () { var data = {}; for (var key in this.data) data[key] = undefined; return this.update(data); }, commit: function (data) { var rollbackData = this.modified; this.modified = null; if (data) this.update(data); if (rollbackData) this.emit_rollbackUpdate(rollbackData); }, rollback: function (keys) { var rollbackData = this.modified; if (rollbackData && keys) { if (!Array.isArray(keys)) keys = [keys]; rollbackData = basis.object.slice(rollbackData, keys.reduce(function (res, item) { return res.concat(entityType.deps[item] || item); }, [])); } this.update(rollbackData, true); }, destroy: function () { if (this.fieldHandlers_) { for (var key in this.fieldHandlers_) if (this.fieldHandlers_[key]) this.data[key].removeHandler(fieldDestroyHandlers[key], this); this.fieldHandlers_ = null; } for (var key in entityType.indexes) { var indexDescriptor = entityType.indexes[key]; var id = this[indexDescriptor.property]; if (id != null) updateIndex(indexDescriptor.index, this, id, null); } if (all && all.has(this)) all.emit_itemsChanged({ deleted: [this] }); DataObject.prototype.destroy.call(this); this.data = NULL_INFO; this.modified = null; } }); }; function isEntity(value) { return value && value instanceof BaseEntity; } function createType(configOrName, fields) { if (this instanceof createType) basis.dev.warn("`new` operator was used with basis.entity.createType, it's a mistake"); var config = configOrName || {}; if (typeof configOrName == "string") { config = { name: config, fields: fields || {} }; } else { if (fields) config = basis.object.merge(config, { fields: fields }); } return new EntityTypeWrapper(config); } function createSetType(name, type, options) { if (this instanceof createSetType) basis.dev.warn("`new` operator was used with basis.entity.createSetType, it's a mistake"); switch (arguments.length) { case 0: case 1: if (name && name.constructor === Object) { options = basis.object.slice(name); type = basis.object.splice(options).type; name = basis.object.splice(options).name; } else { type = name; name = undefined; } break; case 2: if (type && type.constructor === Object) { options = type; type = name; name = undefined; } break; } return new EntitySetWrapper(type, name, options); } module.exports = { isEntity: isEntity, createType: createType, createSetType: createSetType, validate: validateScheme, getTypeByName: function (typeName) { return getTypeByNameIfDefined(typeName); }, getIndexByName: function (name) { return namedIndexes[name]; }, is: function (value, type) { var EntityClass; if (typeof type == "string") type = getTypeByNameIfDefined(type); EntityClass = type && type.type && (type.type.entitySetClass || type.type.entityClass); return value && EntityClass ? value instanceof EntityClass : false; }, get: function (typeName, value) { var Type = getTypeByNameIfDefined(typeName); if (Type) return Type.get(value); }, resolve: function (typeName, value) { var Type = getTypeByNameIfDefined(typeName); if (Type) return Type(value); }, getByIndex: function (indexName, id) { if (indexName in namedIndexes) return namedIndexes[indexName].get(id); else basis.dev.warn("basis.entity: index with name `" + indexName + "` doesn't exists"); }, NumericId: NumericId, NumberId: NumberId, IntId: IntId, StringId: StringId, Index: Index, CalculateField: CalculateField, ConcatStringField: ConcatStringField, calc: CalculateField, arrayField: nullableArray, dateField: nullableDate, EntityType: EntityTypeWrapper, Entity: createEntityClass, BaseEntity: BaseEntity, EntitySetType: EntitySetWrapper, EntitySet: EntitySet, ReadOnlyEntitySet: ReadOnlyEntitySet, Collection: EntityCollection, Grouping: EntityGrouping }; basis.resource("./r.js").ready(function () { basis.dev.warnPropertyAccess(module.exports, "Collection", EntityCollection, "basis.entity: Collection class is deprecated, use basis.data.dataset.Filter instead."); basis.dev.warnPropertyAccess(module.exports, "Grouping", EntityGrouping, "basis.entity: Grouping class is deprecated, use basis.data.dataset.Split instead."); }); }, "s.js": function (exports, module, basis, global, __filename, __dirname, require, resource, asset) { var namespace = "basis.type"; var namedTypes = {}; var deferredTypeDef = {}; var pendingTypeNames = {}; function defineType(typeName, type) { if (typeof typeName !== "string") basis.dev.warn(namespace + ": defineType expects a string as a type name. `" + typeName + "` is not a string"); var list = deferredTypeDef[typeName]; if (list) { for (var i = 0, def; def = list[i]; i++) { var typeHost = def[0]; var fieldName = def[1]; typeHost[fieldName] = type; } delete deferredTypeDef[typeName]; } delete pendingTypeNames[typeName]; if (namedTypes[typeName]) basis.dev.warn(namespace + ": type `" + typeName + "` is already defined. Redefined with new version"); namedTypes[typeName] = type; } function getTypeByName(typeName, typeHost, field) { if (namedTypes.hasOwnProperty(typeName)) return namedTypes[typeName]; if (typeHost && field) { var list = deferredTypeDef[typeName]; if (!list) list = deferredTypeDef[typeName] = []; list.push([ typeHost, field ]); } else pendingTypeNames[typeName] = true; return function (value, oldValue) { var Type = namedTypes.hasOwnProperty(typeName) ? namedTypes[typeName] : null; if (Type) return Type(value, oldValue); if (arguments.length && value != null) basis.dev.warn(namespace + ": type `" + typeName + "` is not defined for `" + field + "`, but function called"); }; } function getTypeByNameIfDefined(typeName) { if (namedTypes.hasOwnProperty(typeName)) return namedTypes[typeName]; } function validateScheme() { for (var typeName in pendingTypeNames) basis.dev.warn(namespace + ": type `" + typeName + "` is not defined, but used via type.getTypeByName()"); for (var typeName in deferredTypeDef) basis.dev.warn(namespace + ": type `" + typeName + "` is not defined, but used by " + deferredTypeDef[typeName].length + " type(s)"); } module.exports = { string: basis.require("./29.js"), number: basis.require("./2a.js"), int: basis.require("./2b.js"), "enum": basis.require("./2c.js"), array: basis.require("./2d.js"), object: basis.require("./2e.js"), date: basis.require("./2f.js"), validate: validateScheme, getTypeByName: getTypeByName, getTypeByNameIfDefined: getTypeByNameIfDefined, defineType: defineType }; }, "29.js": function (exports, module, basis, global, __filename, __dirname, require, resource, asset) { function stringTransform(defaultValue, nullable) { var transformName = nullable ? "basis.type.string.nullable" : "basis.type.string"; if (nullable) { if (defaultValue !== null && typeof defaultValue !== "string") { basis.dev.warn(transformName + ".default expected string or null as default value but got ", defaultValue, ". Falling back to " + transformName); return string.nullable; } } else { if (typeof defaultValue !== "string") { basis.dev.warn(transformName + ".default expected string as default value but got ", defaultValue, ". Falling back to " + transformName); return string; } } var transform = function (value, oldValue) { if (typeof value === "string") return value; if (nullable && value === null) return null; basis.dev.warn(transformName + " expected string or null but got ", value); return oldValue; }; transform.DEFAULT_VALUE = defaultValue; return transform; } var string = stringTransform("", false); string["default"] = function (defaultValue) { return stringTransform(defaultValue, false); }; string.nullable = stringTransform(null, true); string.nullable["default"] = function (defaultValue) { return stringTransform(defaultValue, true); }; module.exports = string; }, "2a.js": function (exports, module, basis, global, __filename, __dirname, require, resource, asset) { function isNumber(value) { return value === 0 || typeof value !== "object" && isFinite(value); } function numberTransform(defaultValue, nullable) { var transformName = nullable ? "basis.type.number.nullable" : "basis.type.number"; if (nullable) { if (defaultValue !== null && !isNumber(defaultValue)) { basis.dev.warn(transformName + ".default expected number or null as default value but got ", defaultValue, ". Falling back to " + transformName); return number.nullable; } } else { if (!isNumber(defaultValue)) { basis.dev.warn(transformName + ".default expected number as default value but got ", defaultValue, ". Falling back to " + transformName); return number; } } defaultValue = defaultValue === null ? null : Number(defaultValue); var transform = function (value, oldValue) { if (isNumber(value)) return Number(value); if (nullable && value === null) return null; basis.dev.warn(transformName + " expected number but got ", value); return oldValue; }; transform.DEFAULT_VALUE = defaultValue; return transform; } var number = numberTransform(0, false); number["default"] = function (defaultValue) { return numberTransform(defaultValue, false); }; number.nullable = numberTransform(null, true); number.nullable["default"] = function (defaultValue) { return numberTransform(defaultValue, true); }; module.exports = number; }, "2b.js": function (exports, module, basis, global, __filename, __dirname, require, resource, asset) { function isNumber(value) { return value === 0 || typeof value !== "object" && isFinite(value); } function intTransform(defaultValue, nullable) { var transformName = nullable ? "basis.type.int.nullable" : "basis.type.int"; if (nullable) { if (defaultValue !== null && !isNumber(defaultValue)) { basis.dev.warn(transformName + ".default expected number or null as default value but got ", defaultValue, ". Falling back to " + transformName); return int.nullable; } } else { if (!isNumber(defaultValue)) { basis.dev.warn(transformName + ".default expected number as default value but got ", defaultValue, ". Falling back to " + transformName); return int; } } defaultValue = defaultValue === null ? null : parseInt(defaultValue, 10); var transform = function (value, oldValue) { if (isNumber(value)) return parseInt(value, 10); if (nullable && value === null) return null; basis.dev.warn(transformName + " expected number but got ", value); return oldValue; }; transform.DEFAULT_VALUE = defaultValue; return transform; } var int = intTransform(0, false); int["default"] = function (defaultValue) { return intTransform(defaultValue, false); }; int.nullable = intTransform(null, true); int.nullable["default"] = function (defaultValue) { return intTransform(defaultValue, true); }; module.exports = int; }, "2c.js": function (exports, module, basis, global, __filename, __dirname, require, resource, asset) { function enumeration(values) { if (!Array.isArray(values)) { basis.dev.warn("basis.type.enum constructor expected array but got ", values, ". Wrapping into array"); values = [values]; } if (!values.length) throw new Error("basis.type.enum constructor expected non-empty array but got empty."); var transform = function (value, oldValue) { if (values.indexOf(value) !== -1) return value; basis.dev.warn("basis.type.enum expected one of values from the list ", values, " but got ", value); return oldValue; }; transform.DEFAULT_VALUE = values[0]; transform["default"] = function (defaultValue) { if (values.indexOf(defaultValue) === -1) { basis.dev.warn("basis.type.enum.default expected one of values from the list ", values, " but got ", defaultValue, ". Ignoring default value"); return transform; } var transformWithDefaultValue = function () { return transform.apply(this, arguments); }; transformWithDefaultValue.DEFAULT_VALUE = defaultValue; return transformWithDefaultValue; }; return transform; } module.exports = enumeration; }, "2d.js": function (exports, module, basis, global, __filename, __dirname, require, resource, asset) { function equalArrays(a, b) { if (a === b) return true; if (a.length != b.length) return false; for (var i = 0; i < a.length; ++i) if (a[i] !== b[i]) return false; return true; } function arrayTransform(defaultValue, nullable) { var transformName = nullable ? "basis.type.array.nullable" : "basis.type.array"; if (nullable) { if (defaultValue !== null && !Array.isArray(defaultValue)) { basis.dev.warn(transformName + ".default expected array or null as default value but got ", defaultValue, ". Falling back to ", defaultValue); return array.nullable; } } else { if (!Array.isArray(defaultValue)) { basis.dev.warn(transformName + ".default expected array as default value but got ", defaultValue, ". Falling back to ", defaultValue); return array; } } var transform = function (value, oldValue) { if (Array.isArray(value)) return oldValue && equalArrays(value, oldValue) ? oldValue : value; if (nullable && value === null) return null; basis.dev.warn("basis.type.array.nullable expected array or null but got ", value); return oldValue; }; transform.serialize = function (value) { try { return JSON.stringify(value); } catch (e) { basis.dev.warn(transformName + ".serialize got exception while stringifying", value, " to JSON. Stringifying default value instead"); return JSON.stringify(defaultValue); } }; transform.deserialize = function (value) { try { return JSON.parse(value); } catch (e) { basis.dev.warn(transformName + ".deserialize expected correct JSON, but got ", value, ". Falling back to default value"); return defaultValue; } }; transform.DEFAULT_VALUE = defaultValue; return transform; } var defValue = []; if (typeof Object.freeze === "function") Object.freeze(defValue); if (typeof Proxy === "function") defValue = new Proxy(defValue, { set: function () { basis.dev.warn("Ignored attempt to modify basis.type.array read-only default value"); } }); var array = arrayTransform(defValue, false); array["default"] = function (defaultValue) { return arrayTransform(defaultValue, false); }; array.nullable = arrayTransform(null, true); array.nullable["default"] = function (defaultValue) { return arrayTransform(defaultValue, true); }; module.exports = array; }, "2e.js": function (exports, module, basis, global, __filename, __dirname, require, resource, asset) { function isObject(value) { if (!value) return false; if (Array.isArray(value)) return false; return typeof value === "object"; } function objectTransform(defaultValue, nullable) { var transformName = nullable ? "basis.type.object.nullable" : "basis.type.object"; if (nullable) { if (defaultValue !== null && !isObject(defaultValue)) { basis.dev.warn(transformName + ".default expected object or null as default value but got ", defaultValue, ". Falling back to " + transformName); return object.nullable; } } else { if (!isObject(defaultValue)) { basis.dev.warn(transformName + ".default expected object as default value but got ", defaultValue, ". Falling back to " + transformName); return object; } } var transform = function (value, oldValue) { if (isObject(value)) return value; if (nullable && value === null) return null; basis.dev.warn(transformName + " expected object but got ", value); return oldValue; }; transform.serialize = function (value) { try { return JSON.stringify(value); } catch (e) { basis.dev.warn(transformName + ".serialize got exception while stringifying", value, " to JSON. Stringifying default value instead"); return JSON.stringify(defaultValue); } }; transform.deserialize = function (value) { try { return JSON.parse(value); } catch (e) { basis.dev.warn(transformName + ".deserialize expected correct JSON, but got ", value, ". Falling back to default value"); return defaultValue; } }; transform.DEFAULT_VALUE = defaultValue; return transform; } var defValue = {}; if (typeof Object.freeze === "function") Object.freeze(defValue); if (typeof Proxy === "function") defValue = new Proxy(defValue, { set: function () { basis.dev.warn("Ignored attempt to modify basis.type.object read-only default value"); } }); var object = objectTransform(defValue, false); object["default"] = function (defaultValue) { return objectTransform(defaultValue, false); }; object.nullable = objectTransform(null, true); object.nullable["default"] = function (defaultValue) { return objectTransform(defaultValue, true); }; module.exports = object; }, "2f.js": function (exports, module, basis, global, __filename, __dirname, require, resource, asset) { var reIsoStringSplit = /\D/; var reIsoTimezoneDesignator = /(.{10,})([\-\+]\d{1,2}):?(\d{1,2})?$/; var fromISOString = function () { function fastDateParse(y, m, d, h, i, s, ms) { var date = new Date(y, m - 1, d, h || 0, 0, s || 0, ms ? ms.substr(0, 3) : 0); date.setMinutes((i || 0) - tz - date.getTimezoneOffset()); return date; } var tz; return function (isoDateString) { tz = 0; return fastDateParse.apply(null, String(isoDateString || "").replace(reIsoTimezoneDesignator, function (m, pre, h, i) { tz = Number(h || 0) * 60 + Number(i || 0); return pre; }).split(reIsoStringSplit)); }; }(); var ISO_REGEXP = /^\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}:\d{2}(\.\d+)?(([+-]\d{2}(:\d{2})?)|Z)?$/; var PARTIAL_ISO_REGEXP = /^\d{4}-\d{2}-\d{2}$/; function toDate(value) { if (typeof value === "number" && isFinite(value)) return new Date(value); if (value && typeof value === "string") { if (!ISO_REGEXP.test(value) && !PARTIAL_ISO_REGEXP.test(value)) basis.dev.warn("basis.type.date expected ISO string but got ", value, ". Try to parse as ISO string anyway"); return fromISOString(value); } if (value instanceof Date) return value; return undefined; } function dateTransform(defaultValue, nullable) { var transformName = nullable ? "basis.type.date.nullable" : "basis.type.date"; var defaultValueAsDate = toDate(defaultValue); if (nullable) { if (defaultValue !== null && defaultValueAsDate === undefined) { basis.dev.warn(transformName + ".default ISO string, number or date object as default value but got ", defaultValue, ". Falling back to " + transformName); return date.nullable; } } else { if (defaultValueAsDate === undefined) { basis.dev.warn(transformName + ".default ISO string, number, date object or null as default value but got ", defaultValue, ". Falling back to " + transformName); return date; } } var transform = function (value, oldValue) { if (nullable && value === null) return null; var dateObject = toDate(value); if (dateObject === undefined) { basis.dev.warn("basis.type.date expected ISO string, number, date or null but got ", value); return oldValue; } if (dateObject && oldValue && dateObject.getTime() === oldValue.getTime()) return oldValue; return dateObject; }; transform.serialize = function (value) { return value ? String(Number(value)) : "null"; }; transform.deserialize = function (value) { if (value === "null") return null; var timestamp = Number(value); return timestamp ? new Date(timestamp) : defaultValue; }; transform.DEFAULT_VALUE = defaultValueAsDate || null; return transform; } var date = dateTransform(new Date(0), false); date["default"] = function (defaultValue) { return dateTransform(defaultValue, false); }; date.nullable = dateTransform(null, true); date.nullable["default"] = function (defaultValue) { return dateTransform(defaultValue, true); }; module.exports = date; }, "t.js": function (exports, module, basis, global, __filename, __dirname, require, resource, asset) { var namespace = "basis.net.jsonp"; var document = global.document; var escapeValue = global.encodeURIComponent; var extend = basis.object.extend; var objectSlice = basis.object.slice; var objectMerge = basis.object.merge; var basisNet = basis.require("./u.js"); var createTransportEvent = basisNet.createTransportEvent; var createRequestEvent = basisNet.createRequestEvent; var AbstractRequest = basisNet.AbstractRequest; var AbstractTransport = basisNet.AbstractTransport; var STATE = basis.require("./g.js").STATE; var STATE_UNSENT = 0; var STATE_LOADING = 3; var STATE_DONE = 4; var callbackData = {}; function getCallback() { var name = basis.fn.publicCallback(function (data) { callbackData[name] = data; }); return name; } function fetchCallbackData(name) { var data = callbackData[name]; delete callbackData[name]; return data; } function releaseCallback(name) { delete callbackData[name]; delete global[name]; } function readyStateChangeHandler(readyState, abort) { var newState; var newStateData; var error = false; if (typeof readyState != "number") { if (!readyState || this.script !== readyState.target) return; error = readyState && readyState.type == "error"; readyState = error || !this.script.readyState || /loaded|complete/.test(this.script.readyState) ? STATE_DONE : STATE_LOADING; } if (readyState == this.prevReadyState_) return; this.prevReadyState_ = readyState; this.emit_readyStateChanged(readyState); if (readyState == STATE_DONE) { this.clearTimeout(); this.script.onload = this.script.onerror = this.script.onreadystatechange = null; if (this.script.parentNode) this.script.parentNode.removeChild(this.script); this.script = null; if (abort) { this.emit_abort(); newState = this.stateOnAbort; } else { this.processResponse(); if (this.isSuccessful() && !error) { newState = STATE.READY; this.emit_success(this.getResponseData()); } else { newState = STATE.ERROR; newStateData = this.getResponseError(); this.emit_failure(newStateData); } } this.emit_complete(this); var callback = this.callback; if (abort) { setTimeout(global[callback] = function () { releaseCallback(callback); }, 5 * 60 * 1000); } else { releaseCallback(callback); } } else newState = STATE.PROCESSING; this.setState(newState, newStateData); } var Request = AbstractRequest.subclass({ className: namespace + ".Request", timeout: 30000, timer_: null, emit_readyStateChanged: createRequestEvent("readyStateChanged"), isIdle: function () { return !this.script; }, isSuccessful: function () { return this.data.status == 200; }, processResponse: function () { if (this.callback in callbackData) this.update({ contentType: "application/javascript", data: fetchCallbackData(this.callback), status: 200 }); }, getResponseData: function () { return this.data.data; }, getResponseError: function () { return { code: "ERROR", msg: "ERROR" }; }, prepare: basis.fn.$true, prepareRequestData: function (requestData) { var params = []; var url = requestData.url; requestData = objectSlice(requestData); this.callback = getCallback(); for (var key in requestData.params) { var value = requestData.params[key]; if (value == null || value.toString() == null) continue; params.push(escapeValue(key) + "=" + escapeValue(value.toString())); } params.push(escapeValue(requestData.callbackParam) + "=" + escapeValue(this.callback)); params = params.join("&"); if (requestData.routerParams) url = url.replace(/:([a-z\_\-][a-z0-9\_\-]+)/gi, function (m, key) { if (key in requestData.routerParams) return requestData.routerParams[key]; else return m; }); if (params) url += (url.indexOf("?") == -1 ? "?" : "&") + params; requestData.requestUrl = url; return requestData; }, doRequest: function () { this.send(this.prepareRequestData(this.requestData)); }, send: function (requestData) { if (!document) throw "JSONP is not supported for current environment"; var head = document.head || document.getElementByName("head")[0] || document.documentElement; var script = document.createElement("script"); this.update({ data: undefined, status: "", error: "" }); this.script = script; script.async = true; script.src = requestData.requestUrl; script.charset = requestData.encoding; script.onload = script.onerror = script.onreadystatechange = readyStateChangeHandler.bind(this); this.prevReadyState_ = -1; this.emit_start(); readyStateChangeHandler.call(this, STATE_UNSENT); this.setTimeout(this.timeout); head.appendChild(this.script); }, repeat: function () { if (this.requestData) { this.abort(); this.doRequest(); } }, abort: function () { if (!this.isIdle()) { this.clearTimeout(); readyStateChangeHandler.call(this, STATE_DONE, true); } }, setTimeout: function (timeout) { this.timer_ = setTimeout(this.timeoutAbort.bind(this), timeout); }, clearTimeout: function () { if (this.timer_) this.timer_ = clearTimeout(this.timer_); }, timeoutAbort: function () { this.update({ error: { code: "TIMEOUT_ERROR", message: "Timeout error" } }); this.emit_timeout(this); this.abort(); }, destroy: function () { this.abort(); AbstractRequest.prototype.destroy.call(this); } }); var Transport = AbstractTransport.subclass({ className: namespace + ".Transport", requestClass: Request, emit_readyStateChanged: createTransportEvent("readyStateChanged"), encoding: null, params: null, callbackParam: "callback", init: function () { AbstractTransport.prototype.init.call(this); this.params = objectSlice(this.params); }, setParam: function (name, value) { this.params[name] = value; }, setParams: function (params) { this.clearParams(); for (var key in params) this.setParam(key, params[key]); }, removeParam: function (name) { delete this.params[name]; }, clearParams: function () { for (var key in this.params) delete this.params[key]; }, prepareRequestData: function (requestData) { var url = requestData.url || this.url; if (!url) throw new Error("URL is not defined"); extend(requestData, { url: url, encoding: requestData.encoding || this.encoding, params: objectMerge(this.params, requestData.params), routerParams: requestData.routerParams, callbackParam: requestData.callbackParam || this.callbackParam }); return requestData; } }); module.exports = { Request: Request, Transport: Transport, request: function (config, successCallback, failureCallback) { if (typeof config == "string") config = { url: config }; var transport = new Transport(config); transport.addHandler({ success: successCallback && function (sender, req, data) { successCallback(data); }, failure: failureCallback && function (sender, req, error) { failureCallback(error); }, complete: function () { basis.nextTick(function () { transport.destroy(); }); } }); transport.request(); } }; }, "u.js": function (exports, module, basis, global, __filename, __dirname, require, resource, asset) { var namespace = "basis.net"; var arrayFrom = basis.array.from; var objectSlice = basis.object.slice; var basisEvent = basis.require("./3.js"); var createEvent = basisEvent.create; var Emitter = basisEvent.Emitter; var DataObject = basis.require("./g.js").Object; var STATE = basis.require("./g.js").STATE; function createTransportEvent(eventName) { var event = createEvent(eventName); return function transportEvent() { event.apply(transportDispatcher, arguments); if (this.service) event.apply(this.service, arguments); event.apply(this, arguments); }; } function createRequestEvent(eventName) { var event = createEvent(eventName); return function requestEvent() { var args = [this].concat(arrayFrom(arguments)); if (this.transport) this.transport["emit_" + eventName].apply(this.transport, args); else event.apply(transportDispatcher, args); event.apply(this, arguments); }; } var inprogressTransports = []; var transportDispatcher = new Emitter({ abort: function () { var result = arrayFrom(inprogressTransports); for (var i = 0; i < result.length; i++) result[i].abort(); return result; }, handler: { start: function (request) { basis.array.add(inprogressTransports, request.transport); }, complete: function (request) { basis.array.remove(inprogressTransports, request.transport); } } }); var AbstractRequest = DataObject.subclass({ className: namespace + ".AbstractRequest", requestData: null, transport: null, stateOnAbort: STATE.UNDEFINED, emit_start: createRequestEvent("start"), emit_timeout: createRequestEvent("timeout"), emit_abort: createRequestEvent("abort"), emit_success: createRequestEvent("success"), emit_failure: createRequestEvent("failure"), emit_complete: createRequestEvent("complete"), abort: basis.fn.$undef, doRequest: basis.fn.$undef, destroy: function () { DataObject.prototype.destroy.call(this); this.requestData = null; } }); var TRANSPORT_REQUEST_HANDLER = { start: function (sender, request) { basis.array.add(this.inprogressRequests, request); }, complete: function (sender, request) { basis.array.remove(this.inprogressRequests, request); } }; var TRANSPORT_POOL_LIMIT_HANDLER = { complete: function () { var nextRequest = this.requestQueue.shift(); if (nextRequest) { basis.nextTick(function () { nextRequest.doRequest(); }); } } }; var AbstractTransport = Emitter.subclass({ className: namespace + ".AbstractTransport", requestClass: AbstractRequest, stopped: false, poolLimit: null, poolHashGetter: null, requests: null, requestQueue: null, inprogressRequests: null, stoppedRequests: null, emit_start: createTransportEvent("start"), emit_timeout: createTransportEvent("timeout"), emit_abort: createTransportEvent("abort"), emit_success: createTransportEvent("success"), emit_failure: createTransportEvent("failure"), emit_complete: createTransportEvent("complete"), init: function () { this.requests = {}; this.requestQueue = []; this.inprogressRequests = []; Emitter.prototype.init.call(this); this.addHandler(TRANSPORT_REQUEST_HANDLER, this); if (this.poolLimit) this.addHandler(TRANSPORT_POOL_LIMIT_HANDLER, this); }, getRequestByHash: function (requestData) { function findIdleRequest(transport) { for (var id in transport.requests) { var request = transport.requests[id]; if (request.isIdle() && transport.requestQueue.indexOf(request) == -1) { delete transport.requests[id]; return request; } } } var requestHashId = this.poolHashGetter ? this.poolHashGetter(requestData) : requestData.origin ? requestData.origin.basisObjectId : "default"; var request = this.requests[requestHashId]; if (!request) { request = findIdleRequest(this) || new this.requestClass({ transport: this }); this.requests[requestHashId] = request; } return request; }, prepare: basis.fn.$true, prepareRequestData: basis.fn.$self, request: function (config) { if (!this.prepare()) return; var requestData = this.prepareRequestData(objectSlice(config)); var request = this.getRequestByHash(requestData); if (request.requestData) request.abort(); request.requestData = requestData; if (!this.poolLimit || this.inprogressRequests.length < this.poolLimit) { request.doRequest(); } else { this.requestQueue.push(request); request.setState(STATE.PROCESSING); } return request; }, abort: function () { for (var request; request = this.requestQueue.pop();) request.setState(STATE.ERROR); for (var request; request = this.inprogressRequests.pop();) request.abort(); }, stop: function () { if (!this.stopped) { this.stoppedRequests = this.inprogressRequests.concat(this.requestQueue); this.abort(); this.stopped = true; } }, resume: function () { if (this.stopped) { for (var request; request = this.stoppedRequests.pop();) this.request(request.requestData); this.stopped = false; } }, destroy: function () { for (var id in this.requests) this.requests[id].destroy(); this.requests = null; this.inprogressRequests = null; this.requestQueue = null; this.stoppedRequests = null; Emitter.prototype.destroy.call(this); } }); module.exports = { createTransportEvent: createTransportEvent, createRequestEvent: createRequestEvent, transportDispatcher: transportDispatcher, AbstractRequest: AbstractRequest, AbstractTransport: AbstractTransport }; }, "v.js": function (exports, module, basis, global, __filename, __dirname, require, resource, asset) { var namespace = "basis.net.service"; var basisEvent = basis.require("./3.js"); var createEvent = basisEvent.create; var Emitter = basisEvent.Emitter; var AjaxTransport = basis.require("./w.js").Transport; var createAction = basis.require("./y.js").create; function removeTransportFromService(service, transport) { service.inprogressRequests = service.inprogressRequests.filter(function (request) { return request.transport !== transport; }); basis.array.remove(service.inprogressTransports, transport); if (service.inprogressTransports.indexOf(transport) == -1 && (!service.stoppedTransports || service.stoppedTransports.indexOf(transport) == -1)) transport.removeHandler(TRANSPORT_HANDLER, service); } var TRANSPORT_HANDLER = { destroy: function (transport) { if (this.stoppedTransports) basis.array.remove(this.stoppedTransports, transport); removeTransportFromService(this, transport); } }; var SERVICE_HANDLER = { start: function (service, request) { this.inprogressRequests.push(request); if (basis.array.add(this.inprogressTransports, request.transport) && (!service.stoppedTransports || service.stoppedTransports.indexOf(request.transport) == -1)) request.transport.addHandler(TRANSPORT_HANDLER, this); }, complete: function (service, request) { basis.array.remove(this.inprogressRequests, request); var hasOtherTransportRequests = this.inprogressRequests.some(function (request) { return request.transport === this.transport; }, request); if (!hasOtherTransportRequests) removeTransportFromService(this, request.transport); } }; var Service = Emitter.subclass({ className: namespace + ".Service", inprogressRequests: null, inprogressTransports: null, stoppedTransports: null, transportClass: AjaxTransport, emit_sessionOpen: createEvent("sessionOpen"), emit_sessionClose: createEvent("sessionClose"), emit_sessionFreeze: createEvent("sessionFreeze"), emit_sessionUnfreeze: createEvent("sessionUnfreeze"), secure: false, prepare: basis.fn.$true, signature: basis.fn.$undef, isSessionExpiredError: basis.fn.$false, init: function () { if (this.requestClass) basis.dev.warn(namespace + ".Service#requestClass is not supported; set requestClass via transportClass"); Emitter.prototype.init.call(this); if ("isSecure" in this) { basis.dev.warn(namespace + ".Service#isSecure is deprecated and will be remove in next version. Please, use Service.secure property instead"); this.secure = this.isSecure; } this.inprogressRequests = []; this.inprogressTransports = []; var TransportClass = this.transportClass; this.transportClass = TransportClass.subclass({ service: this, secure: this.secure, emit_failure: function (request, error) { TransportClass.prototype.emit_failure.call(this, request, error); if (this.secure && this.service.isSessionExpiredError(request)) { this.service.freeze(); if (this.service.stoppedTransports) if (basis.array.add(this.service.stoppedTransports, this)) this.addHandler(TRANSPORT_HANDLER, this.service); this.stop(); } }, init: function () { TransportClass.prototype.init.call(this); if ("needSignature" in this) { basis.dev.warn("`needSignature` property is deprecated and will be remove in next version. Please, use `secure` property instead"); this.secure = this.needSignature; } }, request: function (requestData) { if (!this.service.prepare(this, requestData)) return; if (this.secure && !this.service.sign(this, requestData)) return; return TransportClass.prototype.request.call(this, requestData); } }); this.addHandler(SERVICE_HANDLER); }, sign: function (transport, requestData) { if (this.sessionKey) { this.signature(transport, this.sessionData, requestData); return true; } else { basis.dev.warn("Request ignored. Service have no session key"); } }, openSession: function (sessionKey, sessionData) { this.sessionKey = sessionKey; this.sessionData = sessionData || sessionKey; this.unfreeze(); this.emit_sessionOpen(); }, closeSession: function () { this.freeze(); this.emit_sessionClose(); }, freeze: function () { if (!this.sessionKey) return; this.sessionKey = null; this.sessionData = null; this.stoppedTransports = this.inprogressTransports.filter(function (transport) { return transport.secure; }); for (var i = 0, transport; transport = this.inprogressTransports[i]; i++) transport.stop(); this.emit_sessionFreeze(); }, unfreeze: function () { if (this.stoppedTransports) { for (var i = 0, transport; transport = this.stoppedTransports[i]; i++) transport.resume(); this.stoppedTransports = null; } this.emit_sessionUnfreeze(); }, createTransport: function (config) { return new this.transportClass(config); }, createAction: function (config) { return createAction(basis.object.complete({ service: this }, config)); }, destroy: function () { this.inprogressRequests = null; this.inprogressTransports = null; this.stoppedTransports = null; this.sessionKey = null; this.sessionData = null; Emitter.prototype.destroy.call(this); } }); module.exports = { Service: Service }; }, "w.js": function (exports, module, basis, global, __filename, __dirname, require, resource, asset) { var namespace = "basis.net.ajax"; var escapeValue = global.encodeURIComponent; var FormData = global.FormData; var XMLHttpRequest = global.XMLHttpRequest; var extend = basis.object.extend; var objectSlice = basis.object.slice; var objectMerge = basis.object.merge; var objectIterate = basis.object.iterate; var ua = basis.require("./x.js"); var basisNet = basis.require("./u.js"); var createTransportEvent = basisNet.createTransportEvent; var createRequestEvent = basisNet.createRequestEvent; var AbstractRequest = basisNet.AbstractRequest; var AbstractTransport = basisNet.AbstractTransport; var STATE_UNSENT = 0; var STATE_OPENED = 1; var STATE_DONE = 4; var STATE = basis.require("./g.js").STATE; var METHODS = "HEAD GET POST PUT PATCH DELETE TRACE LINK UNLINK CONNECT".split(" "); var IS_METHOD_WITH_BODY = /^(POST|PUT|PATCH|LINK|UNLINK)$/i; var URL_METHOD_PREFIX = new RegExp("^(" + METHODS.join("|") + ")\\s+", "i"); var JSON_CONTENT_TYPE = /^application\/json/i; var XHRSupport = "native"; var createXmlHttpRequest = function () { if ("XMLHttpRequest" in global) return function () { return new XMLHttpRequest(); }; var ActiveXObject = global.ActiveXObject; if (ActiveXObject) { var progID = [ "MSXML2.XMLHTTP.6.0", "MSXML2.XMLHTTP.3.0", "MSXML2.XMLHTTP", "Microsoft.XMLHTTP" ]; for (var i = 0; XHRSupport = progID[i]; i++) try { if (new ActiveXObject(XHRSupport)) return function () { return new ActiveXObject(XHRSupport); }; } catch (e) { } } throw new Error(XHRSupport = "XMLHttpRequest is not supported!"); }(); function setRequestHeaders(xhr, requestData) { var headers = {}; if (IS_METHOD_WITH_BODY.test(requestData.method)) { if (!FormData || requestData.body instanceof FormData == false) headers["Content-Type"] = requestData.contentType + (requestData.encoding ? ";charset=" + requestData.encoding : ""); } else { if (ua.test("ie")) { headers["If-Modified-Since"] = "Thu, 01 Jan 1970 00:00:00 GMT"; } } headers = basis.object.merge(headers, requestData.headers); objectIterate(requestData.headers, function (name, value) { if (name.trim().toLowerCase() == "content-type") { basis.dev.warn("basis.net.ajax: `Content-Type` header found in request data, use contentType and encoding properties instead"); headers["Content-Type"] = value; } else headers[name] = value; }); objectIterate(headers, function (key, value) { if (value != null && typeof value != "function") xhr.setRequestHeader(key, value); else delete headers[key]; }); return headers; } function setResponseType(xhr, requestData) { if (requestData.responseType && requestData.asynchronous && "responseType" in xhr) try { xhr.responseType = requestData.responseType; } catch (e) { basis.dev.warn("Can't set resposeType `" + requestData.responseType + "` to XMLHttpRequest", requestData); } } function safeJsonParse(content) { try { return basis.json.parse(content); } catch (e) { var url = arguments[1]; basis.dev.warn("basis.net.ajax: Can't parse JSON from " + url, { url: url, content: content }); } } function readyStateChangeHandler(readyState) { var xhr = this.xhr; this.sendDelayTimer_ = clearTimeout(this.sendDelayTimer_); if (!xhr) return; if (typeof readyState != "number") readyState = xhr.readyState; if (readyState == this.prevReadyState_) return; this.prevReadyState_ = readyState; if (this.debug) basis.dev.log("State: (" + readyState + ") " + [ "UNSENT", "OPENED", "HEADERS_RECEIVED", "LOADING", "DONE" ][readyState]); this.emit_readyStateChanged(readyState); if (readyState == STATE_DONE) { xhr.onreadystatechange = basis.fn.$undef; this.clearTimeout(); this.timer_ = setTimeout(processResponse.bind(this), 10); return; } this.setState(STATE.PROCESSING); } function processResponse() { var newState; var newStateData; this.clearTimeout(); this.processResponse(); if (this.isSuccessful()) { newState = STATE.READY; this.emit_success(this.getResponseData()); } else { newState = STATE.ERROR; newStateData = this.getResponseError(); this.emit_failure(newStateData); } this.emit_complete(); this.setState(newState, newStateData); } function abortHandler() { this.clearTimeout(); this.emit_abort(); this.emit_complete(this); this.setState(this.stateOnAbort); } var Request = AbstractRequest.subclass({ className: namespace + ".Request", requestStartTime: 0, timeout: 30000, timer_: null, sendDelay: null, sendDelayTimer_: null, lastRequestUrl_: null, debug: false, emit_readyStateChanged: createRequestEvent("readyStateChanged"), init: function () { AbstractRequest.prototype.init.call(this); this.xhr = createXmlHttpRequest(); }, isIdle: function () { return this.xhr.readyState == STATE_DONE || this.xhr.readyState == STATE_UNSENT; }, isSuccessful: function () { var status = this.xhr.status; return status >= 200 && status < 300 || status == 304; }, processResponse: function () { this.update({ contentType: this.xhr.getResponseHeader("content-type"), status: this.xhr.status }); }, getResponseData: function () { var xhr = this.xhr; if (!xhr.responseType) if (this.responseType == "json" || JSON_CONTENT_TYPE.test(this.data.contentType)) return safeJsonParse(xhr.responseText, this.lastRequestUrl_); if ("response" in xhr) return xhr.response; return xhr.responseText; }, processErrorResponse: function () { basis.dev.warn(namespace + ".Request#processErrorResponse is deprecated now, use Request#getResponseError instead"); return this.getResponseError(); }, getResponseError: function () { var xhr = this.xhr; var msg = !this.responseType ? xhr.responseText : xhr.response || xhr.statusText || "Error"; return { code: "SERVER_ERROR", msg: msg, response: this.getResponseData() }; }, prepare: basis.fn.$true, prepareRequestData: function (requestData) { var params = []; var url = requestData.url; requestData = objectSlice(requestData); for (var key in requestData.params) { var value = requestData.params[key]; if (value == null || value.toString() == null) continue; params.push(escapeValue(key) + "=" + escapeValue(value.toString())); } params = params.join("&"); if (!requestData.body && IS_METHOD_WITH_BODY.test(requestData.method)) { requestData.body = params || ""; params = ""; } if (requestData.routerParams) url = url.replace(/:([a-z\_\-][a-z0-9\_\-]+)/gi, function (m, key) { if (key in requestData.routerParams) return requestData.routerParams[key]; else return m; }); if (params) url += (url.indexOf("?") == -1 ? "?" : "&") + params; requestData.requestUrl = url; return requestData; }, doRequest: function () { this.send(this.prepareRequestData(this.requestData)); }, send: function (requestData) { this.update({ contentType: "", status: "" }); if (ua.test("gecko1.8.1-") && requestData.asynchronous) this.xhr = createXmlHttpRequest(); this.emit_start(); var xhr = this.xhr; this.prevReadyState_ = -1; xhr.onreadystatechange = readyStateChangeHandler.bind(this); xhr.onabort = abortHandler.bind(this); if (!requestData.asynchronous) readyStateChangeHandler.call(this, STATE_UNSENT); xhr.open(requestData.method, requestData.requestUrl, requestData.asynchronous); this.lastRequestUrl_ = requestData.requestUrl; setResponseType(xhr, requestData); this.responseType = requestData.responseType || ""; var requestHeaders = setRequestHeaders(xhr, requestData); this.setTimeout(this.timeout); var payload = null; if (IS_METHOD_WITH_BODY.test(requestData.method)) { payload = requestData.body; if (typeof payload == "function") payload = payload.call(requestData.bodyContext); if (JSON_CONTENT_TYPE.test(requestHeaders["Content-Type"])) if (typeof payload != "string") payload = JSON.stringify(payload); if (ua.test("ie9-")) { if (typeof payload == "object" && typeof payload.documentElement != "undefined" && typeof payload.xml == "string") payload = payload.xml; else if (typeof payload == "string") payload = payload.replace(/\r/g, ""); else if (payload == null || payload == "") payload = "[No data]"; } } if (this.sendDelay) { if (this.sendDelayTimer_) this.sendDelayTimer_ = clearTimeout(this.sendDelayTimer_); this.sendDelayTimer_ = setTimeout(function () { this.sendDelayTimer_ = null; if (this.xhr === xhr && xhr.readyState == STATE_OPENED) xhr.send(payload); }.bind(this), this.sendDelay); } else xhr.send(payload); if (this.debug) basis.dev.log("Request over, waiting for response"); return true; }, repeat: function () { if (this.requestData) { this.abort(); this.doRequest(); } }, abort: function () { if (!this.isIdle()) { this.clearTimeout(); this.xhr.abort(); if (this.xhr.readyState != STATE_DONE && this.xhr.readyState != STATE_UNSENT) readyStateChangeHandler.call(this, STATE_DONE); } }, setTimeout: function (timeout) { if (!this.xhr.asynchronous) return; if ("ontimeout" in this.xhr) { this.xhr.timeout = timeout; this.xhr.ontimeout = this.timeoutAbort.bind(this); } else this.timer_ = setTimeout(this.timeoutAbort.bind(this), timeout); }, clearTimeout: function () { if (this.timer_) this.timer_ = clearTimeout(this.timer_); }, timeoutAbort: function () { this.update({ error: { code: "TIMEOUT_ERROR", message: "Timeout error" } }); this.emit_timeout(this); this.abort(); }, destroy: function () { this.abort(); this.xhr = null; AbstractRequest.prototype.destroy.call(this); } }); var Transport = AbstractTransport.subclass({ className: namespace + ".Transport", requestClass: Request, emit_readyStateChanged: createTransportEvent("readyStateChanged"), asynchronous: true, method: "GET", contentType: "application/x-www-form-urlencoded", encoding: null, requestHeaders: basis.Class.extensibleProperty(), responseType: "", params: null, routerParams: null, url: "", body: null, bodyContext: null, init: function () { AbstractTransport.prototype.init.call(this); if ("postBody" in this) { basis.dev.warn("basis.net.ajax.Transport: `postBody` paramenter is deprecated, use `body` instead"); if (this.body == null) this.body = this.postBody; this.postBody = null; } this.params = objectSlice(this.params); this.routerParams = objectSlice(this.routerParams); }, setParam: function (name, value) { this.params[name] = value; }, setParams: function (params) { this.clearParams(); for (var key in params) this.setParam(key, params[key]); }, removeParam: function (name) { delete this.params[name]; }, clearParams: function () { for (var key in this.params) delete this.params[key]; }, prepareRequestData: function (requestData) { if (!requestData.url && !this.url) throw new Error("URL is not defined"); extend(requestData, { headers: objectMerge(this.requestHeaders, requestData.headers), params: objectMerge(this.params, requestData.params), routerParams: objectMerge(this.routerParams, requestData.routerParams) }); if ("postBody" in requestData) { basis.dev.warn("basis.net.ajax.Transport: `postBody` paramenter is deprecated, use `body` instead"); if (this.body == null) requestData.body = requestData.postBody; requestData.postBody = null; } basis.object.complete(requestData, { asynchronous: this.asynchronous, url: this.url, method: this.method, contentType: this.contentType, encoding: this.encoding, body: this.body, bodyContext: this.bodyContext, responseType: this.responseType }); var urlMethodPrefix = requestData.url.match(URL_METHOD_PREFIX); if (urlMethodPrefix) { requestData.method = urlMethodPrefix[1]; requestData.url = requestData.url.substr(urlMethodPrefix[0].length); } return requestData; } }); module.exports = { Request: Request, Transport: Transport, request: function (config, successCallback, failureCallback) { if (typeof config == "string") config = { url: config, asynchronous: !!(successCallback || failureCallback) }; var transport = new Transport(config); transport.addHandler({ success: successCallback && function (sender, req, data) { successCallback(data); }, failure: failureCallback && function (sender, req, error) { failureCallback(error); }, complete: function () { basis.nextTick(function () { transport.destroy(); }); } }); var req = transport.request(); if (!req.requestData.asynchronous) return req.getResponseData(); } }; }, "x.js": function (exports, module, basis, global, __filename, __dirname, require, resource, asset) { var userAgent = global.navigator && global.navigator.userAgent || ""; var opera = global.opera; var versions = {}; var answers = {}; var browserPrettyName = "unknown"; var browserNames = { "MSIE": [ "Internet Explorer", "msie", "ie" ], "Gecko": [ "Gecko", "gecko" ], "Safari": [ "Safari", "safari" ], "iPhone OS": [ "iPhone", "iphone" ], "AdobeAir": [ "AdobeAir", "air" ], "AppleWebKit": ["WebKit"], "Chrome": [ "Chrome", "chrome" ], "FireFox": [ "FireFox", "firefox", "ff" ], "Iceweasel": [ "FireFox", "firefox", "ff" ], "Shiretoko": [ "FireFox", "firefox", "ff" ], "Opera": [ "Opera", "opera" ] }; for (var name in browserNames) { var prefix = name; if (name == "MSIE" && opera) continue; if (name == "Safari" && /chrome/i.test(userAgent)) continue; if (name == "AppleWebKit" && /iphone/i.test(userAgent)) continue; if (name == "MSIE" && /Trident\/\d+/i.test(userAgent) && /rv:\d+/i.test(userAgent)) prefix = "rv"; if (userAgent.match(new RegExp(prefix + ".(\\d+(\\.\\d+)*)", "i"))) { var names = browserNames[name]; var version = opera && typeof opera.version == "function" ? opera.version() : RegExp.$1; var verNumber = versionToInt(version); browserPrettyName = names[0] + " " + version; for (var j = 0; j < names.length; j++) versions[names[j].toLowerCase()] = verNumber; } } function versionToInt(version) { var base = 1000000; var part = String(version).split("."); for (var i = 0, result = 0; i < 4 && i < part.length; i++, base /= 100) result += part[i] * base; return result; } function testBrowser(browserName) { var forTest = browserName.toLowerCase(); if (forTest in answers) return answers[forTest]; var m = forTest.match(/^([a-z]+)(([\d\.]+)([+-=]?))?$/i); if (m) { answers[forTest] = false; var name = m[1].toLowerCase(); var version = versionToInt(m[3]); var operation = m[4] || "="; var cmpVersion = versions[name]; if (cmpVersion) return answers[forTest] = !version || operation == "=" && cmpVersion == version || operation == "+" && cmpVersion >= version || operation == "-" && cmpVersion < version; } else { basis.dev.warn("Bad browser version description in Browser.test() function: " + forTest); } return false; } module.exports = { prettyName: browserPrettyName, is: testBrowser, test: function () { return basis.array(arguments).some(testBrowser); } }; }, "y.js": function (exports, module, basis, global, __filename, __dirname, require, resource, asset) { var STATE = basis.require("./g.js").STATE; var STATE_UNDEFINED = STATE.UNDEFINED; var STATE_READY = STATE.READY; var STATE_PROCESSING = STATE.PROCESSING; var STATE_ERROR = STATE.ERROR; var AjaxTransport = basis.require("./w.js").Transport; var Promise = basis.require("./z.js"); var nothingToDo = function () { }; var CALLBACK_HANDLER = { start: function (transport, request) { var origin = request.requestData.origin; this.start.call(request.requestData.origin); if (origin.state != STATE_PROCESSING) origin.setState(STATE_PROCESSING); }, success: function (transport, request, data) { var origin = request.requestData.origin; this.success.call(origin, data); if (origin.state == STATE_PROCESSING) origin.setState(STATE_READY); }, failure: function (transport, request, error) { var origin = request.requestData.origin; this.failure.call(origin, error); if (origin.state == STATE_PROCESSING) origin.setState(STATE_ERROR, error); }, abort: function (transport, request) { var origin = request.requestData.origin; this.abort.call(origin); if (origin.state == STATE_PROCESSING) origin.setState(transport.stateOnAbort || request.stateOnAbort || STATE_UNDEFINED); }, complete: function (transport, request) { this.complete.call(request.requestData.origin); } }; var DEFAULT_CALLBACK = { start: nothingToDo, success: nothingToDo, failure: nothingToDo, abort: nothingToDo, complete: nothingToDo }; var PROMISE_REQUEST_HANDLER = { success: function (request, data) { this.fulfill(data); }, abort: function () { this.reject("Request aborted"); }, failure: function (request, error) { this.reject(error); }, complete: function () { this.request.removeHandler(PROMISE_REQUEST_HANDLER, this); } }; function resolveTransport(config) { if (config.transport) return config.transport; if (config.service) return config.service.createTransport(config); if (config.createTransport) return config.createTransport(config); return new AjaxTransport(config); } function createAction(config) { config = basis.object.extend({ prepare: nothingToDo, request: nothingToDo }, config); if (typeof config.body == "function") { var bodyFn = config.body; config.body = function () { return bodyFn.apply(this.context, this.args); }; } var fn = basis.object.splice(config, [ "prepare", "request" ]); var callback = basis.object.merge(DEFAULT_CALLBACK, basis.object.splice(config, [ "start", "success", "failure", "abort", "complete" ])); var getTransport = basis.fn.lazyInit(function () { var transport = resolveTransport(config); transport.addHandler(CALLBACK_HANDLER, callback); return transport; }); return function action() { if (this.state != STATE_PROCESSING) { if (fn.prepare.apply(this, arguments)) { basis.dev.info("Prepare handler returns trulthy result. Operation aborted. Context: ", this); return Promise.reject("Prepare handler returns trulthy result. Operation aborted. Context: ", this); } var request; var requestData = basis.object.complete({ origin: this, bodyContext: { context: this, args: basis.array(arguments) } }, fn.request.apply(this, arguments)); if (typeof requestData.body == "function") { var bodyFn = requestData.body; requestData.body = function () { return bodyFn.apply(this.context, this.args); }; } if (request = getTransport().request(requestData)) return new Promise(function (fulfill, reject) { request.addHandler(PROMISE_REQUEST_HANDLER, { request: request, fulfill: fulfill, reject: reject }); }); return Promise.reject("Request is not performed"); } else { basis.dev.warn("Context in processing state. Operation aborted. Context: ", this); return Promise.reject("Context in processing state, request is not performed"); } }; } module.exports = { create: createAction }; }, "z.js": function (exports, module, basis, global, __filename, __dirname, require, resource, asset) { var PENDING = "pending"; var SEALED = "sealed"; var FULFILLED = "fulfilled"; var REJECTED = "rejected"; var NOOP = function () { }; var asyncQueue = []; var asyncTimer; function asyncFlush() { for (var i = 0; i < asyncQueue.length; i++) asyncQueue[i][0](asyncQueue[i][1]); asyncQueue = []; asyncTimer = false; } function asyncCall(callback, arg) { asyncQueue.push([ callback, arg ]); if (!asyncTimer) { asyncTimer = true; basis.nextTick(asyncFlush, 0); } } function invokeResolver(resolver, promise) { function resolvePromise(value) { resolve(promise, value); } function rejectPromise(reason) { reject(promise, reason); } try { resolver(resolvePromise, rejectPromise); } catch (e) { rejectPromise(e); } } function invokeCallback(subscriber) { var owner = subscriber.owner; var settled = owner.state_; var value = owner.data_; var callback = subscriber[settled]; var promise = subscriber.then; if (typeof callback === "function") { settled = FULFILLED; try { value = callback(value); } catch (e) { reject(promise, e); } } if (!handleThenable(promise, value)) { if (settled === FULFILLED) resolve(promise, value); if (settled === REJECTED) reject(promise, value); } } function handleThenable(promise, value) { var resolved; try { if (promise === value) throw new TypeError("A promises callback cannot return that same promise."); if (value && (typeof value === "function" || typeof value === "object")) { var then = value.then; if (typeof then === "function") { then.call(value, function (val) { if (!resolved) { resolved = true; if (value !== val) resolve(promise, val); else fulfill(promise, val); } }, function (reason) { if (!resolved) { resolved = true; reject(promise, reason); } }); return true; } } } catch (e) { if (!resolved) reject(promise, e); return true; } return false; } function resolve(promise, value) { if (promise === value || !handleThenable(promise, value)) fulfill(promise, value); } function fulfill(promise, value) { if (promise.state_ === PENDING) { promise.state_ = SEALED; promise.data_ = value; asyncCall(publishFulfillment, promise); } } function reject(promise, reason) { if (promise.state_ === PENDING) { promise.state_ = SEALED; promise.data_ = reason; asyncCall(publishRejection, promise); } } function publish(promise) { promise.then_ = promise.then_.forEach(invokeCallback); } function publishFulfillment(promise) { promise.state_ = FULFILLED; publish(promise); } function publishRejection(promise) { promise.state_ = REJECTED; publish(promise); } var Promise = function (resolver) { if (typeof resolver !== "function") throw new TypeError("Promise constructor takes a function argument"); if (this instanceof Promise === false) throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function."); this.then_ = []; invokeResolver(resolver, this); }; Promise.prototype = { constructor: Promise, state_: PENDING, then_: null, data_: undefined, then: function (onFulfillment, onRejection) { var subscriber = { owner: this, then: new this.constructor(NOOP), fulfilled: onFulfillment, rejected: onRejection }; if (this.state_ === FULFILLED || this.state_ === REJECTED) { asyncCall(invokeCallback, subscriber); } else { this.then_.push(subscriber); } return subscriber.then; }, "catch": function (onRejection) { return this.then(null, onRejection); } }; Promise.all = function (promises) { var Class = this; if (!Array.isArray(promises)) throw new TypeError("You must pass an array to Promise.all()."); return new Class(function (resolve, reject) { var results = []; var remaining = 0; function resolver(index) { remaining++; return function (value) { results[index] = value; if (!--remaining) resolve(results); }; } for (var i = 0, promise; i < promises.length; i++) { promise = promises[i]; if (promise && typeof promise.then === "function") promise.then(resolver(i), reject); else results[i] = promise; } if (!remaining) resolve(results); }); }; Promise.race = function (promises) { var Class = this; if (!Array.isArray(promises)) throw new TypeError("You must pass an array to Promise.race()."); return new Class(function (resolve, reject) { for (var i = 0, promise; i < promises.length; i++) { promise = promises[i]; if (promise && typeof promise.then === "function") promise.then(resolve, reject); else resolve(promise); } }); }; Promise.resolve = function (value) { var Class = this; if (value && typeof value === "object" && value.constructor === Class) return value; return new Class(function (resolve) { resolve(value); }); }; Promise.reject = function (reason) { var Class = this; return new Class(function (resolve, reject) { reject(reason); }); }; module.exports = Promise; }, "10.js": function (exports, module, basis, global, __filename, __dirname, require, resource, asset) { var namespace = "basis.router"; var location = global.location; var document = global.document; var eventUtils = basis.require("./e.js"); var Value = basis.require("./g.js").Value; var parsePath = basis.require("./2g.js").parsePath; var stringify = basis.require("./2g.js").stringify; var docMode = document.documentMode; var eventSupport = "onhashchange" in global && (docMode === undefined || docMode > 7); var CHECK_INTERVAL = 50; var arrayFrom = basis.array.from; var allRoutes = []; var plainRoutesByPath = {}; var started = false; var currentPath; var timer; var routeHistory = []; var checkDelayTimer; var log = []; var flushLog = function (message) { var entries = log.splice(0); if (module.exports.debug) basis.dev.info.apply(basis.dev, [message].concat(entries.length ? entries : "\n<no actions>")); }; var ROUTE_ENTER = 1; var ROUTE_MATCH = 2; var ROUTE_LEAVE = 4; function routeEnter(route, nonInitedOnly) { var callbacks = arrayFrom(route.callbacks_); for (var i = 0, item; item = callbacks[i]; i++) if ((!nonInitedOnly || !item.enterInited) && item.callback.enter) { item.enterInited = true; item.callback.enter.call(item.context); log.push("\n", { type: "enter", path: route.path, cb: item, route: route }); } } function routeLeave(route) { var callbacks = arrayFrom(route.callbacks_); for (var i = 0, item; item = callbacks[i]; i++) if (item.callback.leave) { item.callback.leave.call(item.context); log.push("\n", { type: "leave", path: route.path, cb: item, route: route }); } } function routeMatch(route, nonInitedOnly) { var callbacks = arrayFrom(route.callbacks_); for (var i = 0, item; item = callbacks[i]; i++) if ((!nonInitedOnly || !item.matchInited) && item.callback.match) { item.matchInited = true; item.callback.match.apply(item.context, arrayFrom(route.value)); log.push("\n", { type: "match", path: route.path, cb: item, route: route, args: route.value }); } } var initSchedule = basis.asap.schedule(function (route) { if (route.value) { routeEnter(route, true); routeMatch(route, true); flushLog(namespace + ": init callbacks for route `" + route.path + "`"); } }); var flushSchedule = basis.asap.schedule(function (route) { route.flush(true); }); var Route = basis.Token.subclass({ className: namespace + ".Route", path: null, matched: null, ast_: null, names_: null, regexp_: null, params_: null, callbacks_: null, init: function (parseInfo) { var regexp = parseInfo.regexp; basis.Token.prototype.init.call(this, null); this.path = parseInfo.path; this.matched = this.as(Boolean); this.ast_ = parseInfo.ast; this.names_ = parseInfo.params; this.regexp_ = regexp; this.params_ = {}; this.callbacks_ = []; }, matches_: function (path) { return { pathMatch: path.match(this.regexp_), query: null }; }, processLocation_: function (newPath) { initSchedule.remove(this); var resultFlags = 0; var match = this.matches_(newPath); if (match.pathMatch) { if (!this.value) resultFlags |= ROUTE_ENTER; this.setMatch_(arrayFrom(match.pathMatch, 1), match.query); resultFlags |= ROUTE_MATCH; } else { if (this.value) { this.setMatch_(null); resultFlags |= ROUTE_LEAVE; } } return resultFlags; }, param: function (nameOrIdx) { var idx = typeof nameOrIdx == "number" ? nameOrIdx : this.names_.indexOf(nameOrIdx); if (idx in this.params_ == false) this.params_[idx] = this.as(function (value) { return value && value[idx]; }); return this.params_[idx]; }, setMatch_: function (match) { if (match) { match = match.slice(0); for (var key in match) if (key in this.names_) match[this.names_[key]] = match[key]; } this.set(match); }, add: function (callback, context) { return add(this, callback, context); }, remove: function (callback, context) { remove(this, callback, context); } }); var ParametrizedRoute = Route.subclass({ className: namespace + ".ParametrizedRoute", params: null, normalize: basis.fn.$undef, paramsConfig_: null, init: function (parseInfo, config) { Route.prototype.init.apply(this, arguments); this.paramsConfig_ = this.constructParamsConfig_(config.params); if (config.normalize) { if (typeof config.normalize === "function") { this.normalize = config.normalize; } else { basis.dev.warn(namespace + ": expected normalize to be function, but got ", config.normalize, " - ignore"); } } this.constructParams_(); }, constructParamsConfig_: function (paramsConfig) { var result = {}; basis.object.iterate(paramsConfig, function (key, transform) { if (typeof transform === "function") { var deserialize; var serialize; var defaultValue; if ("DEFAULT_VALUE" in transform) defaultValue = transform.DEFAULT_VALUE; else defaultValue = transform(); if ("deserialize" in transform) { if (typeof transform.deserialize === "function") { deserialize = transform.deserialize; } else { basis.dev.warn(namespace + ": expected deserialize to be a function, but got ", deserialize, " - ignore"); deserialize = basis.fn.$self; } } else { deserialize = basis.fn.$self; } if ("serialize" in transform) { if (typeof transform.serialize === "function") { serialize = transform.serialize; } else { basis.dev.warn(namespace + ": expected serialize to be a function, but got ", serialize, " - ignore"); serialize = basis.fn.$self; } } else { serialize = basis.fn.$self; } result[key] = { transform: transform, serialize: serialize, deserialize: deserialize, defaultValue: defaultValue, currentValue: defaultValue, nextValue: undefined }; } else { result[key] = { transform: basis.fn.$self, serialize: basis.fn.$self, deserialize: basis.fn.$self, defaultValue: undefined, currentValue: undefined, nextValue: undefined }; basis.dev.warn(namespace + ": expected param " + key + " to be function, but got ", transform, " using basis.fn.$self instead"); } }); return result; }, constructParams_: function () { var route = this; route.params = {}; route.attach(function (values) { basis.object.iterate(route.paramsConfig_, function (key, paramConfig) { if (values && key in values) Value.prototype.set.call(route.params[key], values[key]); else Value.prototype.set.call(route.params[key], paramConfig.defaultValue); }); }); basis.object.iterate(route.paramsConfig_, function (key, paramConfig) { var paramValue = new Value({ value: paramConfig.defaultValue, set: function (value) { if (!route.value) { basis.dev.warn(namespace + ": trying to set param " + key + " when route not matched - ignoring", { params: route.paramsConfig_ }); return; } flushSchedule.add(route); var newValue = paramConfig.transform(value, paramConfig.currentValue); paramConfig.nextValue = newValue; } }); route.params[key] = paramValue; }); }, calculateDelta_: function (nextValues) { var delta = null; basis.object.iterate(this.paramsConfig_, function (key, paramConfig) { if (paramConfig.currentValue !== nextValues[key]) { delta = delta || {}; delta[key] = paramConfig.currentValue; } }); return delta; }, setMatch_: function (pathMatch, query) { var paramsFromQuery = queryToParams(query); if (!pathMatch) { this.set(null); return; } var paramsFromPath = this.paramsArrayToObject_(pathMatch); var values = {}; for (var paramName in this.params) if (paramName in paramsFromPath) values[paramName] = paramsFromPath[paramName]; else if (paramName in paramsFromQuery) values[paramName] = paramsFromQuery[paramName]; var nextParams = {}; basis.object.iterate(this.paramsConfig_, function (key, paramConfig) { var deserialize = paramConfig.deserialize; var transform = paramConfig.transform; if (key in values) { var parsedValue = deserialize(values[key]); nextParams[key] = transform(parsedValue, paramConfig.currentValue); } else { nextParams[key] = paramConfig.defaultValue; } }, this); var delta = this.calculateDelta_(nextParams); this.normalize(nextParams, delta); basis.object.iterate(this.paramsConfig_, function (key, paramConfig) { var newValue; if (key in nextParams) newValue = paramConfig.transform(nextParams[key], paramConfig.currentValue); else newValue = paramConfig.defaultValue; paramConfig.currentValue = newValue; paramConfig.nextValue = newValue; }, this); var newRouteValue = {}; basis.object.iterate(this.paramsConfig_, function (key, paramConfig) { newRouteValue[key] = paramConfig.currentValue; }); this.set(newRouteValue); silentReplace(this.getCurrentPath_()); }, update: function (params, replace) { if (!this.value) { basis.dev.warn(namespace + ": trying to update when route not matched - ignoring", { path: this.path, params: params }); return; } basis.object.iterate(params, function (key, newValue) { if (key in this.params) { this.params[key].set(newValue); } else { basis.dev.warn(namespace + ": found param " + key + " not specified in config - ignoring", { params: this.paramsConfig_ }); } }, this); this.flush(replace); }, navigate: function (params, replace) { navigate(this.getPath(params), replace); }, getPath: function (specifiedParams) { var params = {}; specifiedParams = specifiedParams || {}; for (var key in specifiedParams) if (!(key in this.paramsConfig_)) basis.dev.warn(namespace + ": found param " + key + " not specified in config - ignoring", { params: this.paramsConfig_ }); basis.object.iterate(this.paramsConfig_, function (key, paramConfig) { if (key in specifiedParams) params[key] = paramConfig.transform(specifiedParams[key], paramConfig.defaultValue); else params[key] = paramConfig.defaultValue; }, this); var serialized = {}; basis.object.iterate(this.paramsConfig_, function (key, paramConfig) { serialized[key] = paramConfig.serialize(params[key]); }); return stringify(this.ast_, serialized, this.areModified_(params)); }, flush: function (replace) { navigate(this.getCurrentPath_(), replace); }, getCurrentPath_: function () { var paramsNextValues = {}; basis.object.iterate(this.paramsConfig_, function (key, paramConfig) { paramsNextValues[key] = paramConfig.nextValue; }); return this.getPath(paramsNextValues); }, areModified_: function (params) { var result = {}; basis.object.iterate(this.paramsConfig_, function (key, paramConfig) { result[key] = params[key] !== paramConfig.defaultValue; }); return result; }, paramsArrayToObject_: function (arr) { var result = {}; for (var paramIdx in arr) if (paramIdx in this.names_) if (arr[paramIdx]) result[this.names_[paramIdx]] = decodeURIComponent(arr[paramIdx]); return result; }, matches_: function (newLocation) { var pathAndQuery = newLocation.split("?"); var newPath = pathAndQuery[0]; var newQuery = pathAndQuery[1]; return { pathMatch: newPath.match(this.regexp_), query: newQuery }; }, destroy: function () { this.paramsConfig_ = null; this.params = null; flushSchedule.remove(this); basis.array.remove(allRoutes, this); Route.prototype.destroy.apply(this, arguments); } }); function start() { if (!started) { if (eventSupport) eventUtils.addHandler(global, "hashchange", checkUrl); else timer = setInterval(checkUrl, CHECK_INTERVAL); if (module.exports.debug) basis.dev.log(namespace + " started"); started = true; checkUrl(); } } function stop() { if (started) { started = false; if (eventSupport) eventUtils.removeHandler(global, "hashchange", checkUrl); else clearInterval(timer); if (module.exports.debug) basis.dev.log(namespace + " stopped"); } } function preventRecursion(path) { if (checkDelayTimer) return true; var currentTime = Date.now(); routeHistory = routeHistory.filter(function (item) { return currentTime - item.time < 200; }); var last = basis.array.lastSearch(routeHistory, path, "path"); if (last && basis.array.lastSearch(routeHistory, path, "path", routeHistory.lastSearchIndex)) { checkDelayTimer = setTimeout(function () { checkDelayTimer = null; checkUrl(); }, 200); return true; } routeHistory.push({ time: Date.now(), path: path }); } function queryToParams(query) { if (!query) return {}; var result = {}; var pairs = query.split("&"); for (var i = 0; i < pairs.length; i++) { var pair = pairs[i].split("="); var key = decodeURIComponent(pair[0]); var value = decodeURIComponent(pair[1]); result[key] = value; } return result; } function checkUrl() { var newPath = location.hash.substr(1) || ""; if (newPath != currentPath) { if (preventRecursion(newPath)) return; currentPath = newPath; var routesToLeave = []; var routesToEnter = []; var routesToMatch = []; allRoutes.forEach(function (route) { var flags = route.processLocation_(newPath); if (flags & ROUTE_LEAVE) routesToLeave.push(route); if (flags & ROUTE_ENTER) routesToEnter.push(route); if (flags & ROUTE_MATCH) routesToMatch.push(route); }); for (var i = 0; i < routesToLeave.length; i++) routeLeave(routesToLeave[i]); for (var i = 0; i < routesToEnter.length; i++) routeEnter(routesToEnter[i]); for (var i = 0; i < routesToMatch.length; i++) routeMatch(routesToMatch[i]); flushLog(namespace + ": hash changed to \"" + newPath + "\""); } else { allRoutes.forEach(function (route) { if (route.value) { routeEnter(route, true); routeMatch(route, true); } }); flushLog(namespace + ": checkUrl()"); } } function createRoute(parseInfo, config) { if (config) return new ParametrizedRoute(parseInfo, config); else return new Route(parseInfo); } function get(params) { var path = params.path; var config = params.config; if (path instanceof Route) return path; var route; if (!config) route = plainRoutesByPath[path]; if (!route && params.autocreate) { var parseInfo = Object.prototype.toString.call(path) == "[object RegExp]" ? { path: path, regexp: path, ast: null, params: [] } : parsePath(path); route = createRoute(parseInfo, config); allRoutes.push(route); if (route instanceof ParametrizedRoute == false) plainRoutesByPath[path] = route; if (typeof currentPath == "string") { var flags = route.processLocation_(currentPath); if (flags & ROUTE_ENTER) routeEnter(route); if (flags & ROUTE_MATCH) routeMatch(route); } } return route; } function add(path, callback, context) { var route = get({ path: path, autocreate: true }); route.callbacks_.push({ cb_: callback, context: context, callback: typeof callback != "function" ? callback || {} : { match: callback } }); initSchedule.add(route); return route; } function remove(route, callback, context) { var route = get({ path: route }); if (!route) return; for (var i = 0, cb; cb = route.callbacks_[i]; i++) { if (cb.cb_ === callback && cb.context === context) { route.callbacks_.splice(i, 1); if (route.value && callback && callback.leave) { callback.leave.call(context); if (module.exports.debug) basis.dev.info(namespace + ": add handler for route `" + path + "`\n", { type: "leave", path: route.path, cb: callback.leave, route: route }); } if (!route.callbacks_.length) { if ((!route.handler || !route.handler.handler) && !route.matched.handler) { basis.array.remove(allRoutes, route); if (!(route instanceof ParametrizedRoute)) delete plainRoutesByPath[route.path]; } } return; } } basis.dev.warn(namespace + ": no callback removed", { callback: callback, context: context }); } function navigate(path, replace) { if (replace) location.replace(location.pathname + "#" + path); else location.hash = path; if (started) checkUrl(); } function silentReplace(path) { currentPath = path; location.replace(location.pathname + "#" + path); } start(); module.exports = { debug: false, start: start, stop: stop, checkUrl: checkUrl, navigate: navigate, add: add, remove: remove, route: function (path, config) { return get({ path: path, autocreate: true, config: config }); } }; }, "2g.js": function (exports, module, basis, global, __filename, __dirname, require, resource, asset) { var TYPE = { PLAIN_PARAM: "PLAIN_PARAM", ANY_PARAM: "ANY_PARAM", WORD: "WORD", GROUP: "GROUP", GROUP_OPTION: "GROUP_OPTION" }; function parsePath(route) { var value = String(route || ""); var params = []; function findWord(offset) { return value.substr(offset).match(/^\w+/); } function getOption(i) { return parse(i + 1, ")", "|"); } function getGroup(i) { var res; var result = ""; var options = []; while (res = getOption(i)) { options.push({ type: TYPE.GROUP_OPTION, children: res.ast }); i = res.offset; result += res.result; if (res.stoppedAt == ")") { return { type: TYPE.GROUP, options: options, result: result, offset: i }; } else { result += "|"; } } return null; } function parse(offset, stopChar, anotherStopChar) { var result = ""; var res; var curWord = ""; var ast = []; function putCurrentWord() { if (curWord) { ast.push({ type: TYPE.WORD, name: curWord }); curWord = ""; } } for (var i = offset; i < value.length; i++) { var c = value.charAt(i); switch (c) { case stopChar: case anotherStopChar: putCurrentWord(); return { result: result, offset: i, stoppedAt: c, ast: ast }; case "\\": var nextChar = value.charAt(++i); result += "\\" + nextChar; curWord += nextChar; break; case "|": result += stopChar != ")" ? "\\|" : "|"; curWord += "|"; break; case "(": if (res = getGroup(i)) { i = res.offset; result += "(?:" + res.result + ")?"; putCurrentWord(); ast.push({ type: TYPE.GROUP, options: res.options }); } else { result += "\\("; curWord += "("; } break; case ":": putCurrentWord(); if (res = findWord(i + 1)) { i += res[0].length; result += "([^/]+)"; params.push(res[0]); ast.push({ type: TYPE.PLAIN_PARAM, name: res[0] }); } else { result += ":"; } break; case "*": putCurrentWord(); if (res = findWord(i + 1)) { i += res[0].length; result += "(.*?)"; params.push(res[0]); ast.push({ type: TYPE.ANY_PARAM, name: res[0] }); } else { result += "\\*"; } break; default: result += basis.string.forRegExp(c); curWord += c; } } putCurrentWord(); return stopChar ? null : { regexpStr: result, ast: ast }; } var parsingResult = parse(0); var regexp = new RegExp("^" + parsingResult.regexpStr + "$", "i"); return { path: route, regexp: regexp, params: params, ast: parsingResult.ast }; } function stringifyGroup(group, values, areModified) { var defaultResult = null; for (var i = 0; i < group.options.length; i++) { var option = group.options[i]; var stringifiedOption = stringifyNodes(option.children, values, areModified, true); if (stringifiedOption.modifiedParamsWritten) return stringifiedOption; else if (!defaultResult) defaultResult = stringifiedOption; } return defaultResult; } function stringifyNodes(nodes, values, areModified) { var trailingDefaults = ""; var result = ""; var modifiedParamsWritten = null; function markAsWritten(paramName) { if (!modifiedParamsWritten) modifiedParamsWritten = {}; modifiedParamsWritten[paramName] = true; } function append(value) { result += trailingDefaults + value; trailingDefaults = ""; } nodes.forEach(function (node) { switch (node.type) { case TYPE.WORD: append(node.name); break; case TYPE.PLAIN_PARAM: case TYPE.ANY_PARAM: append(encodeURIComponent(values[node.name])); if (areModified[node.name]) markAsWritten(node.name); break; case TYPE.GROUP: var groupStringifyResult = stringifyGroup(node, values, areModified); if (groupStringifyResult.modifiedParamsWritten) { append(groupStringifyResult.result); basis.object.iterate(groupStringifyResult.modifiedParamsWritten, markAsWritten); } else { trailingDefaults += groupStringifyResult.result; } break; } }); return { result: result, modifiedParamsWritten: modifiedParamsWritten }; } function stringify(nodes, values, areModified) { var stringifyPathResult = stringifyNodes.apply(this, arguments); var modifiedParamsWritten = stringifyPathResult.modifiedParamsWritten; var result = stringifyPathResult.result; var query = []; basis.object.iterate(values, function (key, value) { if (modifiedParamsWritten && modifiedParamsWritten[key]) return; if (!areModified[key]) return; query.push(encodeURIComponent(key) + "=" + encodeURIComponent(value)); }); if (query.length) result += "?" + query.join("&"); return result; } module.exports = { parsePath: parsePath, stringify: stringify, TYPE: TYPE }; }, "11.js": function (exports, module, basis, global, __filename, __dirname, require, resource, asset) { var resolveValue = basis.require("./g.js").resolveValue; var document = global.document || { title: "unknown" }; var appTitle = document.title; var appInit = basis.fn.$undef; var appInjectPoint; var appEl; function updateTitle(value) { document.title = value; } function resolveNode(ref) { return typeof ref == "string" ? document.getElementById(ref) : ref; } function replaceNode(oldChild, newChild) { try { oldChild.parentNode.replaceChild(newChild, oldChild); return newChild; } catch (e) { return oldChild; } } function appendNode(container, newChild) { try { return container.appendChild(newChild); } catch (e) { return container.appendChild(document.createComment("")); } } var createApp = basis.fn.lazyInit(function (config) { var readyHandlers = []; var inited = false; var app = { inited: false, setTitle: function (title) { if (title != appTitle) { if (appTitle instanceof basis.Token) appTitle.detach(updateTitle); if (title instanceof basis.Token) { title.attach(updateTitle); updateTitle(title.get()); } else updateTitle(title); appTitle = title; } }, setElement: function (el) { el = resolveValue(app, app.setElement, el, "elementRA_"); if (el && el.element) el = el.element; var newAppEl = resolveNode(el); if (appEl === newAppEl) return; if (appEl) { appEl = replaceNode(appEl, newAppEl); return; } if (!appInjectPoint) appInjectPoint = { type: "append", node: document.body }; var node = resolveNode(appInjectPoint.node); appEl = newAppEl; if (!node) return; if (appInjectPoint.type == "append") appEl = appendNode(node, appEl); else appEl = replaceNode(node, appEl); }, ready: function (fn, context) { if (inited) fn.call(context, app); else readyHandlers.push({ fn: fn, context: context }); } }; if (typeof config === "function" && !basis.fn.isFactory(config)) config = { init: config }; else if (config.constructor !== Object) config = { element: config }; for (var key in config) { var value = config[key]; switch (key) { case "title": app.setTitle(value); break; case "container": appInjectPoint = { type: "append", node: value }; break; case "replace": appInjectPoint = { type: "replace", node: value }; break; case "element": appEl = value; break; case "init": appInit = typeof value == "function" ? value : appInit; break; default: basis.dev.warn("Unknown config property `" + key + "` for app, value:", value); } } basis.doc.body.ready(function () { var insertEl = appEl; var initResult = appInit.call(app); if (initResult) insertEl = initResult; appEl = null; app.setElement(insertEl); inited = true; app.inited = true; var handler; while (handler = readyHandlers.shift()) handler.fn.call(handler.context, app); }); return app; }); module.exports = { create: createApp }; } }; ; (function createBasisInstance(context, __basisFilename, __config) { "use strict"; var VERSION = "1.11.1"; var global = Function("return this")(); var process = global.process; var document = global.document; var location = global.location; var NODE_ENV = global !== context && process && process.argv ? global : false; var toString = Object.prototype.toString; var hasOwnProperty = Object.prototype.hasOwnProperty; var FACTORY = {}; var PROXY = {}; FACTORY = new (devVerboseName("basis.FACTORY", {}, function () { }))(); PROXY = new (devVerboseName("basis.PROXY", {}, function () { }))(); function genUID(len) { function base36(val) { return Math.round(val).toString(36); } var result = base36(10 + 25 * Math.random()); if (!len) len = 16; while (result.length < len) result += base36(new Date() * Math.random()); return result.substr(0, len); } var warnPropertyAccess = function () { try { if (Object.defineProperty) { var obj = {}; Object.defineProperty(obj, "foo", { get: function () { return true; } }); if (obj.foo === true) { return function (object, name, value, warning) { Object.defineProperty(object, name, { get: function () { consoleMethods.warn(warning); return value; }, set: function (newValue) { value = newValue; } }); }; } } } catch (e) { } return function () { }; }(); function extend(dest, source) { for (var key in source) dest[key] = source[key]; return dest; } function complete(dest, source) { for (var key in source) if (key in dest == false) dest[key] = source[key]; return dest; } function keys(object) { var result = []; for (var key in object) result.push(key); return result; } function values(object) { var result = []; for (var key in object) result.push(object[key]); return result; } function slice(source, keys) { var result = {}; if (!keys) return extend(result, source); for (var i = 0, key; key = keys[i++];) if (key in source) result[key] = source[key]; return result; } function splice(source, keys) { var result = {}; if (!keys) return extend(result, source); for (var i = 0, key; key = keys[i++];) if (key in source) { result[key] = source[key]; delete source[key]; } return result; } function merge() { var result = {}; for (var i = 0; i < arguments.length; i++) extend(result, arguments[i]); return result; } function iterate(object, callback, thisObject) { var result = []; for (var key in object) result.push(callback.call(thisObject, key, object[key])); return result; } function $undefined(value) { return value == undefined; } function $defined(value) { return value != undefined; } function $isNull(value) { return value == null || value == undefined; } function $isNotNull(value) { return value != null && value != undefined; } function $isSame(value) { return value === this; } function $isNotSame(value) { return value !== this; } function $self(value) { return value; } function $const(value) { return function () { return value; }; } function $false() { return false; } function $true() { return true; } function $null() { return null; } function $undef() { } var getter = function () { var GETTER_ID_PREFIX = "basisGetterId" + genUID() + "_"; var GETTER_ID = GETTER_ID_PREFIX + "root"; var ID = GETTER_ID_PREFIX; var SOURCE = GETTER_ID_PREFIX + "base"; var PARENT = GETTER_ID_PREFIX + "parent"; var getterSeed = 1; var pathCache = {}; function as(path) { var self = this; var wrapper; var result; var id; if (typeof path == "function" || typeof path == "string") { wrapper = resolveFunction(path, self[ID]); id = GETTER_ID_PREFIX + wrapper[ID]; if (hasOwnProperty.call(self, id)) return self[id]; if (typeof wrapper[SOURCE] == "function") wrapper = wrapper[SOURCE]; result = function (value) { return wrapper(self(value)); }; } else { var map = path; if (!map) return nullGetter; result = function (value) { return map[self(value)]; }; } result[PARENT] = self; result[ID] = getterSeed++; result[SOURCE] = path; result.__extend__ = getter; result.as = as; if (id) self[id] = result; return result; } function buildFunction(path) { return new Function("object", "return object != null ? object." + path + " : object"); } function resolveFunction(value, id) { var fn = value; var result; if (value && typeof value == "string") { if (hasOwnProperty.call(pathCache, value)) return pathCache[value]; fn = pathCache[value] = buildFunction(value); } if (typeof fn != "function") { basis.dev.warn("path for root getter should be function or non-empty string"); return nullGetter; } if (fn.__extend__ === getter) return fn; if (hasOwnProperty.call(fn, id)) return fn[id]; result = fn[id] = fn !== value ? fn : function (value) { return fn(value); }; result[ID] = getterSeed++; result[SOURCE] = value; result.__extend__ = getter; result.as = as; return result; } function getter(path, value) { var result = path && path !== nullGetter ? resolveFunction(path, GETTER_ID) : nullGetter; if (value || value === "") { basis.dev.warn("second argument for getter is deprecated, use `as` method of getter instead"); if (typeof value == "string") value = stringFunctions.formatter(value); return result.as(value); } return result; } getter.ID = ID; getter.SOURCE = SOURCE; getter.PARENT = PARENT; return getter; }(); var nullGetter = function () { var nullGetter = function () { }; nullGetter[getter.ID] = getter.ID + "nullGetter"; nullGetter.__extend__ = getter, nullGetter.as = function () { return nullGetter; }; return nullGetter; }(); function wrapper(key) { return function (value) { var result = {}; result[key] = value; return result; }; } function lazyInit(init, thisObject) { var inited = 0; var self; var data; return self = function () { if (!inited++) { self.inited = true; self.data = data = init.apply(thisObject || this, arguments); if (typeof data == "undefined") consoleMethods.warn("lazyInit function returns nothing:\n" + init); } return data; }; } function lazyInitAndRun(init, run, thisObject) { var inited = 0; var self; var data; return self = function () { if (!inited++) { self.inited = true; self.data = data = init.call(thisObject || this); if (typeof data == "undefined") consoleMethods.warn("lazyInitAndRun function returns nothing:\n" + init); } run.apply(data, arguments); return data; }; } function runOnce(run, thisObject) { var fired = 0; return function () { if (!fired++) return run.apply(thisObject || this, arguments); }; } function factory(fn) { if (typeof fn != "function") fn = getter(fn); var result = function (value) { return fn(value); }; result = devInfoResolver.patchFactory(result); result.factory = FACTORY; return result; } function isFactory(value) { return typeof value === "function" && value.factory === FACTORY; } function publicCallback(fn, permanent) { var name = "basisjsCallback" + genUID(); global[name] = permanent ? fn : function () { try { delete global[name]; } catch (e) { global[name] = undefined; } return fn.apply(this, arguments); }; return name; } function devVerboseName(name, args, fn) { return new Function(keys(args), "return {\"" + name + "\": " + fn + "\n}[\"" + name + "\"]").apply(null, values(args)); } var consoleMethods = function () { var console = global.console; var methods = { log: $undef, info: $undef, warn: $undef, error: $undef }; if (console) iterate(methods, function (methodName) { methods[methodName] = "bind" in Function.prototype && typeof console[methodName] == "function" ? Function.prototype.bind.call(console[methodName], console) : function () { Function.prototype.apply.call(console[methodName], console, arguments); }; }); return methods; }(); var setImmediate = global.setImmediate || global.msSetImmediate; var clearImmediate = global.clearImmediate || global.msSetImmediate; if (setImmediate) setImmediate = setImmediate.bind(global); if (clearImmediate) clearImmediate = clearImmediate.bind(global); if (!setImmediate) { (function () { var runTask = function () { var taskById = {}; var taskId = 0; setImmediate = function (fn) { if (typeof fn != "function") { consoleMethods.warn("basis.setImmediate() and basis.nextTick() accept functions only (call ignored)"); return; } taskById[++taskId] = { fn: fn, args: arrayFrom(arguments, 1) }; addToQueue(taskId); return taskId; }; clearImmediate = function (taskId) { delete taskById[taskId]; }; return function (taskId) { var task = taskById[taskId]; if (task) { delete taskById[taskId]; task.fn.apply(undefined, task.args); } asap.process(); }; }(); var addToQueue = function (taskId) { setTimeout(function () { runTask(taskId); }, 0); }; if (NODE_ENV && NODE_ENV.process && typeof process.nextTick == "function") { addToQueue = function (taskId) { process.nextTick(function () { runTask(taskId); }); }; } else { var postMessageSupported = global.postMessage && !global.importScripts; if (postMessageSupported) { var oldOnMessage = global.onmessage; global.onmessage = function () { postMessageSupported = false; }; global.postMessage("", "*"); global.onmessage = oldOnMessage; } if (postMessageSupported) { var taskIdByMessage = {}; var setImmediateHandler = function (event) { if (event && event.source == global) { var data = event.data; if (hasOwnProperty.call(taskIdByMessage, data)) { var taskId = taskIdByMessage[data]; delete taskIdByMessage[data]; runTask(taskId); } } }; if (global.addEventListener) global.addEventListener("message", setImmediateHandler, true); else global.attachEvent("onmessage", setImmediateHandler); addToQueue = function (taskId) { var message = genUID(32); taskIdByMessage[message] = taskId; global.postMessage(message, "*"); }; } else { if (global.MessageChannel) { var channel = new global.MessageChannel(); channel.port1.onmessage = function (event) { runTask(event.data); }; addToQueue = function (taskId) { channel.port2.postMessage(taskId); }; } else { var createScript = function () { return document.createElement("script"); }; if (document && "onreadystatechange" in createScript()) { var defaultAddToQueue = addToQueue; addToQueue = function beforeHeadReady(taskId) { if (typeof documentInterface != "undefined") { addToQueue = defaultAddToQueue; documentInterface.head.ready(function () { addToQueue = function (taskId) { var scriptEl = createScript(); scriptEl.onreadystatechange = function () { scriptEl.onreadystatechange = null; documentInterface.remove(scriptEl); scriptEl = null; runTask(taskId); }; documentInterface.head.add(scriptEl); }; }); } if (addToQueue === beforeHeadReady) defaultAddToQueue(taskId); else addToQueue(taskId); }; } } } } }()); } var asap = function () { var queue = []; var processing = false; var timer; function processQueue() { try { processing = true; var item; while (item = queue.shift()) item.fn.call(item.context); } finally { processing = false; if (queue.length) timer = setImmediate(process); } } function process() { if (timer) timer = clearImmediate(timer); if (queue.length) processQueue(); } var asap = function (fn, context) { queue.push({ fn: fn, context: context }); if (!timer) timer = setImmediate(process); return true; }; asap.process = function () { if (!processing) process(); }; asap.schedule = function (scheduleFn) { var queue = {}; var scheduled = false; function process() { var etimer = setImmediate(process); scheduled = false; for (var id in queue) { var object = queue[id]; delete queue[id]; scheduleFn(object); } clearImmediate(etimer); if (!scheduled) queue = {}; } return { add: function (object) { queue[object.basisObjectId] = object; if (!scheduled) scheduled = asap(process); }, remove: function (object) { delete queue[object.basisObjectId]; } }; }; return asap; }(); var codeFrame = function () { var count = 0; var info = { id: count, start: function () { info.id = count++; }, finish: function () { asap.process(); info.id = "unknown"; } }; return info; }(); var pathUtils = function () { var ABSOLUTE_RX = /^([^\/]+:|\/)/; var PROTOCOL_RX = /^[a-zA-Z0-9\-]+:\/?/; var ORIGIN_RX = /^(?:[a-zA-Z0-9\-]+:)?\/\/[^\/]+\/?/; var SEARCH_HASH_RX = /[\?#].*$/; var baseURI; var origin; var utils; if (NODE_ENV) { var path = (process.basisjsBaseURI || "/").replace(/\\/g, "/"); baseURI = path.replace(/^[^\/]*/, ""); origin = path.replace(/\/.*/, ""); } else { baseURI = location.pathname.replace(/[^\/]+$/, ""); origin = location.protocol + "//" + location.host; } utils = { baseURI: baseURI, origin: origin, normalize: function (path) { path = (path || "").replace(PROTOCOL_RX, "/").replace(ORIGIN_RX, "/").replace(SEARCH_HASH_RX, ""); var result = []; var parts = path.split("/"); for (var i = 0; i < parts.length; i++) { if (parts[i] == "..") { if (result.length > 1 || result[0]) result.pop(); } else { if ((parts[i] || !i) && parts[i] != ".") result.push(parts[i]); } } return result.join("/") || (path[0] === "/" ? "/" : ""); }, dirname: function (path) { var result = utils.normalize(path); return result.replace(/\/([^\/]*)$|^[^\/]+$/, "") || (result[0] == "/" ? "/" : "."); }, extname: function (path) { var ext = utils.normalize(path).match(/[^\/](\.[^\/\.]*)$/); return ext ? ext[1] : ""; }, basename: function (path, ext) { var filename = utils.normalize(path).match(/[^\\\/]*$/); filename = filename ? filename[0] : ""; if (ext == utils.extname(filename)) filename = filename.substring(0, filename.length - ext.length); return filename; }, resolve: function () { var args = arrayFrom(arguments).reverse(); var path = []; var absoluteFound = false; for (var i = 0; !absoluteFound && i < args.length; i++) if (typeof args[i] == "string") { path.unshift(args[i]); absoluteFound = ABSOLUTE_RX.test(args[i]); } if (!absoluteFound) path.unshift(baseURI == "/" ? "" : baseURI); else if (path.length && path[0] == "/") path[0] = ""; return utils.normalize(path.join("/")); }, relative: function (from, to) { if (typeof to != "string") { to = from; from = baseURI; } from = utils.normalize(from); to = utils.normalize(to); if (from[0] == "/" && to[0] != "/") return from; if (to[0] == "/" && from[0] != "/") return to; var base = from.replace(/^\/$/, "").split(/\//); var path = to.replace(/^\/$/, "").split(/\//); var result = []; var i = 0; while (path[i] == base[i] && typeof base[i] == "string") i++; for (var j = base.length - i; j > 0; j--) result.push(".."); return result.concat(path.slice(i).filter(Boolean)).join("/"); } }; return utils; }(); var basisFilename = __basisFilename || ""; var config = __config || { "noConflict": true, "implicitExt": true, "modules": {}, "autoload": ["./1.js"] }; function fetchConfig() { var config = __config; if (!config) { if (NODE_ENV) { basisFilename = process.basisjsFilename || __filename.replace(/\\/g, "/"); if (process.basisjsConfig) { config = process.basisjsConfig; if (typeof config == "string") { try { config = Function("return{" + config + "}")(); } catch (e) { consoleMethods.error("basis-config: basis.js config parse fault: " + e); } } } } else { var scripts = document.scripts; for (var i = 0, scriptEl; scriptEl = scripts[i]; i++) { var configAttrValue = scriptEl.hasAttribute("basis-config") ? scriptEl.getAttribute("basis-config") : scriptEl.getAttribute("data-basis-config"); scriptEl.removeAttribute("basis-config"); scriptEl.removeAttribute("data-basis-config"); if (configAttrValue !== null) { basisFilename = pathUtils.normalize(scriptEl.src); try { config = Function("return{" + configAttrValue + "}")(); } catch (e) { consoleMethods.error("basis-config: basis.js config parse fault: " + e); } break; } } if (!basisFilename) { basisFilename = pathUtils.normalize(scripts[0].src); consoleMethods.warn("basis-config: no `basis-config` marker on any script tag is found. All paths will be resolved relative to `src` from the first `script` tag."); } } } return processConfig(config); } function processConfig(config) { config = slice(config); complete(config, { implicitExt: NODE_ENV ? true : false }); if ("extProto" in config) consoleMethods.warn("basis-config: `extProto` option in basis-config is not support anymore"); if ("path" in config) consoleMethods.warn("basis-config: `path` option in basis-config is deprecated, use `modules` instead"); var autoload = []; var modules = merge(config.path, config.modules, { basis: basisFilename }); config.modules = {}; if (config.autoload) { var m = String(config.autoload).match(/^((?:[^\/]*\/)*)([a-z$_][a-z0-9$_]*)((?:\.[a-z$_][a-z0-9$_]*)*)$/i); if (m) { modules[m[2]] = { autoload: true, filename: m[1] + m[2] + (m[3] || ".js") }; } else { consoleMethods.warn("basis-config: wrong `autoload` value (setting ignored): " + config.autoload); } delete config.autoload; } for (var name in modules) { var module = modules[name]; if (typeof module == "string") module = { filename: module.replace(/\/$/, "/" + name + ".js") }; var filename = module.filename; var path = module.path; if (filename && !path) { filename = pathUtils.resolve(filename); path = filename.substr(0, filename.length - pathUtils.extname(filename).length); filename = "../" + pathUtils.basename(filename); } path = pathUtils.resolve(path); if (!filename && path) { filename = pathUtils.basename(path); path = pathUtils.dirname(path); } if (!pathUtils.extname(filename)) filename += ".js"; filename = pathUtils.resolve(path, filename); config.modules[name] = { path: path, filename: filename }; if (module.autoload) { config.autoload = autoload; autoload.push(name); } } return config; } var Class = function () { var instanceSeed = { id: 1 }; var classSeed = 1; var classes = []; var SELF = {}; function isClass(object) { return typeof object == "function" && !!object.basisClassId_; } function isSubclassOf(superClass) { var cursor = this; while (cursor && cursor !== superClass) cursor = cursor.superClass_; return cursor === superClass; } var TOSTRING_BUG = function () { for (var key in { toString: 1 }) return false; return true; }(); function createClass(SuperClass) { var classId = classSeed++; if (typeof SuperClass != "function") SuperClass = BaseClass; var className = ""; for (var i = 1, extension; extension = arguments[i]; i++) if (typeof extension != "function" && extension.className) className = extension.className; if (!className) className = SuperClass.className + "._Class" + classId; var NewClassProto = function () { }; NewClassProto = devVerboseName(className, {}, NewClassProto); NewClassProto.prototype = SuperClass.prototype; var newProto = new NewClassProto(); var newClassProps = { className: className, basisClassId_: classId, superClass_: SuperClass, extendConstructor_: !!SuperClass.extendConstructor_, isSubclassOf: isSubclassOf, subclass: function () { return createClass.apply(null, [NewClass].concat(arrayFrom(arguments))); }, extend: extendClass, factory: function (config) { return factory(function (extra) { return new NewClass(merge(config, extra)); }); }, __extend__: function (value) { if (value && value !== SELF && (typeof value == "object" || typeof value == "function" && !isClass(value))) return BaseClass.create.call(null, NewClass, value); else return value; }, prototype: newProto }; for (var i = 1, extension; extension = arguments[i]; i++) newClassProps.extend(extension); if (newProto.init !== BaseClass.prototype.init && !/^function[^(]*\(\)/.test(newProto.init) && newClassProps.extendConstructor_) consoleMethods.warn("probably wrong extendConstructor_ value for " + newClassProps.className); var NewClass = newClassProps.extendConstructor_ ? function (extend) { this.basisObjectId = instanceSeed.id++; var prop; for (var key in extend) { prop = this[key]; this[key] = prop && prop.__extend__ ? prop.__extend__(extend[key]) : extend[key]; } this.init(); this.postInit(); } : function () { this.basisObjectId = instanceSeed.id++; this.init.apply(this, arguments); this.postInit(); }; NewClass = devVerboseName(className, { instanceSeed: instanceSeed }, NewClass); newProto.constructor = NewClass; for (var key in newProto) if (newProto[key] === SELF) newProto[key] = NewClass; extend(NewClass, newClassProps); classes.push(NewClass); return NewClass; } function extendClass(source) { var proto = this.prototype; if (typeof source == "function" && !isClass(source)) source = source(this.superClass_.prototype, slice(proto)); if (source.prototype) source = source.prototype; for (var key in source) { var value = source[key]; var protoValue = proto[key]; if (key == "className" || key == "extendConstructor_") this[key] = value; else { if (protoValue && protoValue.__extend__) proto[key] = protoValue.__extend__(value); else { proto[key] = value; } } } if (TOSTRING_BUG && source[key = "toString"] !== toString) proto[key] = source[key]; return this; } var BaseClass = extend(createClass, { className: "basis.Class", extendConstructor_: false, prototype: { basisObjectId: 0, constructor: null, init: function () { }, postInit: function () { }, toString: function () { return "[object " + (this.constructor || this).className + "]"; }, destroy: function () { for (var prop in this) if (hasOwnProperty.call(this, prop)) this[prop] = null; this.destroy = $undef; } } }); var customExtendProperty = function (extension, fn) { return { __extend__: function (extension) { if (!extension) return extension; if (extension && extension.__extend__) return extension; var Base = function () { }; Base = devVerboseName(arguments[2] || "customExtendProperty", {}, Base); Base.prototype = this; var result = new Base(); fn(result, extension); return result; } }.__extend__(extension || {}); }; var extensibleProperty = function (extension) { return customExtendProperty(extension, extend, "extensibleProperty"); }; var nestedExtendProperty = function (extension) { return customExtendProperty(extension, function (result, extension) { for (var key in extension) if (hasOwnProperty.call(extension, key)) { var value = result[key]; var newValue = extension[key]; if (newValue) result[key] = value && value.__extend__ ? value.__extend__(newValue) : extensibleProperty(newValue); else result[key] = null; } }, "nestedExtendProperty"); }; var oneFunctionProperty = function (fn, keys) { var create = function (keys) { var result = { __extend__: create }; if (keys) { if (keys.__extend__) return keys; var Cls = devVerboseName("oneFunctionProperty", {}, function () { }); result = new Cls(); result.__extend__ = create; for (var key in keys) if (hasOwnProperty.call(keys, key) && keys[key]) result[key] = fn; } return result; }; return create(keys || {}); }; return extend(BaseClass, { all_: classes, SELF: SELF, create: createClass, isClass: isClass, customExtendProperty: customExtendProperty, extensibleProperty: extensibleProperty, nestedExtendProperty: nestedExtendProperty, oneFunctionProperty: oneFunctionProperty }); }(); var Token = Class(null, { className: "basis.Token", value: null, handler: null, deferredToken: null, bindingBridge: { attach: function (host, fn, context, onDestroy) { host.attach(fn, context, onDestroy); }, detach: function (host, fn, context) { host.detach(fn, context); }, get: function (host) { return host.get(); } }, init: function (value) { this.value = value; }, get: function () { return this.value; }, set: function (value) { if (this.value !== value) { this.value = value; this.apply(); } }, attach: function (fn, context, onDestroy) { var cursor = this; while (cursor = cursor.handler) if (cursor.fn === fn && cursor.context === context) consoleMethods.warn("basis.Token#attach: duplicate fn & context pair"); this.handler = { fn: fn, context: context, destroy: onDestroy || null, handler: this.handler }; }, detach: function (fn, context) { var cursor = this; var prev; while (prev = cursor, cursor = cursor.handler) if (cursor.fn === fn && cursor.context === context) { cursor.fn = $undef; cursor.destroy = cursor.destroy && $undef; prev.handler = cursor.handler; return; } consoleMethods.warn("basis.Token#detach: fn & context pair not found, nothing was removed"); }, apply: function () { var value = this.get(); var cursor = this; while (cursor = cursor.handler) cursor.fn.call(cursor.context, value); }, deferred: function () { var token = this.deferredToken; if (!token) { token = this.deferredToken = new DeferredToken(this.get()); this.attach(token.set, token); } return token; }, as: function (fn) { var token = new Token(); var setter = function (value) { this.set(fn.call(this, value)); }; if (typeof fn != "function") fn = getter(fn); setter.call(token, this.get()); this.attach(setter, token, token.destroy); token.attach($undef, this, function () { this.detach(setter, token); }); devInfoResolver.setInfo(token, "sourceInfo", { type: "Token#as", source: this, transform: fn }); return token; }, destroy: function () { if (this.deferredToken) { this.deferredToken.destroy(); this.deferredToken = null; } this.attach = $undef; this.detach = $undef; var cursor = this; while (cursor = cursor.handler) if (cursor.destroy) cursor.destroy.call(cursor.context); this.handler = null; this.value = null; } }); var deferredTokenApplyQueue = asap.schedule(function (token) { token.apply(); }); var DeferredToken = Token.subclass({ className: "basis.DeferredToken", set: function (value) { if (this.value !== value) { this.value = value; deferredTokenApplyQueue.add(this); } }, deferred: function () { return this; } }); var resources = {}; var resourceRequestCache = {}; var resourceContentCache = {}; var resourcePatch = {}; var virtualResourceSeed = 1; var resourceSubscribers = []; var resourceResolvingStack = []; var requires; (function () { var map = typeof __resources__ != "undefined" ? __resources__ : null; if (map) { for (var key in map) resourceContentCache[pathUtils.resolve(key)] = map[key]; } }()); function applyResourcePatches(resource) { var patches = resourcePatch[resource.url]; if (patches) for (var i = 0; i < patches.length; i++) { consoleMethods.info("Apply patch for " + resource.url); patches[i](resource.get(), resource.url); } } var resolveResourceFilename = function (url, baseURI) { var rootNS = url.match(/^([a-zA-Z0-9\_\-]+):/); if (rootNS) { var namespaceRoot = rootNS[1]; if (namespaceRoot in nsRootPath == false) nsRootPath[namespaceRoot] = pathUtils.baseURI + namespaceRoot + "/"; url = nsRootPath[namespaceRoot] + pathUtils.normalize("./" + url.substr(rootNS[0].length)); } else { if (!/^(\.\/|\.\.|\/)/.test(url)) { var clr = arguments[2]; consoleMethods.warn("Bad usage: " + (clr ? clr.replace("{url}", url) : url) + "\nFilenames should starts with `./`, `..` or `/`. Otherwise it may treats as special reference in next releases."); } url = pathUtils.resolve(baseURI, url); } return url; }; var getResourceContent = function (url, ignoreCache) { if (ignoreCache || !hasOwnProperty.call(resourceContentCache, url)) { var resourceContent = ""; if (!NODE_ENV) { var req = new global.XMLHttpRequest(); req.open("GET", url, false); req.setRequestHeader("If-Modified-Since", new Date(0).toGMTString()); req.setRequestHeader("X-Basis-Resource", 1); req.send(""); if (req.status >= 200 && req.status < 400) resourceContent = req.responseText; else { consoleMethods.error("basis.resource: Unable to load " + url + " (status code " + req.status + ")"); } } else { try { if (typeof process.basisjsReadFile == "function") resourceContent = process.basisjsReadFile(url); else { if (true) resourceContent = require("fs").readFileSync(url, "utf-8"); else throw new Error("fs not supported for packed basis.js"); } } catch (e) { consoleMethods.error("basis.resource: Unable to load " + url, e); } } resourceContentCache[url] = resourceContent; } return resourceContentCache[url]; }; var createResource = function (resourceUrl, content) { var contentType = pathUtils.extname(resourceUrl); var contentWrapper = getResource.extensions[contentType]; var isVirtual = arguments.length > 1; var resolved = false; var wrapped = false; var wrappedContent; if (isVirtual) resourceUrl += "#virtual"; var resource = function () { if (resolved) return content; var urlContent = isVirtual ? content : getResourceContent(resourceUrl); var idx = resourceResolvingStack.indexOf(resourceUrl); if (idx != -1) consoleMethods.warn("basis.resource recursion: " + resourceResolvingStack.slice(idx).concat(resourceUrl).map(pathUtils.relative, pathUtils).join(" -> ")); resourceResolvingStack.push(resourceUrl); if (contentWrapper) { if (!wrapped) { wrapped = true; content = contentWrapper(urlContent, resourceUrl); wrappedContent = urlContent; } } else { content = urlContent; } resolved = true; applyResourcePatches(resource); resource.apply(); if (!isVirtual) resourceSubscribers.forEach(function (fn) { fn({ type: "resolve", resource: resource }); }); resourceResolvingStack.pop(); return content; }; extend(resource, extend(new Token(), { url: resourceUrl, type: contentType, virtual: isVirtual, fetch: function () { return resource(); }, toString: function () { return "[basis.resource " + resourceUrl + "]"; }, isResolved: function () { return resolved; }, hasChanges: function () { return contentWrapper ? resourceContentCache[resourceUrl] !== wrappedContent : false; }, update: function (newContent) { if (!resolved || isVirtual || newContent != resourceContentCache[resourceUrl]) { if (!isVirtual) resourceContentCache[resourceUrl] = newContent; if (contentWrapper) { if (!wrapped && isVirtual) content = newContent; if (wrapped && !contentWrapper.permanent) { content = contentWrapper(newContent, resourceUrl, content); applyResourcePatches(resource); resource.apply(); } } else { content = newContent; resolved = true; applyResourcePatches(resource); resource.apply(); } } }, reload: function () { if (isVirtual) return; var oldContent = resourceContentCache[resourceUrl]; var newContent = getResourceContent(resourceUrl, true); if (newContent != oldContent) { resolved = false; resource.update(newContent); } }, get: function (source) { if (isVirtual) if (source) return contentWrapper ? wrappedContent : content; return source ? getResourceContent(resourceUrl) : resource(); }, ready: function (fn, context) { if (resolved) { fn.call(context, resource()); if (contentWrapper && contentWrapper.permanent) return; } resource.attach(fn, context); return resource; } })); resources[resourceUrl] = resource; resourceRequestCache[resourceUrl] = resource; if (!isVirtual) resourceSubscribers.forEach(function (fn) { fn({ type: "create", resource: resource }); }); return resource; }; var getResource = function (url, baseURI) { if (url && typeof url != "string") url = url.url; var reference = baseURI ? baseURI + "\0" + url : url; var resource = resourceRequestCache[reference]; if (!resource) { var resolvedUrl = resolveResourceFilename(url, baseURI, "basis.resource('{url}')"); resource = resources[resolvedUrl] || createResource(resolvedUrl); resourceRequestCache[reference] = resource; } return resource; }; extend(getResource, { resolveURI: resolveResourceFilename, buildCloak: getResource, isResource: function (value) { return value ? resources[value.url] === value : false; }, isResolved: function (resourceUrl) { var resource = getResource.get(resourceUrl); return resource ? resource.isResolved() : false; }, exists: function (resourceUrl) { return hasOwnProperty.call(resources, resolveResourceFilename(resourceUrl, null, "basis.resource.exists('{url}')")); }, get: function (resourceUrl) { resourceUrl = resolveResourceFilename(resourceUrl, null, "basis.resource.get('{url}')"); if (!getResource.exists(resourceUrl)) return null; return getResource(resourceUrl); }, getFiles: function (cache) { return cache ? keys(resourceContentCache) : keys(resources).filter(function (filename) { return !resources[filename].virtual; }); }, subscribe: function (fn) { resourceSubscribers.push(fn); }, virtual: function (type, content, ownerUrl) { return createResource((ownerUrl ? ownerUrl + ":" : pathUtils.normalize(pathUtils.baseURI == "/" ? "" : pathUtils.baseURI) + "/") + "virtual-resource" + virtualResourceSeed++ + "." + type, content); }, extensions: { ".js": extend(function processJsResourceContent(content, filename) { var namespace = filename2namespace[filename]; if (!namespace) { var implicitNamespace = true; var resolvedFilename = (pathUtils.dirname(filename) + "/" + pathUtils.basename(filename, pathUtils.extname(filename))).replace(/^\/\//, "/"); for (var ns in nsRootPath) { var path = nsRootPath[ns] + ns + "/"; if (resolvedFilename.substr(0, path.length) == path) { implicitNamespace = false; resolvedFilename = resolvedFilename.substr(nsRootPath[ns].length); break; } } namespace = resolvedFilename.replace(/\./g, "_").replace(/^\//g, "").replace(/\//g, "."); if (implicitNamespace) namespace = "implicit." + namespace; } if (requires) arrayFunctions.add(requires, namespace); var ns = getNamespace(namespace); if (!ns.inited) { var savedRequires = requires; requires = []; ns.inited = true; ns.exports = runScriptInContext({ path: ns.path, exports: ns.exports }, filename, content).exports; if (ns.exports && ns.exports.constructor === Object) { if (config.implicitExt) { if (config.implicitExt == "warn") { for (var key in ns.exports) if (key in ns == false && key != "path") { ns[key] = ns.exports[key]; warnPropertyAccess(ns, key, ns.exports[key], "basis.js: Access to implicit namespace property `" + namespace + "." + key + "`"); } } else complete(ns, ns.exports); } } ns.filename_ = filename; ns.source_ = content; ns.requires_ = requires; requires = savedRequires; } return ns.exports; }, { permanent: true }), ".css": function processCssResourceContent(content, url, cssResource) { if (!cssResource) cssResource = new CssResource(url); cssResource.updateCssText(content); return cssResource; }, ".svg": function processCssResourceContent(content, url, svgResource) { if (!svgResource) svgResource = new SvgResource(url); svgResource.updateSvgText(content); return svgResource; }, ".json": function processJsonResourceContent(content) { if (typeof content == "object") return content; var result; try { content = String(content); result = basis.json.parse(content); } catch (e) { var url = arguments[1]; consoleMethods.warn("basis.resource: Can't parse JSON from " + url, { url: url, content: content }); } return result || null; } } }); var SOURCE_OFFSET; function compileFunction(sourceURL, args, body) { if (isNaN(SOURCE_OFFSET)) { var marker = basis.genUID(); SOURCE_OFFSET = new Function(args, marker).toString().split(marker)[0].split(/\n/).length - 1; } body = devInfoResolver.fixSourceOffset(body, SOURCE_OFFSET + 1) + "\n//# sourceURL=" + pathUtils.origin + sourceURL; try { return new Function(args, "\"use strict\";\n" + (NODE_ENV ? "var __nodejsRequire = require;\n" : "") + body); } catch (e) { if (document && "line" in e == false && "addEventListener" in global) { global.addEventListener("error", function onerror(event) { if (event.filename == pathUtils.origin + sourceURL) { global.removeEventListener("error", onerror); consoleMethods.error("Compilation error at " + event.filename + ":" + event.lineno + ": " + e); event.preventDefault(); } }); var script = document.createElement("script"); script.src = sourceURL; script.async = false; document.head.appendChild(script); document.head.removeChild(script); } consoleMethods.error("Compilation error at " + sourceURL + ("line" in e ? ":" + (e.line - 1) : "") + ": " + e); } } var runScriptInContext = function (context, sourceURL, sourceCode) { var baseURL = pathUtils.dirname(sourceURL); var compiledSourceCode = sourceCode; if (!context.exports) context.exports = {}; if (typeof compiledSourceCode != "function") compiledSourceCode = compileFunction(sourceURL, [ "exports", "module", "basis", "global", "__filename", "__dirname", "resource", "require", "asset" ], sourceCode); if (typeof compiledSourceCode == "function") { compiledSourceCode.displayName = "[module] " + (filename2namespace[sourceURL] || sourceURL); compiledSourceCode.call(context.exports, context.exports, context, basis, global, sourceURL, baseURL, function (path) { return getResource(path, baseURL); }, function (path) { return requireNamespace(path, baseURL); }, function (path, inline) { return inline === true ? getResourceContent(resolveResourceFilename(path, baseURL, "asset('{url}',true)")) : resolveResourceFilename(path, baseURL, "asset('{url}')"); }); } return context; }; var namespaces = {}; var namespace2filename = {}; var filename2namespace = {}; var nsRootPath = {}; iterate(config.modules, function (name, module) { nsRootPath[name] = module.path + "/"; namespace2filename[name] = module.filename; filename2namespace[module.filename] = name; }); (function (map) { var map = typeof __namespace_map__ != "undefined" ? __namespace_map__ : null; if (map) { for (var key in map) { var filename = pathUtils.resolve(key); var namespace = map[key]; filename2namespace[filename] = namespace; namespace2filename[namespace] = filename; } } }()); var Namespace = Class(null, { className: "basis.Namespace", init: function (name) { this.name = name; this.exports = {}; }, toString: function () { return "[basis.namespace " + this.name + "]"; }, extend: function (names) { extend(this.exports, names); return complete(this, names); } }); function resolveNSFilename(namespace) { if (namespace in namespace2filename == false) { var parts = namespace.split("."); var namespaceRoot = parts.shift(); var filename = resolveResourceFilename(namespaceRoot + ":" + parts.join("/") + ".js").replace(/\/\.js$/, ".js"); namespace2filename[namespace] = filename; filename2namespace[filename] = namespace; } return namespace2filename[namespace]; } function getRootNamespace(name) { var namespace = namespaces[name]; if (!namespace) { namespace = namespaces[name] = new Namespace(name); namespace.namespaces_ = {}; namespace.namespaces_[name] = namespace; if (!config.noConflict) global[name] = namespace; } if (name == "library" && !library) library = namespaces[name]; return namespace; } function getNamespace(path) { if (hasOwnProperty.call(namespaces, path)) return namespaces[path]; path = path.split("."); var rootNs = getRootNamespace(path[0]); var cursor = rootNs; for (var i = 1; i < path.length; i++) { var name = path[i]; var nspath = path.slice(0, i + 1).join("."); if (!hasOwnProperty.call(rootNs.namespaces_, nspath)) { var namespace = new Namespace(nspath); if (config.implicitExt) { cursor[name] = namespace; if (config.implicitExt == "warn") { cursor[name] = namespace; warnPropertyAccess(cursor, name, namespace, "basis.js: Access to implicit namespace `" + nspath + "`"); } } rootNs.namespaces_[nspath] = namespace; } cursor = rootNs.namespaces_[nspath]; } namespaces[path.join(".")] = cursor; return cursor; } var requireNamespace = function (path, baseURI) { var extname = pathUtils.extname(path); if (!/[^a-z0-9_\.]/i.test(path) && extname != ".js") { path = resolveNSFilename(path); } else { if (!/[\?#]/.test(path)) { if (!extname) path += ".js"; path = resolveResourceFilename(path, baseURI, "basis.require('{url}')"); } } return getResource(path).fetch(); }; requireNamespace.displayName = "basis.require"; function patch(filename, patchFn) { if (!/[^a-z0-9_\.]/i.test(filename) && pathUtils.extname(filename) != ".js") { filename = resolveNSFilename(filename); } else { filename = resolveResourceFilename(filename, null, "basis.patch('{url}')"); } if (!resourcePatch[filename]) resourcePatch[filename] = [patchFn]; else resourcePatch[filename].push(patchFn); var resource = getResource.get(filename); if (resource && resource.isResolved()) { consoleMethods.info("Apply patch for " + resource.url); patchFn(resource.get(), resource.url); } } complete(Function.prototype, { bind: function (thisObject) { var fn = this; var params = arrayFrom(arguments, 1); return params.length ? function () { return fn.apply(thisObject, params.concat.apply(params, arguments)); } : function () { return fn.apply(thisObject, arguments); }; } }); complete(Array, { isArray: function (value) { return toString.call(value) === "[object Array]"; } }); function arrayFrom(object, offset) { if (object != null) { var len = object.length; if (typeof len == "undefined" || toString.call(object) == "[object Function]") return [object]; if (!offset) offset = 0; if (len - offset > 0) { for (var result = [], k = 0, i = offset; i < len;) result[k++] = object[i++]; return result; } } return []; } function createArray(length, fillValue, thisObject) { var result = []; var isFunc = typeof fillValue == "function"; for (var i = 0; i < length; i++) result[i] = isFunc ? fillValue.call(thisObject, i, result) : fillValue; return result; } complete(Array.prototype, { indexOf: function (searchElement, offset) { offset = parseInt(offset, 10) || 0; if (offset < 0) return -1; for (; offset < this.length; offset++) if (this[offset] === searchElement) return offset; return -1; }, lastIndexOf: function (searchElement, offset) { var len = this.length; offset = parseInt(offset, 10); if (isNaN(offset) || offset >= len) offset = len - 1; else offset = (offset + len) % len; for (; offset >= 0; offset--) if (this[offset] === searchElement) return offset; return -1; }, forEach: function (callback, thisObject) { for (var i = 0, len = this.length; i < len; i++) if (i in this) callback.call(thisObject, this[i], i, this); }, every: function (callback, thisObject) { for (var i = 0, len = this.length; i < len; i++) if (i in this && !callback.call(thisObject, this[i], i, this)) return false; return true; }, some: function (callback, thisObject) { for (var i = 0, len = this.length; i < len; i++) if (i in this && callback.call(thisObject, this[i], i, this)) return true; return false; }, filter: function (callback, thisObject) { var result = []; for (var i = 0, len = this.length; i < len; i++) if (i in this && callback.call(thisObject, this[i], i, this)) result.push(this[i]); return result; }, map: function (callback, thisObject) { var result = []; for (var i = 0, len = this.length; i < len; i++) if (i in this) result[i] = callback.call(thisObject, this[i], i, this); return result; }, reduce: function (callback, initialValue) { var len = this.length; var argsLen = arguments.length; if (len == 0 && argsLen == 1) throw new TypeError(); var result; var inited = 0; if (argsLen > 1) { result = initialValue; inited = 1; } for (var i = 0; i < len; i++) if (i in this) if (inited++) result = callback.call(null, result, this[i], i, this); else result = this[i]; return result; } }); var arrayFunctions = { from: arrayFrom, create: createArray, flatten: function (this_) { return this_.concat.apply([], this_); }, repeat: function (this_, count) { return arrayFunctions.flatten(createArray(parseInt(count, 10) || 0, this_)); }, search: function (this_, value, getter_, offset) { this_.lastSearchIndex = -1; getter_ = getter(getter_ || $self); for (var index = parseInt(offset, 10) || 0, len = this_.length; index < len; index++) if (getter_(this_[index]) === value) return this_[this_.lastSearchIndex = index]; }, lastSearch: function (this_, value, getter_, offset) { this_.lastSearchIndex = -1; getter_ = getter(getter_ || $self); var len = this_.length; var index = isNaN(offset) || offset == null ? len : parseInt(offset, 10); for (var i = index > len ? len : index; i-- > 0;) if (getter_(this_[i]) === value) return this_[this_.lastSearchIndex = i]; }, add: function (this_, value) { return this_.indexOf(value) == -1 && !!this_.push(value); }, remove: function (this_, value) { var index = this_.indexOf(value); return index != -1 && !!this_.splice(index, 1); }, has: function (this_, value) { return this_.indexOf(value) != -1; }, sortAsObject: function () { consoleMethods.warn("basis.array.sortAsObject is deprecated, use basis.array.sort instead"); return arrayFunctions.sort.apply(this, arguments); }, sort: function (this_, getter_, comparator, desc) { getter_ = getter(getter_); desc = desc ? -1 : 1; return this_.map(function (item, index) { return { i: index, v: getter_(item) }; }).sort(comparator || function (a, b) { return desc * (a.v > b.v || -(a.v < b.v) || (a.i > b.i ? 1 : -1)); }).map(function (item) { return this[item.i]; }, this_); } }; if (![ 1, 2 ].splice(1).length) { var nativeArraySplice = Array.prototype.splice; Array.prototype.splice = function () { var params = arrayFrom(arguments); if (params.length < 2) params[1] = this.length; return nativeArraySplice.apply(this, params); }; } var ESCAPE_FOR_REGEXP = /([\/\\\(\)\[\]\?\{\}\|\*\+\-\.\^\$])/g; var FORMAT_REGEXP = /\{([a-z\d_]+)(?::([\.0])(\d+)|:(\?))?\}/gi; var stringFormatCache = {}; complete(String, { toLowerCase: function (value) { return String(value).toLowerCase(); }, toUpperCase: function (value) { return String(value).toUpperCase(); }, trim: function (value) { return String(value).trim(); }, trimLeft: function (value) { return String(value).trimLeft(); }, trimRight: function (value) { return String(value).trimRight(); } }); complete(String.prototype, { trimLeft: function () { return this.replace(/^\s+/, ""); }, trimRight: function () { return this.replace(/\s+$/, ""); }, trim: function () { return this.trimLeft().trimRight(); } }); var stringFunctions = { toObject: function (this_, rethrow) { try { return new Function("return 0," + this_)(); } catch (e) { if (rethrow) throw e; } }, repeat: function (this_, count) { return new Array(parseInt(count, 10) + 1 || 0).join(this_); }, qw: function (this_) { var trimmed = this_.trim(); return trimmed ? trimmed.split(/\s+/) : []; }, forRegExp: function (this_) { return this_.replace(ESCAPE_FOR_REGEXP, "\\$1"); }, format: function (this_, first) { var data = arrayFrom(arguments, 1); if (typeof first == "object") extend(data, first); return this_.replace(FORMAT_REGEXP, function (m, key, numFormat, num, noNull) { var value = key in data ? data[key] : noNull ? "" : m; if (numFormat && !isNaN(value)) { value = Number(value); return numFormat == "." ? value.toFixed(num) : numberFunctions.lead(value, num); } return value; }); }, formatter: function (formatString) { formatString = String(formatString); if (hasOwnProperty.call(stringFormatCache, formatString)) return stringFormatCache[formatString]; var formatter = function (value) { return stringFunctions.format(formatString, value); }; var escapsedFormatString = "\"" + formatString.replace(/"/g, "\\\"") + "\""; formatter = new Function("stringFunctions", "return " + formatter.toString().replace("formatString", escapsedFormatString))(stringFunctions); formatter.toString = function () { return "basis.string.formatter(" + escapsedFormatString + ")"; }; stringFormatCache[formatString] = formatter; return formatter; }, capitalize: function (this_) { return this_.charAt(0).toUpperCase() + this_.substr(1).toLowerCase(); }, camelize: function (this_) { return this_.replace(/-(.)/g, function (m, chr) { return chr.toUpperCase(); }); }, dasherize: function (this_) { return this_.replace(/[A-Z]/g, function (m) { return "-" + m.toLowerCase(); }); }, isEmpty: function (value) { return value == null || String(value) == ""; }, isNotEmpty: function (value) { return value != null && String(value) != ""; } }; if ("|||".split(/\|/).length + "|||".split(/(\|)/).length != 11) { var nativeStringSplit = String.prototype.split; String.prototype.split = function (pattern, count) { if (!pattern || pattern instanceof RegExp == false || pattern.source == "") return nativeStringSplit.call(this, pattern, count); var result = []; var pos = 0; var match; if (!pattern.global) pattern = new RegExp(pattern.source, /\/([mi]*)$/.exec(pattern)[1] + "g"); while (match = pattern.exec(this)) { match[0] = this.substring(pos, match.index); result.push.apply(result, match); pos = pattern.lastIndex; } result.push(this.substr(pos)); return result; }; } if ("12".substr(-1) != "2") { var nativeStringSubstr = String.prototype.substr; String.prototype.substr = function (start, end) { return nativeStringSubstr.call(this, start < 0 ? Math.max(0, this.length + start) : start, end); }; } var numberFunctions = { fit: function (this_, min, max) { if (!isNaN(min) && this_ < min) return Number(min); if (!isNaN(max) && this_ > max) return Number(max); return this_; }, lead: function (this_, len, leadChar) { return String(this_).replace(/\d+/, function (number) { return (len -= number.length - 1) > 1 ? new Array(len).join(leadChar || 0) + number : number; }); }, group: function (this_, len, splitter) { return String(this_).replace(/\d+/, function (number) { return number.replace(/\d/g, function (m, pos) { return !pos + (number.length - pos) % (len || 3) ? m : (splitter || " ") + m; }); }); }, format: function (this_, prec, gs, prefix, postfix, comma) { var res = this_.toFixed(prec); if (gs || comma) res = res.replace(/(\d+)(\.?)/, function (m, number, c) { return (gs ? basis.number.group(Number(number), 3, gs) : number) + (c ? comma || c : ""); }); if (prefix) res = res.replace(/^-?/, "$&" + (prefix || "")); return res + (postfix || ""); } }; complete(Date, { now: function () { return Number(new Date()); } }); var ready = function () { var eventFired = !document || document.readyState == "complete"; var readyHandlers = []; var timer; function processReadyHandler() { var handler; if (timer) timer = clearImmediate(timer); if (readyHandlers.length > 1) timer = setImmediate(processReadyHandler); while (handler = readyHandlers.shift()) handler[0].call(handler[1]); timer = clearImmediate(timer); asap.process(); } function fireHandlers() { if (!eventFired++) processReadyHandler(); } function doScrollCheck() { try { document.documentElement.doScroll("left"); fireHandlers(); } catch (e) { setTimeout(doScrollCheck, 1); } } if (!eventFired) { if (document.addEventListener) { document.addEventListener("DOMContentLoaded", fireHandlers, false); global.addEventListener("load", fireHandlers, false); } else { document.attachEvent("onreadystatechange", fireHandlers); global.attachEvent("onload", fireHandlers); try { if (!global.frameElement && document.documentElement.doScroll) doScrollCheck(); } catch (e) { } } } return function (callback, context) { if (!readyHandlers.length && eventFired && !timer) timer = setImmediate(processReadyHandler); readyHandlers.push([ callback, context ]); }; }(); var teardown = function () { if ("addEventListener" in global) return function (callback, context) { global.addEventListener("unload", function (event) { callback.call(context || null, event || global.event); }, false); }; if ("attachEvent" in global) return function (callback, context) { global.attachEvent("onunload", function (event) { callback.call(context || null, event || global.event); }); }; return $undef; }(); var documentInterface = function () { var timer; var reference = {}; var callbacks = { head: [], body: [] }; function getParent(name) { if (document && !reference[name]) { reference[name] = document[name] || document.getElementsByTagName(name)[0]; if (reference[name]) { var items = callbacks[name]; delete callbacks[name]; for (var i = 0, cb; cb = items[i]; i++) cb[0].call(cb[1], reference[name]); } } return reference[name]; } function add() { var name = this[0]; var node = this[1]; var ref = this[2]; remove(node); var parent = getParent(name); if (parent) { if (ref === true) ref = parent.firstChild; if (!ref || ref.parentNode !== parent) ref = null; parent.insertBefore(node, ref); } else callbacks[name].push([ add, [ name, node, ref ] ]); } function docReady(name, fn, context) { if (callbacks[name]) callbacks[name].push([ fn, context ]); else fn.call(context, reference[name]); } function remove(node) { for (var key in callbacks) { var entry = arrayFunctions.search(callbacks[key], node, function (item) { return item[1] && item[1][1]; }); if (entry) arrayFunctions.remove(callbacks[key], entry); } if (node && node.parentNode && node.parentNode.nodeType == 1) node.parentNode.removeChild(node); } function checkParents() { if (timer && getParent("head") && getParent("body")) timer = clearInterval(timer); } if (document && (!getParent("head") || !getParent("body"))) { timer = setInterval(checkParents, 5); ready(checkParents); } return { head: { ready: function (fn, context) { docReady("head", fn, context); }, add: function (node, ref) { add.call([ "head", node, ref ]); } }, body: { ready: function (fn, context) { docReady("body", fn, context); }, add: function (node, ref) { add.call([ "body", node, ref ]); } }, remove: remove }; }(); var cleaner = function () { var objects = []; function destroy() { var logDestroy = arguments[0] === true; result.globalDestroy = true; result.add = $undef; result.remove = $undef; var object; while (object = objects.pop()) { if (typeof object.destroy == "function") { try { if (logDestroy) consoleMethods.log("destroy", "[" + String(object.className) + "]", object); object.destroy(); } catch (e) { consoleMethods.warn(String(object), e); } } else { for (var prop in object) object[prop] = null; } } objects = []; } if (teardown === $undef) return { add: $undef, remove: $undef }; teardown(destroy); var result = { add: function (object) { if (object != null) objects.push(object); }, remove: function (object) { arrayFunctions.remove(objects, object); } }; result.destroy_ = destroy; result.objects_ = objects; return result; }(); var CssResource = function () { var STYLE_APPEND_BUGGY = function () { try { return !document.createElement("style").appendChild(document.createTextNode("")); } catch (e) { return true; } }(); var baseEl = document && document.createElement("base"); function setBase(baseURI) { baseEl.setAttribute("href", baseURI); documentInterface.head.add(baseEl, true); } function restoreBase() { baseEl.setAttribute("href", location.href); documentInterface.remove(baseEl); } function injectStyleToHead() { setBase(this.baseURI); if (!this.element) { this.element = document.createElement("style"); if (!STYLE_APPEND_BUGGY) this.element.appendChild(document.createTextNode("")); this.element.setAttribute("src", this.url); } documentInterface.head.add(this.element); this.syncCssText(); restoreBase(); } return Class(null, { className: "basis.CssResource", inUse: 0, url: "", baseURI: "", cssText: undefined, element: null, init: function (url) { this.url = url; this.baseURI = pathUtils.dirname(url) + "/"; }, updateCssText: function (cssText) { if (this.cssText != cssText) { this.cssText = cssText; if (this.inUse && this.element) { setBase(this.baseURI); this.syncCssText(); restoreBase(); } } }, syncCssText: STYLE_APPEND_BUGGY ? function () { this.element.styleSheet.cssText = this.cssText; } : function () { var cssText = this.cssText; cssText += "\n/*# sourceURL=" + pathUtils.origin + this.url + " */"; this.element.firstChild.nodeValue = cssText; }, startUse: function () { if (!this.inUse) documentInterface.head.ready(injectStyleToHead, this); this.inUse += 1; }, stopUse: function () { if (this.inUse) { this.inUse -= 1; if (!this.inUse && this.element) documentInterface.remove(this.element); } }, destroy: function () { if (this.element) documentInterface.remove(this.element); this.element = null; this.cssText = null; } }); }(); var svgStorageElement = null; var SvgResource = function () { var baseEl = document && document.createElement("base"); function setBase(baseURI) { baseEl.setAttribute("href", baseURI); documentInterface.head.add(baseEl, true); } function restoreBase() { baseEl.setAttribute("href", location.href); documentInterface.remove(baseEl); } function injectSvg() { setBase(this.baseURI); if (!this.element) { this.element = document.createElement("span"); this.element.setAttribute("src", this.url); } svgStorageElement.appendChild(this.element); this.syncSvgText(); restoreBase(); } return Class(null, { className: "basis.SvgResource", inUse: 0, url: "", baseURI: "", svgText: undefined, element: null, init: function (url) { this.url = url; this.baseURI = pathUtils.dirname(url) + "/"; }, toString: function () { return this.svgText; }, updateSvgText: function (svgText) { if (this.svgText != svgText) { this.svgText = svgText; if (this.inUse && this.element) { setBase(this.baseURI); this.syncSvgText(); restoreBase(); } } }, syncSvgText: function () { this.element.innerHTML = this.svgText; }, startUse: function () { if (!this.inUse) { if (!svgStorageElement) { svgStorageElement = document.createElement("span"); svgStorageElement.setAttribute("title", "svg symbol storage"); svgStorageElement.style.cssText = "position:absolute!important;width:0;height:0;overflow:hidden"; documentInterface.body.add(svgStorageElement); } documentInterface.body.ready(injectSvg, this); } this.inUse += 1; }, stopUse: function () { if (this.inUse) { this.inUse -= 1; if (!this.inUse && this.element) svgStorageElement.removeChild(this.element); } }, destroy: function () { if (this.element) svgStorageElement.removeChild(this.element); this.element = null; this.svgText = null; } }); }(); var devInfoResolver = function () { var getExternalInfo = $undef; var fixSourceOffset = $self; var set = function () { }; var patch = function (target, key, patch) { var oldInfo = get(target, key); if (oldInfo) extend(oldInfo, patch); else set(target, key, patch); }; var get = function (target, key) { var externalInfo = getExternalInfo(target); var ownInfo = map.get(target); if (externalInfo || ownInfo) { var info = merge(externalInfo, ownInfo); return key ? info[key] : info; } }; var patchFactory = function (factory) { return function locationAnchor(target) { var value = factory(target); if (value) set(value, "loc", get(locationAnchor, "loc")); return value; }; }; try { new WeakMap().get(1); } catch (e) { get = function () { }; } var map = typeof WeakMap == "function" ? new WeakMap() : false; if (map) set = function (target, key, value) { if (!target || typeof target != "object" && typeof target != "function") { consoleMethods.warn("Set dev info for non-object or non-function was ignored"); return; } var info = map.get(target); if (!info) map.set(target, info = {}); info[key] = value; }; var resolver = config.devInfoResolver || global.$devinfo || {}; if (typeof resolver.fixSourceOffset == "function") fixSourceOffset = resolver.fixSourceOffset; if (typeof resolver.get == "function") getExternalInfo = resolver.get; return { fixSourceOffset: fixSourceOffset, setInfo: set, patchInfo: patch, patchFactory: patchFactory, getInfo: get }; }(); var attachFileSyncRetry = 50; ready(function attachFileSync() { var basisjsTools = global.basisjsToolsFileSync; if (!basisjsTools) { if (attachFileSyncRetry < 500) setTimeout(attachFileSync, attachFileSyncRetry); attachFileSyncRetry += 100; return; } basisjsTools.notifications.attach(function (action, filename, content) { if (action == "update") { if (filename in resources) resources[filename].update(content); if (filename in resourceContentCache) resourceContentCache[filename] = content; } }); }); var basis = getNamespace("basis").extend({ filename_: basisFilename, processConfig: processConfig, selfFileSync: true, version: VERSION, NODE_ENV: NODE_ENV, config: config, createSandbox: function (config) { return createBasisInstance(global, basisFilename, complete({ noConflict: true, devpanel: false }, config)); }, dev: consoleMethods = new Namespace("basis.dev").extend(consoleMethods).extend(devInfoResolver).extend({ warnPropertyAccess: warnPropertyAccess }), resolveNSFilename: resolveNSFilename, patch: patch, namespace: getNamespace, require: requireNamespace, resource: getResource, asset: function (path, inline) { return inline === true ? getResourceContent(resolveResourceFilename(path, null, "basis.asset('{url}')")) : resolveResourceFilename(path, null, "basis.asset('{url}')"); }, setImmediate: setImmediate, clearImmediate: clearImmediate, nextTick: function () { setImmediate.apply(null, arguments); }, asap: asap, FACTORY: FACTORY, PROXY: PROXY, Class: Class, Token: Token, DeferredToken: DeferredToken, codeFrame: codeFrame, ready: ready, teardown: teardown, cleaner: cleaner, genUID: genUID, getter: getter, console: consoleMethods, path: pathUtils, doc: documentInterface, object: { extend: extend, complete: complete, keys: keys, values: values, slice: slice, splice: splice, merge: merge, iterate: iterate }, fn: { $undefined: $undefined, $defined: $defined, $isNull: $isNull, $isNotNull: $isNotNull, $isSame: $isSame, $isNotSame: $isNotSame, $self: $self, $const: $const, $false: $false, $true: $true, $null: $null, $undef: $undef, getter: getter, nullGetter: nullGetter, wrapper: wrapper, factory: factory, isFactory: isFactory, lazyInit: lazyInit, lazyInitAndRun: lazyInitAndRun, runOnce: runOnce, publicCallback: publicCallback }, array: extend(arrayFrom, arrayFunctions), string: stringFunctions, number: numberFunctions, bool: { invert: function (value) { return !value; } }, json: { parse: typeof JSON != "undefined" ? JSON.parse : function (str) { return stringFunctions.toObject(str, true); } } }); if (!NODE_ENV) { if (config.autoload) config.autoload.forEach(function (name) { requireNamespace(name); }); if ("devpanel" in config == false || config.devpanel) basis.require("./0.js"); } if (NODE_ENV && typeof module != "undefined" && module) { module.exports = basis; module.exports.basis = basis; } return basis; }(this)); }).call(this);
SVG.Defs = SVG.invent({ // Initialize node create: 'defs' // Inherit from , inherit: SVG.Container })
/******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) /******/ return installedModules[moduleId].exports; /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ exports: {}, /******/ id: moduleId, /******/ loaded: false /******/ }; /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ // Flag the module as loaded /******/ module.loaded = true; /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ // Load entry module and return exports /******/ return __webpack_require__(0); /******/ }) /************************************************************************/ /******/ ({ /***/ 0: /***/ function(module, exports, __webpack_require__) { var __weex_template__ = __webpack_require__(242) var __weex_script__ = __webpack_require__(243) __weex_define__('@weex-component/df4a1d587e74e64ad99011cd2bcf06b7', [], function(__weex_require__, __weex_exports__, __weex_module__) { __weex_script__(__weex_module__, __weex_exports__, __weex_require__) if (__weex_exports__.__esModule && __weex_exports__.default) { __weex_module__.exports = __weex_exports__.default } __weex_module__.exports.template = __weex_template__ }) __weex_bootstrap__('@weex-component/df4a1d587e74e64ad99011cd2bcf06b7',undefined,undefined) /***/ }, /***/ 242: /***/ function(module, exports) { module.exports = { "type": "image", "style": { "width": function () {return this.width}, "height": function () {return this.height} }, "attr": { "src": function () {return this.src}, "imageQuality": function () {return this.quality} }, "events": { "click": "_clickHandler" } } /***/ }, /***/ 243: /***/ function(module, exports) { module.exports = function(module, exports, __weex_require__){'use strict'; module.exports = { data: function () {return { quality: 'normal', width: 0, height: 0, src: '', href: '', spmc: 0, spmd: 0 }}, methods: { ready: function ready() {}, _clickHandler: function _clickHandler() { this.$call('modal', 'toast', { message: 'click', duration: 1 }); } } };} /* generated by weex-loader */ /***/ } /******/ });
!function($) { var Selectpicker = function(element, options, e) { if (e ) { e.stopPropagation(); e.preventDefault(); } this.$element = $(element); this.$newElement = null; this.button = null; //Merge defaults, options and data-attributes to make our options this.options = $.extend({}, $.fn.selectpicker.defaults, this.$element.data(), typeof options == 'object' && options); //If we have no title yet, check the attribute 'title' (this is missed by jq as its not a data-attribute if(this.options.title==null) this.options.title = this.$element.attr('title'); //Expose public methods this.val = Selectpicker.prototype.val; this.render = Selectpicker.prototype.render; this.init(); }; Selectpicker.prototype = { constructor: Selectpicker, init: function (e) { var _this = this; this.$element.hide(); this.multiple = this.$element.prop('multiple'); var classList = this.$element.attr('class') !== undefined ? this.$element.attr('class').split(/\s+/) : ''; var id = this.$element.attr('id'); this.$element.after( this.createView() ); this.$newElement = this.$element.next('.select'); var select = this.$newElement; var menu = this.$newElement.find('.dropdown-menu'); var menuArrow = this.$newElement.find('.dropdown-arrow'); var menuA = menu.find('li > a'); var liHeight = select.addClass('open').find('.dropdown-menu li > a').outerHeight(); select.removeClass('open'); var divHeight = menu.find('li .divider').outerHeight(true); var selectOffset_top = this.$newElement.offset().top; var size = 0; var menuHeight = 0; var selectHeight = this.$newElement.outerHeight(); this.button = this.$newElement.find('> button'); if (id !== undefined) { this.button.attr('id', id); $('label[for="' + id + '"]').click(function(){ select.find('button#'+id).focus(); }) } for (var i = 0; i < classList.length; i++) { if(classList[i] != 'selectpicker') { this.$newElement.addClass(classList[i]); } } //If we are multiple, then add the show-tick class by default if(this.multiple) { this.$newElement.addClass('select-multiple'); } this.button.addClass(this.options.style); menu.addClass(this.options.menuStyle); menuArrow.addClass(function() { if (_this.options.menuStyle) { return _this.options.menuStyle.replace('dropdown-', 'dropdown-arrow-'); } }); this.checkDisabled(); this.checkTabIndex(); this.clickListener(); var menuPadding = parseInt(menu.css('padding-top')) + parseInt(menu.css('padding-bottom')) + parseInt(menu.css('border-top-width')) + parseInt(menu.css('border-bottom-width')); if (this.options.size == 'auto') { function getSize() { var selectOffset_top_scroll = selectOffset_top - $(window).scrollTop(); var windowHeight = $(window).innerHeight; var menuExtras = menuPadding + parseInt(menu.css('margin-top')) + parseInt(menu.css('margin-bottom')) + 2; var selectOffset_bot = windowHeight - selectOffset_top_scroll - selectHeight - menuExtras; menuHeight = selectOffset_bot; if (select.hasClass('dropup')) { menuHeight = selectOffset_top_scroll - menuExtras; } menu.css({'max-height' : menuHeight + 'px', 'overflow-y' : 'auto', 'min-height' : liHeight*3 + 'px'}); } getSize(); $(window).resize(getSize); $(window).scroll(getSize); this.$element.bind('DOMNodeInserted', getSize); } else if (this.options.size && this.options.size != 'auto' && menu.find('li').length > this.options.size) { var optIndex = menu.find("li > *").filter(':not(.divider)').slice(0,this.options.size).last().parent().index(); var divLength = menu.find("li").slice(0,optIndex + 1).find('.divider').length; menuHeight = liHeight*this.options.size + divLength*divHeight + menuPadding; menu.css({'max-height' : menuHeight + 'px', 'overflow-y' : 'scroll'}); } //Listen for updates to the DOM and re render... this.$element.bind('DOMNodeInserted', $.proxy(this.reloadLi, this)); this.render(); }, createDropdown: function() { var drop = "<div class='btn-group select'>" + "<button class='btn dropdown-toggle clearfix' data-toggle='dropdown'>" + "<span class='filter-option pull-left'></span>&nbsp;" + "<span class='caret'></span>" + "</button>" + "<span class='dropdown-arrow'></span>" + "<ul class='dropdown-menu' role='menu'>" + "</ul>" + "</div>"; return $(drop); }, createView: function() { var $drop = this.createDropdown(); var $li = this.createLi(); $drop.find('ul').append($li); return $drop; }, reloadLi: function() { //Remove all children. this.destroyLi(); //Re build $li = this.createLi(); this.$newElement.find('ul').append( $li ); //render view this.render(); }, destroyLi:function() { this.$newElement.find('li').remove(); }, createLi: function() { var _this = this; var _li = []; var _liA = []; var _liHtml = ''; this.$element.find('option').each(function(){ _li.push($(this).text()); }); this.$element.find('option').each(function(index) { //Get the class and text for the option var optionClass = $(this).attr("class") !== undefined ? $(this).attr("class") : ''; var text = $(this).text(); var subtext = $(this).data('subtext') !== undefined ? '<small class="muted">'+$(this).data('subtext')+'</small>' : ''; //Append any subtext to the main text. text+=subtext; if ($(this).parent().is('optgroup') && $(this).data('divider') != true) { if ($(this).index() == 0) { //Get the opt group label var label = $(this).parent().attr('label'); var labelSubtext = $(this).parent().data('subtext') !== undefined ? '<small class="muted">'+$(this).parent().data('subtext')+'</small>' : ''; label += labelSubtext; if ($(this)[0].index != 0) { _liA.push( '<div class="divider"></div>'+ '<dt>'+label+'</dt>'+ _this.createA(text, "opt " + optionClass ) ); } else { _liA.push( '<dt>'+label+'</dt>'+ _this.createA(text, "opt " + optionClass )); } } else { _liA.push( _this.createA(text, "opt " + optionClass ) ); } } else if ($(this).data('divider') == true) { _liA.push('<div class="divider"></div>'); } else if ($(this).data('hidden') == true) { _liA.push(''); } else { _liA.push( _this.createA(text, optionClass ) ); } }); if (_li.length > 0) { for (var i = 0; i < _li.length; i++) { var $option = this.$element.find('option').eq(i); _liHtml += "<li rel=" + i + ">" + _liA[i] + "</li>"; } } //If we dont have a selected item, and we dont have a title, select the first element so something is set in the button if(this.$element.find('option:selected').length==0 && !_this.options.title) { this.$element.find('option').eq(0).prop('selected', true).attr('selected', 'selected'); } return $(_liHtml); }, createA:function(test, classes) { return '<a tabindex="-1" href="#" class="'+classes+'">' + '<span class="pull-left">' + test + '</span>' + '</a>'; }, render:function() { var _this = this; //Set width of select if (this.options.width == 'auto') { var ulWidth = this.$newElement.find('.dropdown-menu').css('width'); this.$newElement.css('width',ulWidth); } else if (this.options.width && this.options.width != 'auto') { this.$newElement.css('width',this.options.width); } //Update the LI to match the SELECT this.$element.find('option').each(function(index) { _this.setDisabled(index, $(this).is(':disabled') || $(this).parent().is(':disabled') ); _this.setSelected(index, $(this).is(':selected') ); }); var selectedItems = this.$element.find('option:selected').map(function(index,value) { if($(this).attr('title')!=undefined) { return $(this).attr('title'); } else { return $(this).text(); } }).toArray(); //Convert all the values into a comma delimited string var title = selectedItems.join(", "); //If this is multi select, and the selectText type is count, the show 1 of 2 selected etc.. if(_this.multiple && _this.options.selectedTextFormat.indexOf('count') > -1) { var max = _this.options.selectedTextFormat.split(">"); if( (max.length>1 && selectedItems.length > max[1]) || (max.length==1 && selectedItems.length>=2)) { title = selectedItems.length +' of ' + this.$element.find('option').length + ' selected'; } } //If we dont have a title, then use the default, or if nothing is set at all, use the not selected text if(!title) { title = _this.options.title != undefined ? _this.options.title : _this.options.noneSelectedText; } this.$element.next('.select').find('.filter-option').html( title ); }, setSelected:function(index, selected) { if(selected) { this.$newElement.find('li').eq(index).addClass('selected'); } else { this.$newElement.find('li').eq(index).removeClass('selected'); } }, setDisabled:function(index, disabled) { if(disabled) { this.$newElement.find('li').eq(index).addClass('disabled'); } else { this.$newElement.find('li').eq(index).removeClass('disabled'); } }, checkDisabled: function() { if (this.$element.is(':disabled')) { this.button.addClass('disabled'); this.button.click(function(e) { e.preventDefault(); }); } }, checkTabIndex: function() { if (this.$element.is('[tabindex]')) { var tabindex = this.$element.attr("tabindex"); this.button.attr('tabindex', tabindex); } }, clickListener: function() { var _this = this; $('body').on('touchstart.dropdown', '.dropdown-menu', function (e) { e.stopPropagation(); }); this.$newElement.on('click', 'li a', function(e){ var clickedIndex = $(this).parent().index(), $this = $(this).parent(), $select = $this.parents('.select'); //Dont close on multi choice menu if(_this.multiple) { e.stopPropagation(); } e.preventDefault(); //Dont run if we have been disabled if ($select.prev('select').not(':disabled') && !$(this).parent().hasClass('disabled')){ //Deselect all others if not multi select box if (!_this.multiple) { $select.prev('select').find('option').removeAttr('selected'); $select.prev('select').find('option').eq(clickedIndex).prop('selected', true).attr('selected', 'selected'); } //Else toggle the one we have chosen if we are multi selet. else { var selected = $select.prev('select').find('option').eq(clickedIndex).prop('selected'); if(selected) { $select.prev('select').find('option').eq(clickedIndex).removeAttr('selected'); } else { $select.prev('select').find('option').eq(clickedIndex).prop('selected', true).attr('selected', 'selected'); } } $select.find('.filter-option').html($this.text()); $select.find('button').focus(); // Trigger select 'change' $select.prev('select').trigger('change'); } }); this.$newElement.on('click', 'li.disabled a, li dt, li .divider', function(e) { e.preventDefault(); e.stopPropagation(); $select = $(this).parent().parents('.select'); $select.find('button').focus(); }); this.$element.on('change', function(e) { _this.render(); }); }, val:function(value) { if(value!=undefined) { this.$element.val( value ); this.$element.trigger('change'); return this.$element; } else { return this.$element.val(); } } }; $.fn.selectpicker = function(option, event) { //get the args of the outer function.. var args = arguments; var value; var chain = this.each(function () { var $this = $(this), data = $this.data('selectpicker'), options = typeof option == 'object' && option; if (!data) { $this.data('selectpicker', (data = new Selectpicker(this, options, event))); } else { for(var i in option) { data[i]=option[i]; } } if (typeof option == 'string') { //Copy the value of option, as once we shift the arguments //it also shifts the value of option. property = option; if(data[property] instanceof Function) { [].shift.apply(args); value = data[property].apply(data, args); } else { value = data[property]; } } }); if(value!=undefined) { return value; } else { return chain; } }; $.fn.selectpicker.defaults = { style: null, size: 'auto', title: null, selectedTextFormat : 'values', noneSelectedText : 'Nothing selected', width: null, menuStyle: null, toggleSize: null } }(window.jQuery);
var require = { baseUrl : '[BASEURL]', // We only support AMD modules with an explicit define() statement. enforceDefine: true, skipDataMain: true, waitSeconds : 0, paths: { jquery: '[JSURL]lib/jquery/jquery-1.12.1.min[JSEXT]', jqueryui: '[JSURL]lib/jquery/ui-1.11.4/jquery-ui.min[JSEXT]', jqueryprivate: '[JSURL]lib/requirejs/jquery-private[JSEXT]' }, // Custom jquery config map. map: { // '*' means all modules will get 'jqueryprivate' // for their 'jquery' dependency. '*': { jquery: 'jqueryprivate' }, // 'jquery-private' wants the real jQuery module // though. If this line was not here, there would // be an unresolvable cyclic dependency. jqueryprivate: { jquery: 'jquery' } } };
/* flatpickr v4.0.3, @license MIT */ (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : typeof define === 'function' && define.amd ? define(['exports'], factory) : (factory((global.hi = {}))); }(this, (function (exports) { 'use strict'; var fp = typeof window !== "undefined" && window.flatpickr !== undefined ? window.flatpickr : { l10ns: {}, }; var Hindi = { weekdays: { shorthand: ["रवि", "सोम", "मंगल", "बुध", "गुरु", "शुक्र", "शनि"], longhand: [ "रविवार", "सोमवार", "मंगलवार", "बुधवार", "गुरुवार", "शुक्रवार", "शनिवार", ], }, months: { shorthand: [ "जन", "फर", "मार्च", "अप्रेल", "मई", "जून", "जूलाई", "अग", "सित", "अक्ट", "नव", "दि", ], longhand: [ "जनवरी ", "फरवरी", "मार्च", "अप्रेल", "मई", "जून", "जूलाई", "अगस्त ", "सितम्बर", "अक्टूबर", "नवम्बर", "दिसम्बर", ], }, }; fp.l10ns.hi = Hindi; var hi = fp.l10ns; exports.Hindi = Hindi; exports['default'] = hi; Object.defineProperty(exports, '__esModule', { value: true }); })));
/** * ag-grid-community - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components * @version v21.2.2 * @link http://www.ag-grid.com/ * @license MIT */ "use strict"; var __extends = (this && this.__extends) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; Object.defineProperty(exports, "__esModule", { value: true }); var context_1 = require("../context/context"); var gridSerializer_1 = require("./gridSerializer"); var downloader_1 = require("./downloader"); var columnController_1 = require("../columnController/columnController"); var valueService_1 = require("../valueService/valueService"); var gridOptionsWrapper_1 = require("../gridOptionsWrapper"); var constants_1 = require("../constants"); var utils_1 = require("../utils"); var LINE_SEPARATOR = '\r\n'; var CsvSerializingSession = /** @class */ (function (_super) { __extends(CsvSerializingSession, _super); function CsvSerializingSession(config) { var _this = _super.call(this, { columnController: config.columnController, valueService: config.valueService, gridOptionsWrapper: config.gridOptionsWrapper, processCellCallback: config.processCellCallback, processHeaderCallback: config.processHeaderCallback }) || this; _this.result = ''; _this.lineOpened = false; var suppressQuotes = config.suppressQuotes, columnSeparator = config.columnSeparator; _this.suppressQuotes = suppressQuotes; _this.columnSeparator = columnSeparator; return _this; } CsvSerializingSession.prototype.prepare = function (columnsToExport) { }; CsvSerializingSession.prototype.addCustomHeader = function (customHeader) { if (!customHeader) { return; } this.result += customHeader + LINE_SEPARATOR; }; CsvSerializingSession.prototype.addCustomFooter = function (customFooter) { if (!customFooter) { return; } this.result += customFooter + LINE_SEPARATOR; }; CsvSerializingSession.prototype.onNewHeaderGroupingRow = function () { if (this.lineOpened) { this.result += LINE_SEPARATOR; } return { onColumn: this.onNewHeaderGroupingRowColumn.bind(this) }; }; CsvSerializingSession.prototype.onNewHeaderGroupingRowColumn = function (header, index, span) { if (index != 0) { this.result += this.columnSeparator; } this.result += this.putInQuotes(header, this.suppressQuotes); for (var i = 1; i <= span; i++) { this.result += this.columnSeparator + this.putInQuotes("", this.suppressQuotes); } this.lineOpened = true; }; CsvSerializingSession.prototype.onNewHeaderRow = function () { if (this.lineOpened) { this.result += LINE_SEPARATOR; } return { onColumn: this.onNewHeaderRowColumn.bind(this) }; }; CsvSerializingSession.prototype.onNewHeaderRowColumn = function (column, index, node) { if (index != 0) { this.result += this.columnSeparator; } this.result += this.putInQuotes(this.extractHeaderValue(column), this.suppressQuotes); this.lineOpened = true; }; CsvSerializingSession.prototype.onNewBodyRow = function () { if (this.lineOpened) { this.result += LINE_SEPARATOR; } return { onColumn: this.onNewBodyRowColumn.bind(this) }; }; CsvSerializingSession.prototype.onNewBodyRowColumn = function (column, index, node) { if (index != 0) { this.result += this.columnSeparator; } this.result += this.putInQuotes(this.extractRowCellValue(column, index, constants_1.Constants.EXPORT_TYPE_CSV, node), this.suppressQuotes); this.lineOpened = true; }; CsvSerializingSession.prototype.putInQuotes = function (value, suppressQuotes) { if (suppressQuotes) { return value; } if (value === null || value === undefined) { return '""'; } var stringValue; if (typeof value === 'string') { stringValue = value; } else if (typeof value.toString === 'function') { stringValue = value.toString(); } else { console.warn('unknown value type during csv conversion'); stringValue = ''; } // replace each " with "" (ie two sets of double quotes is how to do double quotes in csv) var valueEscaped = stringValue.replace(/"/g, "\"\""); return '"' + valueEscaped + '"'; }; CsvSerializingSession.prototype.parse = function () { return this.result; }; return CsvSerializingSession; }(gridSerializer_1.BaseGridSerializingSession)); exports.CsvSerializingSession = CsvSerializingSession; var BaseCreator = /** @class */ (function () { function BaseCreator() { } BaseCreator.prototype.setBeans = function (beans) { this.beans = beans; }; BaseCreator.prototype.export = function (userParams) { if (this.isExportSuppressed()) { console.warn("ag-grid: Export cancelled. Export is not allowed as per your configuration."); return ''; } var _a = this.getMergedParamsAndData(userParams), mergedParams = _a.mergedParams, data = _a.data; var fileNamePresent = mergedParams && mergedParams.fileName && mergedParams.fileName.length !== 0; var fileName = fileNamePresent ? mergedParams.fileName : this.getDefaultFileName(); if (fileName.indexOf(".") === -1) { fileName = fileName + "." + this.getDefaultFileExtension(); } this.beans.downloader.download(fileName, this.packageFile(data)); return data; }; BaseCreator.prototype.getData = function (params) { return this.getMergedParamsAndData(params).data; }; BaseCreator.prototype.getMergedParamsAndData = function (userParams) { var mergedParams = this.mergeDefaultParams(userParams); var data = this.beans.gridSerializer.serialize(this.createSerializingSession(mergedParams), mergedParams); return { mergedParams: mergedParams, data: data }; }; BaseCreator.prototype.mergeDefaultParams = function (userParams) { var baseParams = this.beans.gridOptionsWrapper.getDefaultExportParams(); var params = {}; utils_1._.assign(params, baseParams); utils_1._.assign(params, userParams); return params; }; BaseCreator.prototype.packageFile = function (data) { return new Blob(["\ufeff", data], { type: window.navigator.msSaveOrOpenBlob ? this.getMimeType() : 'octet/stream' }); }; return BaseCreator; }()); exports.BaseCreator = BaseCreator; var CsvCreator = /** @class */ (function (_super) { __extends(CsvCreator, _super); function CsvCreator() { return _super !== null && _super.apply(this, arguments) || this; } CsvCreator.prototype.postConstruct = function () { this.setBeans({ downloader: this.downloader, gridSerializer: this.gridSerializer, gridOptionsWrapper: this.gridOptionsWrapper }); }; CsvCreator.prototype.exportDataAsCsv = function (params) { return this.export(params); }; CsvCreator.prototype.getDataAsCsv = function (params) { return this.getData(params); }; CsvCreator.prototype.getMimeType = function () { return 'text/csv;charset=utf-8;'; }; CsvCreator.prototype.getDefaultFileName = function () { return 'export.csv'; }; CsvCreator.prototype.getDefaultFileExtension = function () { return 'csv'; }; CsvCreator.prototype.createSerializingSession = function (params) { var _a = this, columnController = _a.columnController, valueService = _a.valueService, gridOptionsWrapper = _a.gridOptionsWrapper; var _b = params, processCellCallback = _b.processCellCallback, processHeaderCallback = _b.processHeaderCallback, suppressQuotes = _b.suppressQuotes, columnSeparator = _b.columnSeparator; return new CsvSerializingSession({ columnController: columnController, valueService: valueService, gridOptionsWrapper: gridOptionsWrapper, processCellCallback: processCellCallback || undefined, processHeaderCallback: processHeaderCallback || undefined, suppressQuotes: suppressQuotes || false, columnSeparator: columnSeparator || ',' }); }; CsvCreator.prototype.isExportSuppressed = function () { return this.gridOptionsWrapper.isSuppressCsvExport(); }; __decorate([ context_1.Autowired('columnController'), __metadata("design:type", columnController_1.ColumnController) ], CsvCreator.prototype, "columnController", void 0); __decorate([ context_1.Autowired('valueService'), __metadata("design:type", valueService_1.ValueService) ], CsvCreator.prototype, "valueService", void 0); __decorate([ context_1.Autowired('downloader'), __metadata("design:type", downloader_1.Downloader) ], CsvCreator.prototype, "downloader", void 0); __decorate([ context_1.Autowired('gridSerializer'), __metadata("design:type", gridSerializer_1.GridSerializer) ], CsvCreator.prototype, "gridSerializer", void 0); __decorate([ context_1.Autowired('gridOptionsWrapper'), __metadata("design:type", gridOptionsWrapper_1.GridOptionsWrapper) ], CsvCreator.prototype, "gridOptionsWrapper", void 0); __decorate([ context_1.PostConstruct, __metadata("design:type", Function), __metadata("design:paramtypes", []), __metadata("design:returntype", void 0) ], CsvCreator.prototype, "postConstruct", null); CsvCreator = __decorate([ context_1.Bean('csvCreator') ], CsvCreator); return CsvCreator; }(BaseCreator)); exports.CsvCreator = CsvCreator;
!function(_,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e(require("dayjs")):"function"==typeof define&&define.amd?define(["dayjs"],e):_.dayjs_locale_am=e(_.dayjs)}(this,function(_){"use strict";_=_&&_.hasOwnProperty("default")?_.default:_;var e={name:"am",weekdays:"እሑድ_ሰኞ_ማክሰኞ_ረቡዕ_ሐሙስ_አርብ_ቅዳሜ".split("_"),weekdaysShort:"እሑድ_ሰኞ_ማክሰ_ረቡዕ_ሐሙስ_አርብ_ቅዳሜ".split("_"),weekdaysMin:"እሑ_ሰኞ_ማክ_ረቡ_ሐሙ_አር_ቅዳ".split("_"),months:"ጃንዋሪ_ፌብሯሪ_ማርች_ኤፕሪል_ሜይ_ጁን_ጁላይ_ኦገስት_ሴፕቴምበር_ኦክቶበር_ኖቬምበር_ዲሴምበር".split("_"),monthsShort:"ጃንዋ_ፌብሯ_ማርች_ኤፕሪ_ሜይ_ጁን_ጁላይ_ኦገስ_ሴፕቴ_ኦክቶ_ኖቬም_ዲሴም".split("_"),weekStart:1,yearStart:4,relativeTime:{future:"በ%s",past:"%s በፊት",s:"ጥቂት ሰከንዶች",m:"አንድ ደቂቃ",mm:"%d ደቂቃዎች",h:"አንድ ሰዓት",hh:"%d ሰዓታት",d:"አንድ ቀን",dd:"%d ቀናት",M:"አንድ ወር",MM:"%d ወራት",y:"አንድ ዓመት",yy:"%d ዓመታት"},formats:{LT:"HH:mm",LTS:"HH:mm:ss",L:"DD/MM/YYYY",LL:"MMMM D ፣ YYYY",LLL:"MMMM D ፣ YYYY HH:mm",LLLL:"dddd ፣ MMMM D ፣ YYYY HH:mm"},ordinal:function(_){return _+"ኛ"}};return _.locale(e,null,!0),e});
function waitsFor (test, fn) { if (test()) { fn(); } else { setTimeout(function () { waitsFor(test, fn); }, 10); } }
/** * Created by azu on 2014/03/25. * LICENSE : MIT */ "use strict"; var assert = require("power-assert"); var sinon = require("sinon"); var racer = require("../src/promise-race-other"); describe("promise-race-other", function () { it("should call both promise", function (done) { var count = 0; var winnerPromise = new Promise(function (resolve) { setTimeout(function () { count++; resolve("this is winner"); }, 4); }); var loserPromise = new Promise(function (resolve) { setTimeout(function () { count++; resolve("this is loser"); }, 64); }).then(function () { assert(count === [winnerPromise, loserPromise].length); done(); }); Promise.race([winnerPromise, loserPromise]).then(function () { assert(count === [winnerPromise, loserPromise].length); }); }); });
exports.BattlePokedex = { bulbasaur:{num:1,species:"Bulbasaur",types:["Grass","Poison"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:45,atk:49,def:49,spa:65,spd:65,spe:45},abilities:{0:"Overgrow",H:"Chlorophyll"},heightm:0.7,weightkg:6.9,color:"Green",evos:["ivysaur"],eggGroups:["Monster","Grass"]}, ivysaur:{num:2,species:"Ivysaur",types:["Grass","Poison"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:60,atk:62,def:63,spa:80,spd:80,spe:60},abilities:{0:"Overgrow",H:"Chlorophyll"},heightm:1,weightkg:13,color:"Green",prevo:"bulbasaur",evos:["venusaur"],evoLevel:16,eggGroups:["Monster","Grass"]}, venusaur:{num:3,species:"Venusaur",types:["Grass","Poison"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:80,atk:82,def:83,spa:100,spd:100,spe:80},abilities:{0:"Overgrow",H:"Chlorophyll"},heightm:2,weightkg:100,color:"Green",prevo:"ivysaur",evoLevel:32,eggGroups:["Monster","Grass"],otherFormes:["venusaurmega"]}, venusaurmega:{num:3,species:"Venusaur-Mega",baseSpecies:"Venusaur",forme:"Mega",formeLetter:"M",types:["Grass","Poison"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:80,atk:100,def:123,spa:122,spd:120,spe:80},abilities:{0:"Thick Fat"},heightm:2.4,weightkg:155.5,color:"Green",prevo:"ivysaur",evoLevel:32,eggGroups:["Monster","Grass"]}, charmander:{num:4,species:"Charmander",types:["Fire"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:39,atk:52,def:43,spa:60,spd:50,spe:65},abilities:{0:"Blaze",H:"Solar Power"},heightm:0.6,weightkg:8.5,color:"Red",evos:["charmeleon"],eggGroups:["Monster","Dragon"]}, charmeleon:{num:5,species:"Charmeleon",types:["Fire"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:58,atk:64,def:58,spa:80,spd:65,spe:80},abilities:{0:"Blaze",H:"Solar Power"},heightm:1.1,weightkg:19,color:"Red",prevo:"charmander",evos:["charizard"],evoLevel:16,eggGroups:["Monster","Dragon"]}, charizard:{num:6,species:"Charizard",types:["Fire","Flying"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:78,atk:84,def:78,spa:109,spd:85,spe:100},abilities:{0:"Blaze",H:"Solar Power"},heightm:1.7,weightkg:90.5,color:"Red",prevo:"charmeleon",evoLevel:36,eggGroups:["Monster","Dragon"],otherFormes:["charizardmegax","charizardmegay"]}, charizardmegax:{num:6,species:"Charizard-Mega-X",baseSpecies:"Charizard",forme:"Mega-X",formeLetter:"M",types:["Fire","Dragon"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:78,atk:130,def:111,spa:130,spd:85,spe:100},abilities:{0:"Tough Claws"},heightm:1.7,weightkg:110.5,color:"Red",prevo:"charmeleon",evoLevel:36,eggGroups:["Monster","Dragon"]}, charizardmegay:{num:6,species:"Charizard-Mega-Y",baseSpecies:"Charizard",forme:"Mega-Y",formeLetter:"M",types:["Fire","Flying"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:78,atk:104,def:78,spa:159,spd:115,spe:100},abilities:{0:"Drought"},heightm:1.7,weightkg:100.5,color:"Red",prevo:"charmeleon",evoLevel:36,eggGroups:["Monster","Dragon"]}, squirtle:{num:7,species:"Squirtle",types:["Water"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:44,atk:48,def:65,spa:50,spd:64,spe:43},abilities:{0:"Torrent",H:"Rain Dish"},heightm:0.5,weightkg:9,color:"Blue",evos:["wartortle"],eggGroups:["Monster","Water 1"]}, wartortle:{num:8,species:"Wartortle",types:["Water"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:59,atk:63,def:80,spa:65,spd:80,spe:58},abilities:{0:"Torrent",H:"Rain Dish"},heightm:1,weightkg:22.5,color:"Blue",prevo:"squirtle",evos:["blastoise"],evoLevel:16,eggGroups:["Monster","Water 1"]}, blastoise:{num:9,species:"Blastoise",types:["Water"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:79,atk:83,def:100,spa:85,spd:105,spe:78},abilities:{0:"Torrent",H:"Rain Dish"},heightm:1.6,weightkg:85.5,color:"Blue",prevo:"wartortle",evoLevel:36,eggGroups:["Monster","Water 1"],otherFormes:["blastoisemega"]}, blastoisemega:{num:9,species:"Blastoise-Mega",baseSpecies:"Blastoise",forme:"Mega",formeLetter:"M",types:["Water"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:79,atk:103,def:120,spa:135,spd:115,spe:78},abilities:{0:"Mega Launcher"},heightm:1.6,weightkg:101.1,color:"Blue",prevo:"wartortle",evoLevel:36,eggGroups:["Monster","Water 1"]}, caterpie:{num:10,species:"Caterpie",types:["Bug"],baseStats:{hp:45,atk:30,def:35,spa:20,spd:20,spe:45},abilities:{0:"Shield Dust",H:"Run Away"},heightm:0.3,weightkg:2.9,color:"Green",evos:["metapod"],eggGroups:["Bug"]}, metapod:{num:11,species:"Metapod",types:["Bug"],baseStats:{hp:50,atk:20,def:55,spa:25,spd:25,spe:30},abilities:{0:"Shed Skin"},heightm:0.7,weightkg:9.9,color:"Green",prevo:"caterpie",evos:["butterfree"],evoLevel:7,eggGroups:["Bug"]}, butterfree:{num:12,species:"Butterfree",types:["Bug","Flying"],baseStats:{hp:60,atk:45,def:50,spa:90,spd:80,spe:70},abilities:{0:"Compound Eyes",H:"Tinted Lens"},heightm:1.1,weightkg:32,color:"White",prevo:"metapod",evoLevel:10,eggGroups:["Bug"]}, weedle:{num:13,species:"Weedle",types:["Bug","Poison"],baseStats:{hp:40,atk:35,def:30,spa:20,spd:20,spe:50},abilities:{0:"Shield Dust",H:"Run Away"},heightm:0.3,weightkg:3.2,color:"Brown",evos:["kakuna"],eggGroups:["Bug"]}, kakuna:{num:14,species:"Kakuna",types:["Bug","Poison"],baseStats:{hp:45,atk:25,def:50,spa:25,spd:25,spe:35},abilities:{0:"Shed Skin"},heightm:0.6,weightkg:10,color:"Yellow",prevo:"weedle",evos:["beedrill"],evoLevel:7,eggGroups:["Bug"]}, beedrill:{num:15,species:"Beedrill",types:["Bug","Poison"],baseStats:{hp:65,atk:90,def:40,spa:45,spd:80,spe:75},abilities:{0:"Swarm",H:"Sniper"},heightm:1,weightkg:29.5,color:"Yellow",prevo:"kakuna",evoLevel:10,eggGroups:["Bug"]}, pidgey:{num:16,species:"Pidgey",types:["Normal","Flying"],baseStats:{hp:40,atk:45,def:40,spa:35,spd:35,spe:56},abilities:{0:"Keen Eye",1:"Tangled Feet",H:"Big Pecks"},heightm:0.3,weightkg:1.8,color:"Brown",evos:["pidgeotto"],eggGroups:["Flying"]}, pidgeotto:{num:17,species:"Pidgeotto",types:["Normal","Flying"],baseStats:{hp:63,atk:60,def:55,spa:50,spd:50,spe:71},abilities:{0:"Keen Eye",1:"Tangled Feet",H:"Big Pecks"},heightm:1.1,weightkg:30,color:"Brown",prevo:"pidgey",evos:["pidgeot"],evoLevel:18,eggGroups:["Flying"]}, pidgeot:{num:18,species:"Pidgeot",types:["Normal","Flying"],baseStats:{hp:83,atk:80,def:75,spa:70,spd:70,spe:101},abilities:{0:"Keen Eye",1:"Tangled Feet",H:"Big Pecks"},heightm:1.5,weightkg:39.5,color:"Brown",prevo:"pidgeotto",evoLevel:36,eggGroups:["Flying"]}, rattata:{num:19,species:"Rattata",types:["Normal"],baseStats:{hp:30,atk:56,def:35,spa:25,spd:35,spe:72},abilities:{0:"Run Away",1:"Guts",H:"Hustle"},heightm:0.3,weightkg:3.5,color:"Purple",evos:["raticate"],eggGroups:["Field"]}, raticate:{num:20,species:"Raticate",types:["Normal"],baseStats:{hp:55,atk:81,def:60,spa:50,spd:70,spe:97},abilities:{0:"Run Away",1:"Guts",H:"Hustle"},heightm:0.7,weightkg:18.5,color:"Brown",prevo:"rattata",evoLevel:20,eggGroups:["Field"]}, spearow:{num:21,species:"Spearow",types:["Normal","Flying"],baseStats:{hp:40,atk:60,def:30,spa:31,spd:31,spe:70},abilities:{0:"Keen Eye",H:"Sniper"},heightm:0.3,weightkg:2,color:"Brown",evos:["fearow"],eggGroups:["Flying"]}, fearow:{num:22,species:"Fearow",types:["Normal","Flying"],baseStats:{hp:65,atk:90,def:65,spa:61,spd:61,spe:100},abilities:{0:"Keen Eye",H:"Sniper"},heightm:1.2,weightkg:38,color:"Brown",prevo:"spearow",evoLevel:20,eggGroups:["Flying"]}, ekans:{num:23,species:"Ekans",types:["Poison"],baseStats:{hp:35,atk:60,def:44,spa:40,spd:54,spe:55},abilities:{0:"Intimidate",1:"Shed Skin",H:"Unnerve"},heightm:2,weightkg:6.9,color:"Purple",evos:["arbok"],eggGroups:["Field","Dragon"]}, arbok:{num:24,species:"Arbok",types:["Poison"],baseStats:{hp:60,atk:85,def:69,spa:65,spd:79,spe:80},abilities:{0:"Intimidate",1:"Shed Skin",H:"Unnerve"},heightm:3.5,weightkg:65,color:"Purple",prevo:"ekans",evoLevel:22,eggGroups:["Field","Dragon"]}, pikachu:{num:25,species:"Pikachu",types:["Electric"],baseStats:{hp:35,atk:55,def:40,spa:50,spd:50,spe:90},abilities:{0:"Static",H:"Lightningrod"},heightm:0.4,weightkg:6,color:"Yellow",prevo:"pichu",evos:["raichu"],evoLevel:1,eggGroups:["Field","Fairy"]}, raichu:{num:26,species:"Raichu",types:["Electric"],baseStats:{hp:60,atk:90,def:55,spa:90,spd:80,spe:110},abilities:{0:"Static",H:"Lightningrod"},heightm:0.8,weightkg:30,color:"Yellow",prevo:"pikachu",evoLevel:1,eggGroups:["Field","Fairy"]}, sandshrew:{num:27,species:"Sandshrew",types:["Ground"],baseStats:{hp:50,atk:75,def:85,spa:20,spd:30,spe:40},abilities:{0:"Sand Veil",H:"Sand Rush"},heightm:0.6,weightkg:12,color:"Yellow",evos:["sandslash"],eggGroups:["Field"]}, sandslash:{num:28,species:"Sandslash",types:["Ground"],baseStats:{hp:75,atk:100,def:110,spa:45,spd:55,spe:65},abilities:{0:"Sand Veil",H:"Sand Rush"},heightm:1,weightkg:29.5,color:"Yellow",prevo:"sandshrew",evoLevel:22,eggGroups:["Field"]}, nidoranf:{num:29,species:"Nidoran-F",types:["Poison"],gender:"F",baseStats:{hp:55,atk:47,def:52,spa:40,spd:40,spe:41},abilities:{0:"Poison Point",1:"Rivalry",H:"Hustle"},heightm:0.4,weightkg:7,color:"Blue",evos:["nidorina"],eggGroups:["Monster","Field"]}, nidorina:{num:30,species:"Nidorina",types:["Poison"],gender:"F",baseStats:{hp:70,atk:62,def:67,spa:55,spd:55,spe:56},abilities:{0:"Poison Point",1:"Rivalry",H:"Hustle"},heightm:0.8,weightkg:20,color:"Blue",prevo:"nidoranf",evos:["nidoqueen"],evoLevel:16,eggGroups:["Undiscovered"]}, nidoqueen:{num:31,species:"Nidoqueen",types:["Poison","Ground"],gender:"F",baseStats:{hp:90,atk:92,def:87,spa:75,spd:85,spe:76},abilities:{0:"Poison Point",1:"Rivalry",H:"Sheer Force"},heightm:1.3,weightkg:60,color:"Blue",prevo:"nidorina",evoLevel:16,eggGroups:["Undiscovered"]}, nidoranm:{num:32,species:"Nidoran-M",types:["Poison"],gender:"M",baseStats:{hp:46,atk:57,def:40,spa:40,spd:40,spe:50},abilities:{0:"Poison Point",1:"Rivalry",H:"Hustle"},heightm:0.5,weightkg:9,color:"Purple",evos:["nidorino"],eggGroups:["Monster","Field"]}, nidorino:{num:33,species:"Nidorino",types:["Poison"],gender:"M",baseStats:{hp:61,atk:72,def:57,spa:55,spd:55,spe:65},abilities:{0:"Poison Point",1:"Rivalry",H:"Hustle"},heightm:0.9,weightkg:19.5,color:"Purple",prevo:"nidoranm",evos:["nidoking"],evoLevel:16,eggGroups:["Monster","Field"]}, nidoking:{num:34,species:"Nidoking",types:["Poison","Ground"],gender:"M",baseStats:{hp:81,atk:102,def:77,spa:85,spd:75,spe:85},abilities:{0:"Poison Point",1:"Rivalry",H:"Sheer Force"},heightm:1.4,weightkg:62,color:"Purple",prevo:"nidorino",evoLevel:16,eggGroups:["Monster","Field"]}, clefairy:{num:35,species:"Clefairy",types:["Fairy"],genderRatio:{M:0.25,F:0.75},baseStats:{hp:70,atk:45,def:48,spa:60,spd:65,spe:35},abilities:{0:"Cute Charm",1:"Magic Guard",H:"Friend Guard"},heightm:0.6,weightkg:7.5,color:"Pink",prevo:"cleffa",evos:["clefable"],evoLevel:1,eggGroups:["Fairy"]}, clefable:{num:36,species:"Clefable",types:["Fairy"],genderRatio:{M:0.25,F:0.75},baseStats:{hp:95,atk:70,def:73,spa:95,spd:90,spe:60},abilities:{0:"Cute Charm",1:"Magic Guard",H:"Unaware"},heightm:1.3,weightkg:40,color:"Pink",prevo:"clefairy",evoLevel:1,eggGroups:["Fairy"]}, vulpix:{num:37,species:"Vulpix",types:["Fire"],genderRatio:{M:0.25,F:0.75},baseStats:{hp:38,atk:41,def:40,spa:50,spd:65,spe:65},abilities:{0:"Flash Fire",H:"Drought"},heightm:0.6,weightkg:9.9,color:"Brown",evos:["ninetales"],eggGroups:["Field"]}, ninetales:{num:38,species:"Ninetales",types:["Fire"],genderRatio:{M:0.25,F:0.75},baseStats:{hp:73,atk:76,def:75,spa:81,spd:100,spe:100},abilities:{0:"Flash Fire",H:"Drought"},heightm:1.1,weightkg:19.9,color:"Yellow",prevo:"vulpix",evoLevel:1,eggGroups:["Field"]}, jigglypuff:{num:39,species:"Jigglypuff",types:["Normal","Fairy"],genderRatio:{M:0.25,F:0.75},baseStats:{hp:115,atk:45,def:20,spa:45,spd:25,spe:20},abilities:{0:"Cute Charm",1:"Competitive",H:"Friend Guard"},heightm:0.5,weightkg:5.5,color:"Pink",prevo:"igglybuff",evos:["wigglytuff"],evoLevel:1,eggGroups:["Fairy"]}, wigglytuff:{num:40,species:"Wigglytuff",types:["Normal","Fairy"],genderRatio:{M:0.25,F:0.75},baseStats:{hp:140,atk:70,def:45,spa:85,spd:50,spe:45},abilities:{0:"Cute Charm",1:"Competitive",H:"Frisk"},heightm:1,weightkg:12,color:"Pink",prevo:"jigglypuff",evoLevel:1,eggGroups:["Fairy"]}, zubat:{num:41,species:"Zubat",types:["Poison","Flying"],baseStats:{hp:40,atk:45,def:35,spa:30,spd:40,spe:55},abilities:{0:"Inner Focus",H:"Infiltrator"},heightm:0.8,weightkg:7.5,color:"Purple",evos:["golbat"],eggGroups:["Flying"]}, golbat:{num:42,species:"Golbat",types:["Poison","Flying"],baseStats:{hp:75,atk:80,def:70,spa:65,spd:75,spe:90},abilities:{0:"Inner Focus",H:"Infiltrator"},heightm:1.6,weightkg:55,color:"Purple",prevo:"zubat",evos:["crobat"],evoLevel:22,eggGroups:["Flying"]}, oddish:{num:43,species:"Oddish",types:["Grass","Poison"],baseStats:{hp:45,atk:50,def:55,spa:75,spd:65,spe:30},abilities:{0:"Chlorophyll",H:"Run Away"},heightm:0.5,weightkg:5.4,color:"Blue",evos:["gloom"],eggGroups:["Grass"]}, gloom:{num:44,species:"Gloom",types:["Grass","Poison"],baseStats:{hp:60,atk:65,def:70,spa:85,spd:75,spe:40},abilities:{0:"Chlorophyll",H:"Stench"},heightm:0.8,weightkg:8.6,color:"Blue",prevo:"oddish",evos:["vileplume","bellossom"],evoLevel:21,eggGroups:["Grass"]}, vileplume:{num:45,species:"Vileplume",types:["Grass","Poison"],baseStats:{hp:75,atk:80,def:85,spa:110,spd:90,spe:50},abilities:{0:"Chlorophyll",H:"Effect Spore"},heightm:1.2,weightkg:18.6,color:"Red",prevo:"gloom",evoLevel:21,eggGroups:["Grass"]}, paras:{num:46,species:"Paras",types:["Bug","Grass"],baseStats:{hp:35,atk:70,def:55,spa:45,spd:55,spe:25},abilities:{0:"Effect Spore",1:"Dry Skin",H:"Damp"},heightm:0.3,weightkg:5.4,color:"Red",evos:["parasect"],eggGroups:["Bug","Grass"]}, parasect:{num:47,species:"Parasect",types:["Bug","Grass"],baseStats:{hp:60,atk:95,def:80,spa:60,spd:80,spe:30},abilities:{0:"Effect Spore",1:"Dry Skin",H:"Damp"},heightm:1,weightkg:29.5,color:"Red",prevo:"paras",evoLevel:24,eggGroups:["Bug","Grass"]}, venonat:{num:48,species:"Venonat",types:["Bug","Poison"],baseStats:{hp:60,atk:55,def:50,spa:40,spd:55,spe:45},abilities:{0:"Compound Eyes",1:"Tinted Lens",H:"Run Away"},heightm:1,weightkg:30,color:"Purple",evos:["venomoth"],eggGroups:["Bug"]}, venomoth:{num:49,species:"Venomoth",types:["Bug","Poison"],baseStats:{hp:70,atk:65,def:60,spa:90,spd:75,spe:90},abilities:{0:"Shield Dust",1:"Tinted Lens",H:"Wonder Skin"},heightm:1.5,weightkg:12.5,color:"Purple",prevo:"venonat",evoLevel:31,eggGroups:["Bug"]}, diglett:{num:50,species:"Diglett",types:["Ground"],baseStats:{hp:10,atk:55,def:25,spa:35,spd:45,spe:95},abilities:{0:"Sand Veil",1:"Arena Trap",H:"Sand Force"},heightm:0.2,weightkg:0.8,color:"Brown",evos:["dugtrio"],eggGroups:["Field"]}, dugtrio:{num:51,species:"Dugtrio",types:["Ground"],baseStats:{hp:35,atk:80,def:50,spa:50,spd:70,spe:120},abilities:{0:"Sand Veil",1:"Arena Trap",H:"Sand Force"},heightm:0.7,weightkg:33.3,color:"Brown",prevo:"diglett",evoLevel:26,eggGroups:["Field"]}, meowth:{num:52,species:"Meowth",types:["Normal"],baseStats:{hp:40,atk:45,def:35,spa:40,spd:40,spe:90},abilities:{0:"Pickup",1:"Technician",H:"Unnerve"},heightm:0.4,weightkg:4.2,color:"Yellow",evos:["persian"],eggGroups:["Field"]}, persian:{num:53,species:"Persian",types:["Normal"],baseStats:{hp:65,atk:70,def:60,spa:65,spd:65,spe:115},abilities:{0:"Limber",1:"Technician",H:"Unnerve"},heightm:1,weightkg:32,color:"Yellow",prevo:"meowth",evoLevel:28,eggGroups:["Field"]}, psyduck:{num:54,species:"Psyduck",types:["Water"],baseStats:{hp:50,atk:52,def:48,spa:65,spd:50,spe:55},abilities:{0:"Damp",1:"Cloud Nine",H:"Swift Swim"},heightm:0.8,weightkg:19.6,color:"Yellow",evos:["golduck"],eggGroups:["Water 1","Field"]}, golduck:{num:55,species:"Golduck",types:["Water"],baseStats:{hp:80,atk:82,def:78,spa:95,spd:80,spe:85},abilities:{0:"Damp",1:"Cloud Nine",H:"Swift Swim"},heightm:1.7,weightkg:76.6,color:"Blue",prevo:"psyduck",evoLevel:33,eggGroups:["Water 1","Field"]}, mankey:{num:56,species:"Mankey",types:["Fighting"],baseStats:{hp:40,atk:80,def:35,spa:35,spd:45,spe:70},abilities:{0:"Vital Spirit",1:"Anger Point",H:"Defiant"},heightm:0.5,weightkg:28,color:"Brown",evos:["primeape"],eggGroups:["Field"]}, primeape:{num:57,species:"Primeape",types:["Fighting"],baseStats:{hp:65,atk:105,def:60,spa:60,spd:70,spe:95},abilities:{0:"Vital Spirit",1:"Anger Point",H:"Defiant"},heightm:1,weightkg:32,color:"Brown",prevo:"mankey",evoLevel:28,eggGroups:["Field"]}, growlithe:{num:58,species:"Growlithe",types:["Fire"],genderRatio:{M:0.75,F:0.25},baseStats:{hp:55,atk:70,def:45,spa:70,spd:50,spe:60},abilities:{0:"Intimidate",1:"Flash Fire",H:"Justified"},heightm:0.7,weightkg:19,color:"Brown",evos:["arcanine"],eggGroups:["Field"]}, arcanine:{num:59,species:"Arcanine",types:["Fire"],genderRatio:{M:0.75,F:0.25},baseStats:{hp:90,atk:110,def:80,spa:100,spd:80,spe:95},abilities:{0:"Intimidate",1:"Flash Fire",H:"Justified"},heightm:1.9,weightkg:155,color:"Brown",prevo:"growlithe",evoLevel:1,eggGroups:["Field"]}, poliwag:{num:60,species:"Poliwag",types:["Water"],baseStats:{hp:40,atk:50,def:40,spa:40,spd:40,spe:90},abilities:{0:"Water Absorb",1:"Damp",H:"Swift Swim"},heightm:0.6,weightkg:12.4,color:"Blue",evos:["poliwhirl"],eggGroups:["Water 1"]}, poliwhirl:{num:61,species:"Poliwhirl",types:["Water"],baseStats:{hp:65,atk:65,def:65,spa:50,spd:50,spe:90},abilities:{0:"Water Absorb",1:"Damp",H:"Swift Swim"},heightm:1,weightkg:20,color:"Blue",prevo:"poliwag",evos:["poliwrath","politoed"],evoLevel:25,eggGroups:["Water 1"]}, poliwrath:{num:62,species:"Poliwrath",types:["Water","Fighting"],baseStats:{hp:90,atk:95,def:95,spa:70,spd:90,spe:70},abilities:{0:"Water Absorb",1:"Damp",H:"Swift Swim"},heightm:1.3,weightkg:54,color:"Blue",prevo:"poliwhirl",evoLevel:25,eggGroups:["Water 1"]}, abra:{num:63,species:"Abra",types:["Psychic"],genderRatio:{M:0.75,F:0.25},baseStats:{hp:25,atk:20,def:15,spa:105,spd:55,spe:90},abilities:{0:"Synchronize",1:"Inner Focus",H:"Magic Guard"},heightm:0.9,weightkg:19.5,color:"Brown",evos:["kadabra"],eggGroups:["Human-Like"]}, kadabra:{num:64,species:"Kadabra",types:["Psychic"],genderRatio:{M:0.75,F:0.25},baseStats:{hp:40,atk:35,def:30,spa:120,spd:70,spe:105},abilities:{0:"Synchronize",1:"Inner Focus",H:"Magic Guard"},heightm:1.3,weightkg:56.5,color:"Brown",prevo:"abra",evos:["alakazam"],evoLevel:16,eggGroups:["Human-Like"]}, alakazam:{num:65,species:"Alakazam",types:["Psychic"],genderRatio:{M:0.75,F:0.25},baseStats:{hp:55,atk:50,def:45,spa:135,spd:95,spe:120},abilities:{0:"Synchronize",1:"Inner Focus",H:"Magic Guard"},heightm:1.5,weightkg:48,color:"Brown",prevo:"kadabra",evoLevel:16,eggGroups:["Human-Like"],otherFormes:["alakazammega"]}, alakazammega:{num:65,species:"Alakazam-Mega",baseSpecies:"Alakazam",forme:"Mega",formeLetter:"M",types:["Psychic"],genderRatio:{M:0.75,F:0.25},baseStats:{hp:55,atk:50,def:65,spa:175,spd:95,spe:150},abilities:{0:"Trace"},heightm:1.2,weightkg:48,color:"Brown",prevo:"kadabra",evoLevel:16,eggGroups:["Human-Like"]}, machop:{num:66,species:"Machop",types:["Fighting"],genderRatio:{M:0.75,F:0.25},baseStats:{hp:70,atk:80,def:50,spa:35,spd:35,spe:35},abilities:{0:"Guts",1:"No Guard",H:"Steadfast"},heightm:0.8,weightkg:19.5,color:"Gray",evos:["machoke"],eggGroups:["Human-Like"]}, machoke:{num:67,species:"Machoke",types:["Fighting"],genderRatio:{M:0.75,F:0.25},baseStats:{hp:80,atk:100,def:70,spa:50,spd:60,spe:45},abilities:{0:"Guts",1:"No Guard",H:"Steadfast"},heightm:1.5,weightkg:70.5,color:"Gray",prevo:"machop",evos:["machamp"],evoLevel:28,eggGroups:["Human-Like"]}, machamp:{num:68,species:"Machamp",types:["Fighting"],genderRatio:{M:0.75,F:0.25},baseStats:{hp:90,atk:130,def:80,spa:65,spd:85,spe:55},abilities:{0:"Guts",1:"No Guard",H:"Steadfast"},heightm:1.6,weightkg:130,color:"Gray",prevo:"machoke",evoLevel:28,eggGroups:["Human-Like"]}, bellsprout:{num:69,species:"Bellsprout",types:["Grass","Poison"],baseStats:{hp:50,atk:75,def:35,spa:70,spd:30,spe:40},abilities:{0:"Chlorophyll",H:"Gluttony"},heightm:0.7,weightkg:4,color:"Green",evos:["weepinbell"],eggGroups:["Grass"]}, weepinbell:{num:70,species:"Weepinbell",types:["Grass","Poison"],baseStats:{hp:65,atk:90,def:50,spa:85,spd:45,spe:55},abilities:{0:"Chlorophyll",H:"Gluttony"},heightm:1,weightkg:6.4,color:"Green",prevo:"bellsprout",evos:["victreebel"],evoLevel:21,eggGroups:["Grass"]}, victreebel:{num:71,species:"Victreebel",types:["Grass","Poison"],baseStats:{hp:80,atk:105,def:65,spa:100,spd:70,spe:70},abilities:{0:"Chlorophyll",H:"Gluttony"},heightm:1.7,weightkg:15.5,color:"Green",prevo:"weepinbell",evoLevel:21,eggGroups:["Grass"]}, tentacool:{num:72,species:"Tentacool",types:["Water","Poison"],baseStats:{hp:40,atk:40,def:35,spa:50,spd:100,spe:70},abilities:{0:"Clear Body",1:"Liquid Ooze",H:"Rain Dish"},heightm:0.9,weightkg:45.5,color:"Blue",evos:["tentacruel"],eggGroups:["Water 3"]}, tentacruel:{num:73,species:"Tentacruel",types:["Water","Poison"],baseStats:{hp:80,atk:70,def:65,spa:80,spd:120,spe:100},abilities:{0:"Clear Body",1:"Liquid Ooze",H:"Rain Dish"},heightm:1.6,weightkg:55,color:"Blue",prevo:"tentacool",evoLevel:30,eggGroups:["Water 3"]}, geodude:{num:74,species:"Geodude",types:["Rock","Ground"],baseStats:{hp:40,atk:80,def:100,spa:30,spd:30,spe:20},abilities:{0:"Rock Head",1:"Sturdy",H:"Sand Veil"},heightm:0.4,weightkg:20,color:"Brown",evos:["graveler"],eggGroups:["Mineral"]}, graveler:{num:75,species:"Graveler",types:["Rock","Ground"],baseStats:{hp:55,atk:95,def:115,spa:45,spd:45,spe:35},abilities:{0:"Rock Head",1:"Sturdy",H:"Sand Veil"},heightm:1,weightkg:105,color:"Brown",prevo:"geodude",evos:["golem"],evoLevel:25,eggGroups:["Mineral"]}, golem:{num:76,species:"Golem",types:["Rock","Ground"],baseStats:{hp:80,atk:120,def:130,spa:55,spd:65,spe:45},abilities:{0:"Rock Head",1:"Sturdy",H:"Sand Veil"},heightm:1.4,weightkg:300,color:"Brown",prevo:"graveler",evoLevel:25,eggGroups:["Mineral"]}, ponyta:{num:77,species:"Ponyta",types:["Fire"],baseStats:{hp:50,atk:85,def:55,spa:65,spd:65,spe:90},abilities:{0:"Run Away",1:"Flash Fire",H:"Flame Body"},heightm:1,weightkg:30,color:"Yellow",evos:["rapidash"],eggGroups:["Field"]}, rapidash:{num:78,species:"Rapidash",types:["Fire"],baseStats:{hp:65,atk:100,def:70,spa:80,spd:80,spe:105},abilities:{0:"Run Away",1:"Flash Fire",H:"Flame Body"},heightm:1.7,weightkg:95,color:"Yellow",prevo:"ponyta",evoLevel:40,eggGroups:["Field"]}, slowpoke:{num:79,species:"Slowpoke",types:["Water","Psychic"],baseStats:{hp:90,atk:65,def:65,spa:40,spd:40,spe:15},abilities:{0:"Oblivious",1:"Own Tempo",H:"Regenerator"},heightm:1.2,weightkg:36,color:"Pink",evos:["slowbro","slowking"],eggGroups:["Monster","Water 1"]}, slowbro:{num:80,species:"Slowbro",types:["Water","Psychic"],baseStats:{hp:95,atk:75,def:110,spa:100,spd:80,spe:30},abilities:{0:"Oblivious",1:"Own Tempo",H:"Regenerator"},heightm:1.6,weightkg:78.5,color:"Pink",prevo:"slowpoke",evoLevel:37,eggGroups:["Monster","Water 1"]}, magnemite:{num:81,species:"Magnemite",types:["Electric","Steel"],gender:"N",baseStats:{hp:25,atk:35,def:70,spa:95,spd:55,spe:45},abilities:{0:"Magnet Pull",1:"Sturdy",H:"Analytic"},heightm:0.3,weightkg:6,color:"Gray",evos:["magneton"],eggGroups:["Mineral"]}, magneton:{num:82,species:"Magneton",types:["Electric","Steel"],gender:"N",baseStats:{hp:50,atk:60,def:95,spa:120,spd:70,spe:70},abilities:{0:"Magnet Pull",1:"Sturdy",H:"Analytic"},heightm:1,weightkg:60,color:"Gray",prevo:"magnemite",evos:["magnezone"],evoLevel:30,eggGroups:["Mineral"]}, farfetchd:{num:83,species:"Farfetch'd",types:["Normal","Flying"],baseStats:{hp:52,atk:65,def:55,spa:58,spd:62,spe:60},abilities:{0:"Keen Eye",1:"Inner Focus",H:"Defiant"},heightm:0.8,weightkg:15,color:"Brown",eggGroups:["Flying","Field"]}, doduo:{num:84,species:"Doduo",types:["Normal","Flying"],baseStats:{hp:35,atk:85,def:45,spa:35,spd:35,spe:75},abilities:{0:"Run Away",1:"Early Bird",H:"Tangled Feet"},heightm:1.4,weightkg:39.2,color:"Brown",evos:["dodrio"],eggGroups:["Flying"]}, dodrio:{num:85,species:"Dodrio",types:["Normal","Flying"],baseStats:{hp:60,atk:110,def:70,spa:60,spd:60,spe:100},abilities:{0:"Run Away",1:"Early Bird",H:"Tangled Feet"},heightm:1.8,weightkg:85.2,color:"Brown",prevo:"doduo",evoLevel:31,eggGroups:["Flying"]}, seel:{num:86,species:"Seel",types:["Water"],baseStats:{hp:65,atk:45,def:55,spa:45,spd:70,spe:45},abilities:{0:"Thick Fat",1:"Hydration",H:"Ice Body"},heightm:1.1,weightkg:90,color:"White",evos:["dewgong"],eggGroups:["Water 1","Field"]}, dewgong:{num:87,species:"Dewgong",types:["Water","Ice"],baseStats:{hp:90,atk:70,def:80,spa:70,spd:95,spe:70},abilities:{0:"Thick Fat",1:"Hydration",H:"Ice Body"},heightm:1.7,weightkg:120,color:"White",prevo:"seel",evoLevel:34,eggGroups:["Water 1","Field"]}, grimer:{num:88,species:"Grimer",types:["Poison"],baseStats:{hp:80,atk:80,def:50,spa:40,spd:50,spe:25},abilities:{0:"Stench",1:"Sticky Hold",H:"Poison Touch"},heightm:0.9,weightkg:30,color:"Purple",evos:["muk"],eggGroups:["Amorphous"]}, muk:{num:89,species:"Muk",types:["Poison"],baseStats:{hp:105,atk:105,def:75,spa:65,spd:100,spe:50},abilities:{0:"Stench",1:"Sticky Hold",H:"Poison Touch"},heightm:1.2,weightkg:30,color:"Purple",prevo:"grimer",evoLevel:38,eggGroups:["Amorphous"]}, shellder:{num:90,species:"Shellder",types:["Water"],baseStats:{hp:30,atk:65,def:100,spa:45,spd:25,spe:40},abilities:{0:"Shell Armor",1:"Skill Link",H:"Overcoat"},heightm:0.3,weightkg:4,color:"Purple",evos:["cloyster"],eggGroups:["Water 3"]}, cloyster:{num:91,species:"Cloyster",types:["Water","Ice"],baseStats:{hp:50,atk:95,def:180,spa:85,spd:45,spe:70},abilities:{0:"Shell Armor",1:"Skill Link",H:"Overcoat"},heightm:1.5,weightkg:132.5,color:"Purple",prevo:"shellder",evoLevel:1,eggGroups:["Water 3"]}, gastly:{num:92,species:"Gastly",types:["Ghost","Poison"],baseStats:{hp:30,atk:35,def:30,spa:100,spd:35,spe:80},abilities:{0:"Levitate"},heightm:1.3,weightkg:0.1,color:"Purple",evos:["haunter"],eggGroups:["Amorphous"]}, haunter:{num:93,species:"Haunter",types:["Ghost","Poison"],baseStats:{hp:45,atk:50,def:45,spa:115,spd:55,spe:95},abilities:{0:"Levitate"},heightm:1.6,weightkg:0.1,color:"Purple",prevo:"gastly",evos:["gengar"],evoLevel:25,eggGroups:["Amorphous"]}, gengar:{num:94,species:"Gengar",types:["Ghost","Poison"],baseStats:{hp:60,atk:65,def:60,spa:130,spd:75,spe:110},abilities:{0:"Levitate"},heightm:1.5,weightkg:40.5,color:"Purple",prevo:"haunter",evoLevel:25,eggGroups:["Amorphous"],otherFormes:["gengarmega"]}, gengarmega:{num:94,species:"Gengar-Mega",baseSpecies:"Gengar",forme:"Mega",formeLetter:"M",types:["Ghost","Poison"],baseStats:{hp:60,atk:65,def:80,spa:170,spd:95,spe:130},abilities:{0:"Shadow Tag"},heightm:1.4,weightkg:40.5,color:"Purple",prevo:"haunter",evoLevel:25,eggGroups:["Amorphous"]}, onix:{num:95,species:"Onix",types:["Rock","Ground"],baseStats:{hp:35,atk:45,def:160,spa:30,spd:45,spe:70},abilities:{0:"Rock Head",1:"Sturdy",H:"Weak Armor"},heightm:8.8,weightkg:210,color:"Gray",evos:["steelix"],eggGroups:["Mineral"]}, drowzee:{num:96,species:"Drowzee",types:["Psychic"],baseStats:{hp:60,atk:48,def:45,spa:43,spd:90,spe:42},abilities:{0:"Insomnia",1:"Forewarn",H:"Inner Focus"},heightm:1,weightkg:32.4,color:"Yellow",evos:["hypno"],eggGroups:["Human-Like"]}, hypno:{num:97,species:"Hypno",types:["Psychic"],baseStats:{hp:85,atk:73,def:70,spa:73,spd:115,spe:67},abilities:{0:"Insomnia",1:"Forewarn",H:"Inner Focus"},heightm:1.6,weightkg:75.6,color:"Yellow",prevo:"drowzee",evoLevel:26,eggGroups:["Human-Like"]}, krabby:{num:98,species:"Krabby",types:["Water"],baseStats:{hp:30,atk:105,def:90,spa:25,spd:25,spe:50},abilities:{0:"Hyper Cutter",1:"Shell Armor",H:"Sheer Force"},heightm:0.4,weightkg:6.5,color:"Red",evos:["kingler"],eggGroups:["Water 3"]}, kingler:{num:99,species:"Kingler",types:["Water"],baseStats:{hp:55,atk:130,def:115,spa:50,spd:50,spe:75},abilities:{0:"Hyper Cutter",1:"Shell Armor",H:"Sheer Force"},heightm:1.3,weightkg:60,color:"Red",prevo:"krabby",evoLevel:28,eggGroups:["Water 3"]}, voltorb:{num:100,species:"Voltorb",types:["Electric"],gender:"N",baseStats:{hp:40,atk:30,def:50,spa:55,spd:55,spe:100},abilities:{0:"Soundproof",1:"Static",H:"Aftermath"},heightm:0.5,weightkg:10.4,color:"Red",evos:["electrode"],eggGroups:["Mineral"]}, electrode:{num:101,species:"Electrode",types:["Electric"],gender:"N",baseStats:{hp:60,atk:50,def:70,spa:80,spd:80,spe:140},abilities:{0:"Soundproof",1:"Static",H:"Aftermath"},heightm:1.2,weightkg:66.6,color:"Red",prevo:"voltorb",evoLevel:30,eggGroups:["Mineral"]}, exeggcute:{num:102,species:"Exeggcute",types:["Grass","Psychic"],baseStats:{hp:60,atk:40,def:80,spa:60,spd:45,spe:40},abilities:{0:"Chlorophyll",H:"Harvest"},heightm:0.4,weightkg:2.5,color:"Pink",evos:["exeggutor"],eggGroups:["Grass"]}, exeggutor:{num:103,species:"Exeggutor",types:["Grass","Psychic"],baseStats:{hp:95,atk:95,def:85,spa:125,spd:65,spe:55},abilities:{0:"Chlorophyll",H:"Harvest"},heightm:2,weightkg:120,color:"Yellow",prevo:"exeggcute",evoLevel:1,eggGroups:["Grass"]}, cubone:{num:104,species:"Cubone",types:["Ground"],baseStats:{hp:50,atk:50,def:95,spa:40,spd:50,spe:35},abilities:{0:"Rock Head",1:"Lightningrod",H:"Battle Armor"},heightm:0.4,weightkg:6.5,color:"Brown",evos:["marowak"],eggGroups:["Monster"]}, marowak:{num:105,species:"Marowak",types:["Ground"],baseStats:{hp:60,atk:80,def:110,spa:50,spd:80,spe:45},abilities:{0:"Rock Head",1:"Lightningrod",H:"Battle Armor"},heightm:1,weightkg:45,color:"Brown",prevo:"cubone",evoLevel:28,eggGroups:["Monster"]}, hitmonlee:{num:106,species:"Hitmonlee",types:["Fighting"],gender:"M",baseStats:{hp:50,atk:120,def:53,spa:35,spd:110,spe:87},abilities:{0:"Limber",1:"Reckless",H:"Unburden"},heightm:1.5,weightkg:49.8,color:"Brown",prevo:"tyrogue",evoLevel:20,eggGroups:["Human-Like"]}, hitmonchan:{num:107,species:"Hitmonchan",types:["Fighting"],gender:"M",baseStats:{hp:50,atk:105,def:79,spa:35,spd:110,spe:76},abilities:{0:"Keen Eye",1:"Iron Fist",H:"Inner Focus"},heightm:1.4,weightkg:50.2,color:"Brown",prevo:"tyrogue",evoLevel:20,eggGroups:["Human-Like"]}, lickitung:{num:108,species:"Lickitung",types:["Normal"],baseStats:{hp:90,atk:55,def:75,spa:60,spd:75,spe:30},abilities:{0:"Own Tempo",1:"Oblivious",H:"Cloud Nine"},heightm:1.2,weightkg:65.5,color:"Pink",evos:["lickilicky"],eggGroups:["Monster"]}, koffing:{num:109,species:"Koffing",types:["Poison"],baseStats:{hp:40,atk:65,def:95,spa:60,spd:45,spe:35},abilities:{0:"Levitate"},heightm:0.6,weightkg:1,color:"Purple",evos:["weezing"],eggGroups:["Amorphous"]}, weezing:{num:110,species:"Weezing",types:["Poison"],baseStats:{hp:65,atk:90,def:120,spa:85,spd:70,spe:60},abilities:{0:"Levitate"},heightm:1.2,weightkg:9.5,color:"Purple",prevo:"koffing",evoLevel:35,eggGroups:["Amorphous"]}, rhyhorn:{num:111,species:"Rhyhorn",types:["Ground","Rock"],baseStats:{hp:80,atk:85,def:95,spa:30,spd:30,spe:25},abilities:{0:"Lightningrod",1:"Rock Head",H:"Reckless"},heightm:1,weightkg:115,color:"Gray",evos:["rhydon"],eggGroups:["Monster","Field"]}, rhydon:{num:112,species:"Rhydon",types:["Ground","Rock"],baseStats:{hp:105,atk:130,def:120,spa:45,spd:45,spe:40},abilities:{0:"Lightningrod",1:"Rock Head",H:"Reckless"},heightm:1.9,weightkg:120,color:"Gray",prevo:"rhyhorn",evos:["rhyperior"],evoLevel:42,eggGroups:["Monster","Field"]}, chansey:{num:113,species:"Chansey",types:["Normal"],gender:"F",baseStats:{hp:250,atk:5,def:5,spa:35,spd:105,spe:50},abilities:{0:"Natural Cure",1:"Serene Grace",H:"Healer"},heightm:1.1,weightkg:34.6,color:"Pink",prevo:"happiny",evos:["blissey"],evoLevel:1,eggGroups:["Fairy"]}, tangela:{num:114,species:"Tangela",types:["Grass"],baseStats:{hp:65,atk:55,def:115,spa:100,spd:40,spe:60},abilities:{0:"Chlorophyll",1:"Leaf Guard",H:"Regenerator"},heightm:1,weightkg:35,color:"Blue",evos:["tangrowth"],eggGroups:["Grass"]}, kangaskhan:{num:115,species:"Kangaskhan",types:["Normal"],gender:"F",baseStats:{hp:105,atk:95,def:80,spa:40,spd:80,spe:90},abilities:{0:"Early Bird",1:"Scrappy",H:"Inner Focus"},heightm:2.2,weightkg:80,color:"Brown",eggGroups:["Monster"],otherFormes:["kangaskhanmega"]}, kangaskhanmega:{num:115,species:"Kangaskhan-Mega",baseSpecies:"Kangaskhan",forme:"Mega",formeLetter:"M",types:["Normal"],gender:"F",baseStats:{hp:105,atk:125,def:100,spa:60,spd:100,spe:100},abilities:{0:"Parental Bond"},heightm:2.2,weightkg:100,color:"Brown",eggGroups:["Monster"]}, horsea:{num:116,species:"Horsea",types:["Water"],baseStats:{hp:30,atk:40,def:70,spa:70,spd:25,spe:60},abilities:{0:"Swift Swim",1:"Sniper",H:"Damp"},heightm:0.4,weightkg:8,color:"Blue",evos:["seadra"],eggGroups:["Water 1","Dragon"]}, seadra:{num:117,species:"Seadra",types:["Water"],baseStats:{hp:55,atk:65,def:95,spa:95,spd:45,spe:85},abilities:{0:"Poison Point",1:"Sniper",H:"Damp"},heightm:1.2,weightkg:25,color:"Blue",prevo:"horsea",evos:["kingdra"],evoLevel:32,eggGroups:["Water 1","Dragon"]}, goldeen:{num:118,species:"Goldeen",types:["Water"],baseStats:{hp:45,atk:67,def:60,spa:35,spd:50,spe:63},abilities:{0:"Swift Swim",1:"Water Veil",H:"Lightningrod"},heightm:0.6,weightkg:15,color:"Red",evos:["seaking"],eggGroups:["Water 2"]}, seaking:{num:119,species:"Seaking",types:["Water"],baseStats:{hp:80,atk:92,def:65,spa:65,spd:80,spe:68},abilities:{0:"Swift Swim",1:"Water Veil",H:"Lightningrod"},heightm:1.3,weightkg:39,color:"Red",prevo:"goldeen",evoLevel:33,eggGroups:["Water 2"]}, staryu:{num:120,species:"Staryu",types:["Water"],gender:"N",baseStats:{hp:30,atk:45,def:55,spa:70,spd:55,spe:85},abilities:{0:"Illuminate",1:"Natural Cure",H:"Analytic"},heightm:0.8,weightkg:34.5,color:"Brown",evos:["starmie"],eggGroups:["Water 3"]}, starmie:{num:121,species:"Starmie",types:["Water","Psychic"],gender:"N",baseStats:{hp:60,atk:75,def:85,spa:100,spd:85,spe:115},abilities:{0:"Illuminate",1:"Natural Cure",H:"Analytic"},heightm:1.1,weightkg:80,color:"Purple",prevo:"staryu",evoLevel:1,eggGroups:["Water 3"]}, mrmime:{num:122,species:"Mr. Mime",types:["Psychic","Fairy"],baseStats:{hp:40,atk:45,def:65,spa:100,spd:120,spe:90},abilities:{0:"Soundproof",1:"Filter",H:"Technician"},heightm:1.3,weightkg:54.5,color:"Pink",prevo:"mimejr",evoLevel:1,evoMove:"Mimic",eggGroups:["Human-Like"]}, scyther:{num:123,species:"Scyther",types:["Bug","Flying"],baseStats:{hp:70,atk:110,def:80,spa:55,spd:80,spe:105},abilities:{0:"Swarm",1:"Technician",H:"Steadfast"},heightm:1.5,weightkg:56,color:"Green",evos:["scizor"],eggGroups:["Bug"]}, jynx:{num:124,species:"Jynx",types:["Ice","Psychic"],gender:"F",baseStats:{hp:65,atk:50,def:35,spa:115,spd:95,spe:95},abilities:{0:"Oblivious",1:"Forewarn",H:"Dry Skin"},heightm:1.4,weightkg:40.6,color:"Red",prevo:"smoochum",evoLevel:30,eggGroups:["Human-Like"]}, electabuzz:{num:125,species:"Electabuzz",types:["Electric"],genderRatio:{M:0.75,F:0.25},baseStats:{hp:65,atk:83,def:57,spa:95,spd:85,spe:105},abilities:{0:"Static",H:"Vital Spirit"},heightm:1.1,weightkg:30,color:"Yellow",prevo:"elekid",evos:["electivire"],evoLevel:30,eggGroups:["Human-Like"]}, magmar:{num:126,species:"Magmar",types:["Fire"],genderRatio:{M:0.75,F:0.25},baseStats:{hp:65,atk:95,def:57,spa:100,spd:85,spe:93},abilities:{0:"Flame Body",H:"Vital Spirit"},heightm:1.3,weightkg:44.5,color:"Red",prevo:"magby",evos:["magmortar"],evoLevel:30,eggGroups:["Human-Like"]}, pinsir:{num:127,species:"Pinsir",types:["Bug"],baseStats:{hp:65,atk:125,def:100,spa:55,spd:70,spe:85},abilities:{0:"Hyper Cutter",1:"Mold Breaker",H:"Moxie"},heightm:1.5,weightkg:55,color:"Brown",eggGroups:["Bug"],otherFormes:["pinsirmega"]}, pinsirmega:{num:127,species:"Pinsir-Mega",baseSpecies:"Pinsir",forme:"Mega",formeLetter:"M",types:["Bug","Flying"],baseStats:{hp:65,atk:155,def:120,spa:65,spd:90,spe:105},abilities:{0:"Aerilate"},heightm:1.7,weightkg:59,color:"Brown",eggGroups:["Bug"]}, tauros:{num:128,species:"Tauros",types:["Normal"],gender:"M",baseStats:{hp:75,atk:100,def:95,spa:40,spd:70,spe:110},abilities:{0:"Intimidate",1:"Anger Point",H:"Sheer Force"},heightm:1.4,weightkg:88.4,color:"Brown",eggGroups:["Field"]}, magikarp:{num:129,species:"Magikarp",types:["Water"],baseStats:{hp:20,atk:10,def:55,spa:15,spd:20,spe:80},abilities:{0:"Swift Swim",H:"Rattled"},heightm:0.9,weightkg:10,color:"Red",evos:["gyarados"],eggGroups:["Water 2","Dragon"]}, gyarados:{num:130,species:"Gyarados",types:["Water","Flying"],baseStats:{hp:95,atk:125,def:79,spa:60,spd:100,spe:81},abilities:{0:"Intimidate",H:"Moxie"},heightm:6.5,weightkg:235,color:"Blue",prevo:"magikarp",evoLevel:20,eggGroups:["Water 2","Dragon"],otherFormes:["gyaradosmega"]}, gyaradosmega:{num:130,species:"Gyarados-Mega",baseSpecies:"Gyarados",forme:"Mega",formeLetter:"M",types:["Water","Dark"],baseStats:{hp:95,atk:155,def:109,spa:70,spd:130,spe:81},abilities:{0:"Mold Breaker"},heightm:6.5,weightkg:305,color:"Blue",prevo:"magikarp",evoLevel:20,eggGroups:["Water 2","Dragon"]}, lapras:{num:131,species:"Lapras",types:["Water","Ice"],baseStats:{hp:130,atk:85,def:80,spa:85,spd:95,spe:60},abilities:{0:"Water Absorb",1:"Shell Armor",H:"Hydration"},heightm:2.5,weightkg:220,color:"Blue",eggGroups:["Monster","Water 1"]}, ditto:{num:132,species:"Ditto",types:["Normal"],gender:"N",baseStats:{hp:48,atk:48,def:48,spa:48,spd:48,spe:48},abilities:{0:"Limber",H:"Imposter"},heightm:0.3,weightkg:4,color:"Purple",eggGroups:["Ditto"]}, eevee:{num:133,species:"Eevee",types:["Normal"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:55,atk:55,def:50,spa:45,spd:65,spe:55},abilities:{0:"Run Away",1:"Adaptability",H:"Anticipation"},heightm:0.3,weightkg:6.5,color:"Brown",evos:["vaporeon","jolteon","flareon","espeon","umbreon","leafeon","glaceon","sylveon"],eggGroups:["Field"]}, vaporeon:{num:134,species:"Vaporeon",types:["Water"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:130,atk:65,def:60,spa:110,spd:95,spe:65},abilities:{0:"Water Absorb",H:"Hydration"},heightm:1,weightkg:29,color:"Blue",prevo:"eevee",evoLevel:1,eggGroups:["Field"]}, jolteon:{num:135,species:"Jolteon",types:["Electric"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:65,atk:65,def:60,spa:110,spd:95,spe:130},abilities:{0:"Volt Absorb",H:"Quick Feet"},heightm:0.8,weightkg:24.5,color:"Yellow",prevo:"eevee",evoLevel:1,eggGroups:["Field"]}, flareon:{num:136,species:"Flareon",types:["Fire"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:65,atk:130,def:60,spa:95,spd:110,spe:65},abilities:{0:"Flash Fire",H:"Guts"},heightm:0.9,weightkg:25,color:"Red",prevo:"eevee",evoLevel:1,eggGroups:["Field"]}, porygon:{num:137,species:"Porygon",types:["Normal"],gender:"N",baseStats:{hp:65,atk:60,def:70,spa:85,spd:75,spe:40},abilities:{0:"Trace",1:"Download",H:"Analytic"},heightm:0.8,weightkg:36.5,color:"Pink",evos:["porygon2"],eggGroups:["Mineral"]}, omanyte:{num:138,species:"Omanyte",types:["Rock","Water"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:35,atk:40,def:100,spa:90,spd:55,spe:35},abilities:{0:"Swift Swim",1:"Shell Armor",H:"Weak Armor"},heightm:0.4,weightkg:7.5,color:"Blue",evos:["omastar"],eggGroups:["Water 1","Water 3"]}, omastar:{num:139,species:"Omastar",types:["Rock","Water"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:70,atk:60,def:125,spa:115,spd:70,spe:55},abilities:{0:"Swift Swim",1:"Shell Armor",H:"Weak Armor"},heightm:1,weightkg:35,color:"Blue",prevo:"omanyte",evoLevel:40,eggGroups:["Water 1","Water 3"]}, kabuto:{num:140,species:"Kabuto",types:["Rock","Water"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:30,atk:80,def:90,spa:55,spd:45,spe:55},abilities:{0:"Swift Swim",1:"Battle Armor",H:"Weak Armor"},heightm:0.5,weightkg:11.5,color:"Brown",evos:["kabutops"],eggGroups:["Water 1","Water 3"]}, kabutops:{num:141,species:"Kabutops",types:["Rock","Water"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:60,atk:115,def:105,spa:65,spd:70,spe:80},abilities:{0:"Swift Swim",1:"Battle Armor",H:"Weak Armor"},heightm:1.3,weightkg:40.5,color:"Brown",prevo:"kabuto",evoLevel:40,eggGroups:["Water 1","Water 3"]}, aerodactyl:{num:142,species:"Aerodactyl",types:["Rock","Flying"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:80,atk:105,def:65,spa:60,spd:75,spe:130},abilities:{0:"Rock Head",1:"Pressure",H:"Unnerve"},heightm:1.8,weightkg:59,color:"Purple",eggGroups:["Flying"],otherFormes:["aerodactylmega"]}, aerodactylmega:{num:142,species:"Aerodactyl-Mega",baseSpecies:"Aerodactyl",forme:"Mega",formeLetter:"M",types:["Rock","Flying"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:80,atk:135,def:85,spa:70,spd:95,spe:150},abilities:{0:"Tough Claws"},heightm:2.1,weightkg:79,color:"Purple",eggGroups:["Flying"]}, snorlax:{num:143,species:"Snorlax",types:["Normal"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:160,atk:110,def:65,spa:65,spd:110,spe:30},abilities:{0:"Immunity",1:"Thick Fat",H:"Gluttony"},heightm:2.1,weightkg:460,color:"Black",prevo:"munchlax",evoLevel:1,eggGroups:["Monster"]}, articuno:{num:144,species:"Articuno",types:["Ice","Flying"],gender:"N",baseStats:{hp:90,atk:85,def:100,spa:95,spd:125,spe:85},abilities:{0:"Pressure",H:"Snow Cloak"},heightm:1.7,weightkg:55.4,color:"Blue",eggGroups:["Undiscovered"]}, zapdos:{num:145,species:"Zapdos",types:["Electric","Flying"],gender:"N",baseStats:{hp:90,atk:90,def:85,spa:125,spd:90,spe:100},abilities:{0:"Pressure",H:"Static"},heightm:1.6,weightkg:52.6,color:"Yellow",eggGroups:["Undiscovered"]}, moltres:{num:146,species:"Moltres",types:["Fire","Flying"],gender:"N",baseStats:{hp:90,atk:100,def:90,spa:125,spd:85,spe:90},abilities:{0:"Pressure",H:"Flame Body"},heightm:2,weightkg:60,color:"Yellow",eggGroups:["Undiscovered"]}, dratini:{num:147,species:"Dratini",types:["Dragon"],baseStats:{hp:41,atk:64,def:45,spa:50,spd:50,spe:50},abilities:{0:"Shed Skin",H:"Marvel Scale"},heightm:1.8,weightkg:3.3,color:"Blue",evos:["dragonair"],eggGroups:["Water 1","Dragon"]}, dragonair:{num:148,species:"Dragonair",types:["Dragon"],baseStats:{hp:61,atk:84,def:65,spa:70,spd:70,spe:70},abilities:{0:"Shed Skin",H:"Marvel Scale"},heightm:4,weightkg:16.5,color:"Blue",prevo:"dratini",evos:["dragonite"],evoLevel:30,eggGroups:["Water 1","Dragon"]}, dragonite:{num:149,species:"Dragonite",types:["Dragon","Flying"],baseStats:{hp:91,atk:134,def:95,spa:100,spd:100,spe:80},abilities:{0:"Inner Focus",H:"Multiscale"},heightm:2.2,weightkg:210,color:"Brown",prevo:"dragonair",evoLevel:55,eggGroups:["Water 1","Dragon"]}, mewtwo:{num:150,species:"Mewtwo",types:["Psychic"],gender:"N",baseStats:{hp:106,atk:110,def:90,spa:154,spd:90,spe:130},abilities:{0:"Pressure",H:"Unnerve"},heightm:2,weightkg:122,color:"Purple",eggGroups:["Undiscovered"],otherFormes:["mewtwomegax","mewtwomegay"]}, mewtwomegax:{num:150,species:"Mewtwo-Mega-X",baseSpecies:"Mewtwo",forme:"Mega-X",formeLetter:"M",types:["Psychic","Fighting"],gender:"N",baseStats:{hp:106,atk:190,def:100,spa:154,spd:100,spe:130},abilities:{0:"Steadfast"},heightm:2.3,weightkg:127,color:"Purple",eggGroups:["Undiscovered"]}, mewtwomegay:{num:150,species:"Mewtwo-Mega-Y",baseSpecies:"Mewtwo",forme:"Mega-Y",formeLetter:"M",types:["Psychic"],gender:"N",baseStats:{hp:106,atk:150,def:70,spa:194,spd:120,spe:140},abilities:{0:"Insomnia"},heightm:1.5,weightkg:33,color:"Purple",eggGroups:["Undiscovered"]}, mew:{num:151,species:"Mew",types:["Psychic"],gender:"N",baseStats:{hp:100,atk:100,def:100,spa:100,spd:100,spe:100},abilities:{0:"Synchronize"},heightm:0.4,weightkg:4,color:"Pink",eggGroups:["Undiscovered"]}, chikorita:{num:152,species:"Chikorita",types:["Grass"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:45,atk:49,def:65,spa:49,spd:65,spe:45},abilities:{0:"Overgrow",H:"Leaf Guard"},heightm:0.9,weightkg:6.4,color:"Green",evos:["bayleef"],eggGroups:["Monster","Grass"]}, bayleef:{num:153,species:"Bayleef",types:["Grass"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:60,atk:62,def:80,spa:63,spd:80,spe:60},abilities:{0:"Overgrow",H:"Leaf Guard"},heightm:1.2,weightkg:15.8,color:"Green",prevo:"chikorita",evos:["meganium"],evoLevel:16,eggGroups:["Monster","Grass"]}, meganium:{num:154,species:"Meganium",types:["Grass"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:80,atk:82,def:100,spa:83,spd:100,spe:80},abilities:{0:"Overgrow",H:"Leaf Guard"},heightm:1.8,weightkg:100.5,color:"Green",prevo:"bayleef",evoLevel:32,eggGroups:["Monster","Grass"]}, cyndaquil:{num:155,species:"Cyndaquil",types:["Fire"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:39,atk:52,def:43,spa:60,spd:50,spe:65},abilities:{0:"Blaze",H:"Flash Fire"},heightm:0.5,weightkg:7.9,color:"Yellow",evos:["quilava"],eggGroups:["Field"]}, quilava:{num:156,species:"Quilava",types:["Fire"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:58,atk:64,def:58,spa:80,spd:65,spe:80},abilities:{0:"Blaze",H:"Flash Fire"},heightm:0.9,weightkg:19,color:"Yellow",prevo:"cyndaquil",evos:["typhlosion"],evoLevel:14,eggGroups:["Field"]}, typhlosion:{num:157,species:"Typhlosion",types:["Fire"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:78,atk:84,def:78,spa:109,spd:85,spe:100},abilities:{0:"Blaze",H:"Flash Fire"},heightm:1.7,weightkg:79.5,color:"Yellow",prevo:"quilava",evoLevel:36,eggGroups:["Field"]}, totodile:{num:158,species:"Totodile",types:["Water"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:50,atk:65,def:64,spa:44,spd:48,spe:43},abilities:{0:"Torrent",H:"Sheer Force"},heightm:0.6,weightkg:9.5,color:"Blue",evos:["croconaw"],eggGroups:["Monster","Water 1"]}, croconaw:{num:159,species:"Croconaw",types:["Water"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:65,atk:80,def:80,spa:59,spd:63,spe:58},abilities:{0:"Torrent",H:"Sheer Force"},heightm:1.1,weightkg:25,color:"Blue",prevo:"totodile",evos:["feraligatr"],evoLevel:18,eggGroups:["Monster","Water 1"]}, feraligatr:{num:160,species:"Feraligatr",types:["Water"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:85,atk:105,def:100,spa:79,spd:83,spe:78},abilities:{0:"Torrent",H:"Sheer Force"},heightm:2.3,weightkg:88.8,color:"Blue",prevo:"croconaw",evoLevel:30,eggGroups:["Monster","Water 1"]}, sentret:{num:161,species:"Sentret",types:["Normal"],baseStats:{hp:35,atk:46,def:34,spa:35,spd:45,spe:20},abilities:{0:"Run Away",1:"Keen Eye",H:"Frisk"},heightm:0.8,weightkg:6,color:"Brown",evos:["furret"],eggGroups:["Field"]}, furret:{num:162,species:"Furret",types:["Normal"],baseStats:{hp:85,atk:76,def:64,spa:45,spd:55,spe:90},abilities:{0:"Run Away",1:"Keen Eye",H:"Frisk"},heightm:1.8,weightkg:32.5,color:"Brown",prevo:"sentret",evoLevel:15,eggGroups:["Field"]}, hoothoot:{num:163,species:"Hoothoot",types:["Normal","Flying"],baseStats:{hp:60,atk:30,def:30,spa:36,spd:56,spe:50},abilities:{0:"Insomnia",1:"Keen Eye",H:"Tinted Lens"},heightm:0.7,weightkg:21.2,color:"Brown",evos:["noctowl"],eggGroups:["Flying"]}, noctowl:{num:164,species:"Noctowl",types:["Normal","Flying"],baseStats:{hp:100,atk:50,def:50,spa:76,spd:96,spe:70},abilities:{0:"Insomnia",1:"Keen Eye",H:"Tinted Lens"},heightm:1.6,weightkg:40.8,color:"Brown",prevo:"hoothoot",evoLevel:20,eggGroups:["Flying"]}, ledyba:{num:165,species:"Ledyba",types:["Bug","Flying"],baseStats:{hp:40,atk:20,def:30,spa:40,spd:80,spe:55},abilities:{0:"Swarm",1:"Early Bird",H:"Rattled"},heightm:1,weightkg:10.8,color:"Red",evos:["ledian"],eggGroups:["Bug"]}, ledian:{num:166,species:"Ledian",types:["Bug","Flying"],baseStats:{hp:55,atk:35,def:50,spa:55,spd:110,spe:85},abilities:{0:"Swarm",1:"Early Bird",H:"Iron Fist"},heightm:1.4,weightkg:35.6,color:"Red",prevo:"ledyba",evoLevel:18,eggGroups:["Bug"]}, spinarak:{num:167,species:"Spinarak",types:["Bug","Poison"],baseStats:{hp:40,atk:60,def:40,spa:40,spd:40,spe:30},abilities:{0:"Swarm",1:"Insomnia",H:"Sniper"},heightm:0.5,weightkg:8.5,color:"Green",evos:["ariados"],eggGroups:["Bug"]}, ariados:{num:168,species:"Ariados",types:["Bug","Poison"],baseStats:{hp:70,atk:90,def:70,spa:60,spd:60,spe:40},abilities:{0:"Swarm",1:"Insomnia",H:"Sniper"},heightm:1.1,weightkg:33.5,color:"Red",prevo:"spinarak",evoLevel:22,eggGroups:["Bug"]}, crobat:{num:169,species:"Crobat",types:["Poison","Flying"],baseStats:{hp:85,atk:90,def:80,spa:70,spd:80,spe:130},abilities:{0:"Inner Focus",H:"Infiltrator"},heightm:1.8,weightkg:75,color:"Purple",prevo:"golbat",evoLevel:23,eggGroups:["Flying"]}, chinchou:{num:170,species:"Chinchou",types:["Water","Electric"],baseStats:{hp:75,atk:38,def:38,spa:56,spd:56,spe:67},abilities:{0:"Volt Absorb",1:"Illuminate",H:"Water Absorb"},heightm:0.5,weightkg:12,color:"Blue",evos:["lanturn"],eggGroups:["Water 2"]}, lanturn:{num:171,species:"Lanturn",types:["Water","Electric"],baseStats:{hp:125,atk:58,def:58,spa:76,spd:76,spe:67},abilities:{0:"Volt Absorb",1:"Illuminate",H:"Water Absorb"},heightm:1.2,weightkg:22.5,color:"Blue",prevo:"chinchou",evoLevel:27,eggGroups:["Water 2"]}, pichu:{num:172,species:"Pichu",types:["Electric"],baseStats:{hp:20,atk:40,def:15,spa:35,spd:35,spe:60},abilities:{0:"Static",H:"Lightningrod"},heightm:0.3,weightkg:2,color:"Yellow",evos:["pikachu"],eggGroups:["Undiscovered"],otherFormes:["pichuspikyeared"]}, pichuspikyeared:{num:172,species:"Pichu-Spiky-eared",baseSpecies:"Pichu",forme:"Spiky-eared",formeLetter:"S",types:["Electric"],gender:"F",baseStats:{hp:20,atk:40,def:15,spa:35,spd:35,spe:60},abilities:{0:"Static"},heightm:0.3,weightkg:2,color:"Yellow",eggGroups:["Undiscovered"]}, cleffa:{num:173,species:"Cleffa",types:["Fairy"],genderRatio:{M:0.25,F:0.75},baseStats:{hp:50,atk:25,def:28,spa:45,spd:55,spe:15},abilities:{0:"Cute Charm",1:"Magic Guard",H:"Friend Guard"},heightm:0.3,weightkg:3,color:"Pink",evos:["clefairy"],eggGroups:["Undiscovered"]}, igglybuff:{num:174,species:"Igglybuff",types:["Normal","Fairy"],genderRatio:{M:0.25,F:0.75},baseStats:{hp:90,atk:30,def:15,spa:40,spd:20,spe:15},abilities:{0:"Cute Charm",1:"Competitive",H:"Friend Guard"},heightm:0.3,weightkg:1,color:"Pink",evos:["jigglypuff"],eggGroups:["Undiscovered"]}, togepi:{num:175,species:"Togepi",types:["Fairy"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:35,atk:20,def:65,spa:40,spd:65,spe:20},abilities:{0:"Hustle",1:"Serene Grace",H:"Super Luck"},heightm:0.3,weightkg:1.5,color:"White",evos:["togetic"],eggGroups:["Undiscovered"]}, togetic:{num:176,species:"Togetic",types:["Fairy","Flying"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:55,atk:40,def:85,spa:80,spd:105,spe:40},abilities:{0:"Hustle",1:"Serene Grace",H:"Super Luck"},heightm:0.6,weightkg:3.2,color:"White",prevo:"togepi",evos:["togekiss"],evoLevel:2,eggGroups:["Flying","Fairy"]}, natu:{num:177,species:"Natu",types:["Psychic","Flying"],baseStats:{hp:40,atk:50,def:45,spa:70,spd:45,spe:70},abilities:{0:"Synchronize",1:"Early Bird",H:"Magic Bounce"},heightm:0.2,weightkg:2,color:"Green",evos:["xatu"],eggGroups:["Flying"]}, xatu:{num:178,species:"Xatu",types:["Psychic","Flying"],baseStats:{hp:65,atk:75,def:70,spa:95,spd:70,spe:95},abilities:{0:"Synchronize",1:"Early Bird",H:"Magic Bounce"},heightm:1.5,weightkg:15,color:"Green",prevo:"natu",evoLevel:25,eggGroups:["Flying"]}, mareep:{num:179,species:"Mareep",types:["Electric"],baseStats:{hp:55,atk:40,def:40,spa:65,spd:45,spe:35},abilities:{0:"Static",H:"Plus"},heightm:0.6,weightkg:7.8,color:"White",evos:["flaaffy"],eggGroups:["Monster","Field"]}, flaaffy:{num:180,species:"Flaaffy",types:["Electric"],baseStats:{hp:70,atk:55,def:55,spa:80,spd:60,spe:45},abilities:{0:"Static",H:"Plus"},heightm:0.8,weightkg:13.3,color:"Pink",prevo:"mareep",evos:["ampharos"],evoLevel:15,eggGroups:["Monster","Field"]}, ampharos:{num:181,species:"Ampharos",types:["Electric"],baseStats:{hp:90,atk:75,def:85,spa:115,spd:90,spe:55},abilities:{0:"Static",H:"Plus"},heightm:1.4,weightkg:61.5,color:"Yellow",prevo:"flaaffy",evoLevel:30,eggGroups:["Monster","Field"],otherFormes:["ampharosmega"]}, ampharosmega:{num:181,species:"Ampharos-Mega",baseSpecies:"Ampharos",forme:"Mega",formeLetter:"M",types:["Electric","Dragon"],baseStats:{hp:90,atk:95,def:105,spa:165,spd:110,spe:45},abilities:{0:"Mold Breaker"},heightm:1.4,weightkg:61.5,color:"Yellow",prevo:"flaaffy",evoLevel:30,eggGroups:["Monster","Field"]}, bellossom:{num:182,species:"Bellossom",types:["Grass"],baseStats:{hp:75,atk:80,def:95,spa:90,spd:100,spe:50},abilities:{0:"Chlorophyll",H:"Healer"},heightm:0.4,weightkg:5.8,color:"Green",prevo:"gloom",evoLevel:21,eggGroups:["Grass"]}, marill:{num:183,species:"Marill",types:["Water","Fairy"],baseStats:{hp:70,atk:20,def:50,spa:20,spd:50,spe:40},abilities:{0:"Thick Fat",1:"Huge Power",H:"Sap Sipper"},heightm:0.4,weightkg:8.5,color:"Blue",prevo:"azurill",evos:["azumarill"],evoLevel:1,eggGroups:["Water 1","Fairy"]}, azumarill:{num:184,species:"Azumarill",types:["Water","Fairy"],baseStats:{hp:100,atk:50,def:80,spa:60,spd:80,spe:50},abilities:{0:"Thick Fat",1:"Huge Power",H:"Sap Sipper"},heightm:0.8,weightkg:28.5,color:"Blue",prevo:"marill",evoLevel:18,eggGroups:["Water 1","Fairy"]}, sudowoodo:{num:185,species:"Sudowoodo",types:["Rock"],baseStats:{hp:70,atk:100,def:115,spa:30,spd:65,spe:30},abilities:{0:"Sturdy",1:"Rock Head",H:"Rattled"},heightm:1.2,weightkg:38,color:"Brown",prevo:"bonsly",evoLevel:1,evoMove:"Mimic",eggGroups:["Mineral"]}, politoed:{num:186,species:"Politoed",types:["Water"],baseStats:{hp:90,atk:75,def:75,spa:90,spd:100,spe:70},abilities:{0:"Water Absorb",1:"Damp",H:"Drizzle"},heightm:1.1,weightkg:33.9,color:"Green",prevo:"poliwhirl",evoLevel:25,eggGroups:["Water 1"]}, hoppip:{num:187,species:"Hoppip",types:["Grass","Flying"],baseStats:{hp:35,atk:35,def:40,spa:35,spd:55,spe:50},abilities:{0:"Chlorophyll",1:"Leaf Guard",H:"Infiltrator"},heightm:0.4,weightkg:0.5,color:"Pink",evos:["skiploom"],eggGroups:["Fairy","Grass"]}, skiploom:{num:188,species:"Skiploom",types:["Grass","Flying"],baseStats:{hp:55,atk:45,def:50,spa:45,spd:65,spe:80},abilities:{0:"Chlorophyll",1:"Leaf Guard",H:"Infiltrator"},heightm:0.6,weightkg:1,color:"Green",prevo:"hoppip",evos:["jumpluff"],evoLevel:18,eggGroups:["Fairy","Grass"]}, jumpluff:{num:189,species:"Jumpluff",types:["Grass","Flying"],baseStats:{hp:75,atk:55,def:70,spa:55,spd:95,spe:110},abilities:{0:"Chlorophyll",1:"Leaf Guard",H:"Infiltrator"},heightm:0.8,weightkg:3,color:"Blue",prevo:"skiploom",evoLevel:27,eggGroups:["Fairy","Grass"]}, aipom:{num:190,species:"Aipom",types:["Normal"],baseStats:{hp:55,atk:70,def:55,spa:40,spd:55,spe:85},abilities:{0:"Run Away",1:"Pickup",H:"Skill Link"},heightm:0.8,weightkg:11.5,color:"Purple",evos:["ambipom"],eggGroups:["Field"]}, sunkern:{num:191,species:"Sunkern",types:["Grass"],baseStats:{hp:30,atk:30,def:30,spa:30,spd:30,spe:30},abilities:{0:"Chlorophyll",1:"Solar Power",H:"Early Bird"},heightm:0.3,weightkg:1.8,color:"Yellow",evos:["sunflora"],eggGroups:["Grass"]}, sunflora:{num:192,species:"Sunflora",types:["Grass"],baseStats:{hp:75,atk:75,def:55,spa:105,spd:85,spe:30},abilities:{0:"Chlorophyll",1:"Solar Power",H:"Early Bird"},heightm:0.8,weightkg:8.5,color:"Yellow",prevo:"sunkern",evoLevel:1,eggGroups:["Grass"]}, yanma:{num:193,species:"Yanma",types:["Bug","Flying"],baseStats:{hp:65,atk:65,def:45,spa:75,spd:45,spe:95},abilities:{0:"Speed Boost",1:"Compound Eyes",H:"Frisk"},heightm:1.2,weightkg:38,color:"Red",evos:["yanmega"],eggGroups:["Bug"]}, wooper:{num:194,species:"Wooper",types:["Water","Ground"],baseStats:{hp:55,atk:45,def:45,spa:25,spd:25,spe:15},abilities:{0:"Damp",1:"Water Absorb",H:"Unaware"},heightm:0.4,weightkg:8.5,color:"Blue",evos:["quagsire"],eggGroups:["Water 1","Field"]}, quagsire:{num:195,species:"Quagsire",types:["Water","Ground"],baseStats:{hp:95,atk:85,def:85,spa:65,spd:65,spe:35},abilities:{0:"Damp",1:"Water Absorb",H:"Unaware"},heightm:1.4,weightkg:75,color:"Blue",prevo:"wooper",evoLevel:20,eggGroups:["Water 1","Field"]}, espeon:{num:196,species:"Espeon",types:["Psychic"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:65,atk:65,def:60,spa:130,spd:95,spe:110},abilities:{0:"Synchronize",H:"Magic Bounce"},heightm:0.9,weightkg:26.5,color:"Purple",prevo:"eevee",evoLevel:2,eggGroups:["Field"]}, umbreon:{num:197,species:"Umbreon",types:["Dark"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:95,atk:65,def:110,spa:60,spd:130,spe:65},abilities:{0:"Synchronize",H:"Inner Focus"},heightm:1,weightkg:27,color:"Black",prevo:"eevee",evoLevel:2,eggGroups:["Field"]}, murkrow:{num:198,species:"Murkrow",types:["Dark","Flying"],baseStats:{hp:60,atk:85,def:42,spa:85,spd:42,spe:91},abilities:{0:"Insomnia",1:"Super Luck",H:"Prankster"},heightm:0.5,weightkg:2.1,color:"Black",evos:["honchkrow"],eggGroups:["Flying"]}, slowking:{num:199,species:"Slowking",types:["Water","Psychic"],baseStats:{hp:95,atk:75,def:80,spa:100,spd:110,spe:30},abilities:{0:"Oblivious",1:"Own Tempo",H:"Regenerator"},heightm:2,weightkg:79.5,color:"Pink",prevo:"slowpoke",evoLevel:1,eggGroups:["Monster","Water 1"]}, misdreavus:{num:200,species:"Misdreavus",types:["Ghost"],baseStats:{hp:60,atk:60,def:60,spa:85,spd:85,spe:85},abilities:{0:"Levitate"},heightm:0.7,weightkg:1,color:"Gray",evos:["mismagius"],eggGroups:["Amorphous"]}, unown:{num:201,species:"Unown",baseForme:"A",types:["Psychic"],gender:"N",baseStats:{hp:48,atk:72,def:48,spa:72,spd:48,spe:48},abilities:{0:"Levitate"},heightm:0.5,weightkg:5,color:"Black",eggGroups:["Undiscovered"],otherForms:["unownb","unownc","unownd","unowne","unownf","unowng","unownh","unowni","unownj","unownk","unownl","unownm","unownn","unowno","unownp","unownq","unownr","unowns","unownt","unownu","unownv","unownw","unownx","unowny","unownz","unownem","unownqm"]}, wobbuffet:{num:202,species:"Wobbuffet",types:["Psychic"],baseStats:{hp:190,atk:33,def:58,spa:33,spd:58,spe:33},abilities:{0:"Shadow Tag",H:"Telepathy"},heightm:1.3,weightkg:28.5,color:"Blue",prevo:"wynaut",evoLevel:15,eggGroups:["Amorphous"]}, girafarig:{num:203,species:"Girafarig",types:["Normal","Psychic"],baseStats:{hp:70,atk:80,def:65,spa:90,spd:65,spe:85},abilities:{0:"Inner Focus",1:"Early Bird",H:"Sap Sipper"},heightm:1.5,weightkg:41.5,color:"Yellow",eggGroups:["Field"]}, pineco:{num:204,species:"Pineco",types:["Bug"],baseStats:{hp:50,atk:65,def:90,spa:35,spd:35,spe:15},abilities:{0:"Sturdy",H:"Overcoat"},heightm:0.6,weightkg:7.2,color:"Gray",evos:["forretress"],eggGroups:["Bug"]}, forretress:{num:205,species:"Forretress",types:["Bug","Steel"],baseStats:{hp:75,atk:90,def:140,spa:60,spd:60,spe:40},abilities:{0:"Sturdy",H:"Overcoat"},heightm:1.2,weightkg:125.8,color:"Purple",prevo:"pineco",evoLevel:31,eggGroups:["Bug"]}, dunsparce:{num:206,species:"Dunsparce",types:["Normal"],baseStats:{hp:100,atk:70,def:70,spa:65,spd:65,spe:45},abilities:{0:"Serene Grace",1:"Run Away",H:"Rattled"},heightm:1.5,weightkg:14,color:"Yellow",eggGroups:["Field"]}, gligar:{num:207,species:"Gligar",types:["Ground","Flying"],baseStats:{hp:65,atk:75,def:105,spa:35,spd:65,spe:85},abilities:{0:"Hyper Cutter",1:"Sand Veil",H:"Immunity"},heightm:1.1,weightkg:64.8,color:"Purple",evos:["gliscor"],eggGroups:["Bug"]}, steelix:{num:208,species:"Steelix",types:["Steel","Ground"],baseStats:{hp:75,atk:85,def:200,spa:55,spd:65,spe:30},abilities:{0:"Rock Head",1:"Sturdy",H:"Sheer Force"},heightm:9.2,weightkg:400,color:"Gray",prevo:"onix",evoLevel:1,eggGroups:["Mineral"]}, snubbull:{num:209,species:"Snubbull",types:["Fairy"],genderRatio:{M:0.25,F:0.75},baseStats:{hp:60,atk:80,def:50,spa:40,spd:40,spe:30},abilities:{0:"Intimidate",1:"Run Away",H:"Rattled"},heightm:0.6,weightkg:7.8,color:"Pink",evos:["granbull"],eggGroups:["Field","Fairy"]}, granbull:{num:210,species:"Granbull",types:["Fairy"],genderRatio:{M:0.25,F:0.75},baseStats:{hp:90,atk:120,def:75,spa:60,spd:60,spe:45},abilities:{0:"Intimidate",1:"Quick Feet",H:"Rattled"},heightm:1.4,weightkg:48.7,color:"Purple",prevo:"snubbull",evoLevel:23,eggGroups:["Field","Fairy"]}, qwilfish:{num:211,species:"Qwilfish",types:["Water","Poison"],baseStats:{hp:65,atk:95,def:75,spa:55,spd:55,spe:85},abilities:{0:"Poison Point",1:"Swift Swim",H:"Intimidate"},heightm:0.5,weightkg:3.9,color:"Gray",eggGroups:["Water 2"]}, scizor:{num:212,species:"Scizor",types:["Bug","Steel"],baseStats:{hp:70,atk:130,def:100,spa:55,spd:80,spe:65},abilities:{0:"Swarm",1:"Technician",H:"Light Metal"},heightm:1.8,weightkg:118,color:"Red",prevo:"scyther",evoLevel:1,eggGroups:["Bug"],otherFormes:["scizormega"]}, scizormega:{num:212,species:"Scizor-Mega",baseSpecies:"Scizor",forme:"Mega",formeLetter:"M",types:["Bug","Steel"],baseStats:{hp:70,atk:150,def:140,spa:65,spd:100,spe:75},abilities:{0:"Technician"},heightm:2,weightkg:125,color:"Red",prevo:"scyther",evoLevel:1,eggGroups:["Bug"]}, shuckle:{num:213,species:"Shuckle",types:["Bug","Rock"],baseStats:{hp:20,atk:10,def:230,spa:10,spd:230,spe:5},abilities:{0:"Sturdy",1:"Gluttony",H:"Contrary"},heightm:0.6,weightkg:20.5,color:"Yellow",eggGroups:["Bug"]}, heracross:{num:214,species:"Heracross",types:["Bug","Fighting"],baseStats:{hp:80,atk:125,def:75,spa:40,spd:95,spe:85},abilities:{0:"Swarm",1:"Guts",H:"Moxie"},heightm:1.5,weightkg:54,color:"Blue",eggGroups:["Bug"],otherFormes:["heracrossmega"]}, heracrossmega:{num:214,species:"Heracross-Mega",baseSpecies:"Heracross",forme:"Mega",formeLetter:"M",types:["Bug","Fighting"],baseStats:{hp:80,atk:185,def:115,spa:40,spd:105,spe:75},abilities:{0:"Skill Link"},heightm:1.7,weightkg:62.5,color:"Blue",eggGroups:["Bug"]}, sneasel:{num:215,species:"Sneasel",types:["Dark","Ice"],baseStats:{hp:55,atk:95,def:55,spa:35,spd:75,spe:115},abilities:{0:"Inner Focus",1:"Keen Eye",H:"Pickpocket"},heightm:0.9,weightkg:28,color:"Black",evos:["weavile"],eggGroups:["Field"]}, teddiursa:{num:216,species:"Teddiursa",types:["Normal"],baseStats:{hp:60,atk:80,def:50,spa:50,spd:50,spe:40},abilities:{0:"Pickup",1:"Quick Feet",H:"Honey Gather"},heightm:0.6,weightkg:8.8,color:"Brown",evos:["ursaring"],eggGroups:["Field"]}, ursaring:{num:217,species:"Ursaring",types:["Normal"],baseStats:{hp:90,atk:130,def:75,spa:75,spd:75,spe:55},abilities:{0:"Guts",1:"Quick Feet",H:"Unnerve"},heightm:1.8,weightkg:125.8,color:"Brown",prevo:"teddiursa",evoLevel:30,eggGroups:["Field"]}, slugma:{num:218,species:"Slugma",types:["Fire"],baseStats:{hp:40,atk:40,def:40,spa:70,spd:40,spe:20},abilities:{0:"Magma Armor",1:"Flame Body",H:"Weak Armor"},heightm:0.7,weightkg:35,color:"Red",evos:["magcargo"],eggGroups:["Amorphous"]}, magcargo:{num:219,species:"Magcargo",types:["Fire","Rock"],baseStats:{hp:50,atk:50,def:120,spa:80,spd:80,spe:30},abilities:{0:"Magma Armor",1:"Flame Body",H:"Weak Armor"},heightm:0.8,weightkg:55,color:"Red",prevo:"slugma",evoLevel:38,eggGroups:["Amorphous"]}, swinub:{num:220,species:"Swinub",types:["Ice","Ground"],baseStats:{hp:50,atk:50,def:40,spa:30,spd:30,spe:50},abilities:{0:"Oblivious",1:"Snow Cloak",H:"Thick Fat"},heightm:0.4,weightkg:6.5,color:"Brown",evos:["piloswine"],eggGroups:["Field"]}, piloswine:{num:221,species:"Piloswine",types:["Ice","Ground"],baseStats:{hp:100,atk:100,def:80,spa:60,spd:60,spe:50},abilities:{0:"Oblivious",1:"Snow Cloak",H:"Thick Fat"},heightm:1.1,weightkg:55.8,color:"Brown",prevo:"swinub",evos:["mamoswine"],evoLevel:33,eggGroups:["Field"]}, corsola:{num:222,species:"Corsola",types:["Water","Rock"],genderRatio:{M:0.25,F:0.75},baseStats:{hp:55,atk:55,def:85,spa:65,spd:85,spe:35},abilities:{0:"Hustle",1:"Natural Cure",H:"Regenerator"},heightm:0.6,weightkg:5,color:"Pink",eggGroups:["Water 1","Water 3"]}, remoraid:{num:223,species:"Remoraid",types:["Water"],baseStats:{hp:35,atk:65,def:35,spa:65,spd:35,spe:65},abilities:{0:"Hustle",1:"Sniper",H:"Moody"},heightm:0.6,weightkg:12,color:"Gray",evos:["octillery"],eggGroups:["Water 1","Water 2"]}, octillery:{num:224,species:"Octillery",types:["Water"],baseStats:{hp:75,atk:105,def:75,spa:105,spd:75,spe:45},abilities:{0:"Suction Cups",1:"Sniper",H:"Moody"},heightm:0.9,weightkg:28.5,color:"Red",prevo:"remoraid",evoLevel:25,eggGroups:["Water 1","Water 2"]}, delibird:{num:225,species:"Delibird",types:["Ice","Flying"],baseStats:{hp:45,atk:55,def:45,spa:65,spd:45,spe:75},abilities:{0:"Vital Spirit",1:"Hustle",H:"Insomnia"},heightm:0.9,weightkg:16,color:"Red",eggGroups:["Water 1","Field"]}, mantine:{num:226,species:"Mantine",types:["Water","Flying"],baseStats:{hp:65,atk:40,def:70,spa:80,spd:140,spe:70},abilities:{0:"Swift Swim",1:"Water Absorb",H:"Water Veil"},heightm:2.1,weightkg:220,color:"Purple",prevo:"mantyke",evoLevel:1,eggGroups:["Water 1"]}, skarmory:{num:227,species:"Skarmory",types:["Steel","Flying"],baseStats:{hp:65,atk:80,def:140,spa:40,spd:70,spe:70},abilities:{0:"Keen Eye",1:"Sturdy",H:"Weak Armor"},heightm:1.7,weightkg:50.5,color:"Gray",eggGroups:["Flying"]}, houndour:{num:228,species:"Houndour",types:["Dark","Fire"],baseStats:{hp:45,atk:60,def:30,spa:80,spd:50,spe:65},abilities:{0:"Early Bird",1:"Flash Fire",H:"Unnerve"},heightm:0.6,weightkg:10.8,color:"Black",evos:["houndoom"],eggGroups:["Field"]}, houndoom:{num:229,species:"Houndoom",types:["Dark","Fire"],baseStats:{hp:75,atk:90,def:50,spa:110,spd:80,spe:95},abilities:{0:"Early Bird",1:"Flash Fire",H:"Unnerve"},heightm:1.4,weightkg:35,color:"Black",prevo:"houndour",evoLevel:24,eggGroups:["Field"],otherFormes:["houndoommega"]}, houndoommega:{num:229,species:"Houndoom-Mega",baseSpecies:"Houndoom",forme:"Mega",formeLetter:"M",types:["Dark","Fire"],baseStats:{hp:75,atk:90,def:90,spa:140,spd:90,spe:115},abilities:{0:"Solar Power"},heightm:1.9,weightkg:49.5,color:"Black",prevo:"houndour",evoLevel:24,eggGroups:["Field"]}, kingdra:{num:230,species:"Kingdra",types:["Water","Dragon"],baseStats:{hp:75,atk:95,def:95,spa:95,spd:95,spe:85},abilities:{0:"Swift Swim",1:"Sniper",H:"Damp"},heightm:1.8,weightkg:152,color:"Blue",prevo:"seadra",evoLevel:32,eggGroups:["Water 1","Dragon"]}, phanpy:{num:231,species:"Phanpy",types:["Ground"],baseStats:{hp:90,atk:60,def:60,spa:40,spd:40,spe:40},abilities:{0:"Pickup",H:"Sand Veil"},heightm:0.5,weightkg:33.5,color:"Blue",evos:["donphan"],eggGroups:["Field"]}, donphan:{num:232,species:"Donphan",types:["Ground"],baseStats:{hp:90,atk:120,def:120,spa:60,spd:60,spe:50},abilities:{0:"Sturdy",H:"Sand Veil"},heightm:1.1,weightkg:120,color:"Gray",prevo:"phanpy",evoLevel:25,eggGroups:["Field"]}, porygon2:{num:233,species:"Porygon2",types:["Normal"],gender:"N",baseStats:{hp:85,atk:80,def:90,spa:105,spd:95,spe:60},abilities:{0:"Trace",1:"Download",H:"Analytic"},heightm:0.6,weightkg:32.5,color:"Red",prevo:"porygon",evos:["porygonz"],evoLevel:1,eggGroups:["Mineral"]}, stantler:{num:234,species:"Stantler",types:["Normal"],baseStats:{hp:73,atk:95,def:62,spa:85,spd:65,spe:85},abilities:{0:"Intimidate",1:"Frisk",H:"Sap Sipper"},heightm:1.4,weightkg:71.2,color:"Brown",eggGroups:["Field"]}, smeargle:{num:235,species:"Smeargle",types:["Normal"],baseStats:{hp:55,atk:20,def:35,spa:20,spd:45,spe:75},abilities:{0:"Own Tempo",1:"Technician",H:"Moody"},heightm:1.2,weightkg:58,color:"White",eggGroups:["Field"]}, tyrogue:{num:236,species:"Tyrogue",types:["Fighting"],gender:"M",baseStats:{hp:35,atk:35,def:35,spa:35,spd:35,spe:35},abilities:{0:"Guts",1:"Steadfast",H:"Vital Spirit"},heightm:0.7,weightkg:21,color:"Purple",evos:["hitmonlee","hitmonchan","hitmontop"],eggGroups:["Undiscovered"]}, hitmontop:{num:237,species:"Hitmontop",types:["Fighting"],gender:"M",baseStats:{hp:50,atk:95,def:95,spa:35,spd:110,spe:70},abilities:{0:"Intimidate",1:"Technician",H:"Steadfast"},heightm:1.4,weightkg:48,color:"Brown",prevo:"tyrogue",evoLevel:20,eggGroups:["Human-Like"]}, smoochum:{num:238,species:"Smoochum",types:["Ice","Psychic"],gender:"F",baseStats:{hp:45,atk:30,def:15,spa:85,spd:65,spe:65},abilities:{0:"Oblivious",1:"Forewarn",H:"Hydration"},heightm:0.4,weightkg:6,color:"Pink",evos:["jynx"],eggGroups:["Undiscovered"]}, elekid:{num:239,species:"Elekid",types:["Electric"],genderRatio:{M:0.75,F:0.25},baseStats:{hp:45,atk:63,def:37,spa:65,spd:55,spe:95},abilities:{0:"Static",H:"Vital Spirit"},heightm:0.6,weightkg:23.5,color:"Yellow",evos:["electabuzz"],eggGroups:["Undiscovered"]}, magby:{num:240,species:"Magby",types:["Fire"],genderRatio:{M:0.75,F:0.25},baseStats:{hp:45,atk:75,def:37,spa:70,spd:55,spe:83},abilities:{0:"Flame Body",H:"Vital Spirit"},heightm:0.7,weightkg:21.4,color:"Red",evos:["magmar"],eggGroups:["Undiscovered"]}, miltank:{num:241,species:"Miltank",types:["Normal"],gender:"F",baseStats:{hp:95,atk:80,def:105,spa:40,spd:70,spe:100},abilities:{0:"Thick Fat",1:"Scrappy",H:"Sap Sipper"},heightm:1.2,weightkg:75.5,color:"Pink",eggGroups:["Field"]}, blissey:{num:242,species:"Blissey",types:["Normal"],gender:"F",baseStats:{hp:255,atk:10,def:10,spa:75,spd:135,spe:55},abilities:{0:"Natural Cure",1:"Serene Grace",H:"Healer"},heightm:1.5,weightkg:46.8,color:"Pink",prevo:"chansey",evoLevel:2,eggGroups:["Fairy"]}, raikou:{num:243,species:"Raikou",types:["Electric"],gender:"N",baseStats:{hp:90,atk:85,def:75,spa:115,spd:100,spe:115},abilities:{0:"Pressure",H:"Volt Absorb"},heightm:1.9,weightkg:178,color:"Yellow",eggGroups:["Undiscovered"]}, entei:{num:244,species:"Entei",types:["Fire"],gender:"N",baseStats:{hp:115,atk:115,def:85,spa:90,spd:75,spe:100},abilities:{0:"Pressure",H:"Flash Fire"},heightm:2.1,weightkg:198,color:"Brown",eggGroups:["Undiscovered"]}, suicune:{num:245,species:"Suicune",types:["Water"],gender:"N",baseStats:{hp:100,atk:75,def:115,spa:90,spd:115,spe:85},abilities:{0:"Pressure",H:"Water Absorb"},heightm:2,weightkg:187,color:"Blue",eggGroups:["Undiscovered"]}, larvitar:{num:246,species:"Larvitar",types:["Rock","Ground"],baseStats:{hp:50,atk:64,def:50,spa:45,spd:50,spe:41},abilities:{0:"Guts",H:"Sand Veil"},heightm:0.6,weightkg:72,color:"Green",evos:["pupitar"],eggGroups:["Monster"]}, pupitar:{num:247,species:"Pupitar",types:["Rock","Ground"],baseStats:{hp:70,atk:84,def:70,spa:65,spd:70,spe:51},abilities:{0:"Shed Skin"},heightm:1.2,weightkg:152,color:"Gray",prevo:"larvitar",evos:["tyranitar"],evoLevel:30,eggGroups:["Monster"]}, tyranitar:{num:248,species:"Tyranitar",types:["Rock","Dark"],baseStats:{hp:100,atk:134,def:110,spa:95,spd:100,spe:61},abilities:{0:"Sand Stream",H:"Unnerve"},heightm:2,weightkg:202,color:"Green",prevo:"pupitar",evoLevel:55,eggGroups:["Monster"],otherFormes:["tyranitarmega"]}, tyranitarmega:{num:248,species:"Tyranitar-Mega",baseSpecies:"Tyranitar",forme:"Mega",formeLetter:"M",types:["Rock","Dark"],baseStats:{hp:100,atk:164,def:150,spa:95,spd:120,spe:71},abilities:{0:"Sand Stream"},heightm:2.5,weightkg:255,color:"Green",prevo:"pupitar",evoLevel:55,eggGroups:["Monster"]}, lugia:{num:249,species:"Lugia",types:["Psychic","Flying"],gender:"N",baseStats:{hp:106,atk:90,def:130,spa:90,spd:154,spe:110},abilities:{0:"Pressure",H:"Multiscale"},heightm:5.2,weightkg:216,color:"White",eggGroups:["Undiscovered"]}, hooh:{num:250,species:"Ho-Oh",types:["Fire","Flying"],gender:"N",baseStats:{hp:106,atk:130,def:90,spa:110,spd:154,spe:90},abilities:{0:"Pressure",H:"Regenerator"},heightm:3.8,weightkg:199,color:"Red",eggGroups:["Undiscovered"]}, celebi:{num:251,species:"Celebi",types:["Psychic","Grass"],gender:"N",baseStats:{hp:100,atk:100,def:100,spa:100,spd:100,spe:100},abilities:{0:"Natural Cure"},heightm:0.6,weightkg:5,color:"Green",eggGroups:["Undiscovered"]}, treecko:{num:252,species:"Treecko",types:["Grass"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:40,atk:45,def:35,spa:65,spd:55,spe:70},abilities:{0:"Overgrow",H:"Unburden"},heightm:0.5,weightkg:5,color:"Green",evos:["grovyle"],eggGroups:["Monster","Dragon"]}, grovyle:{num:253,species:"Grovyle",types:["Grass"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:50,atk:65,def:45,spa:85,spd:65,spe:95},abilities:{0:"Overgrow",H:"Unburden"},heightm:0.9,weightkg:21.6,color:"Green",prevo:"treecko",evos:["sceptile"],evoLevel:16,eggGroups:["Monster","Dragon"]}, sceptile:{num:254,species:"Sceptile",types:["Grass"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:70,atk:85,def:65,spa:105,spd:85,spe:120},abilities:{0:"Overgrow",H:"Unburden"},heightm:1.7,weightkg:52.2,color:"Green",prevo:"grovyle",evoLevel:36,eggGroups:["Monster","Dragon"]}, torchic:{num:255,species:"Torchic",types:["Fire"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:45,atk:60,def:40,spa:70,spd:50,spe:45},abilities:{0:"Blaze",H:"Speed Boost"},heightm:0.4,weightkg:2.5,color:"Red",evos:["combusken"],eggGroups:["Field"]}, combusken:{num:256,species:"Combusken",types:["Fire","Fighting"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:60,atk:85,def:60,spa:85,spd:60,spe:55},abilities:{0:"Blaze",H:"Speed Boost"},heightm:0.9,weightkg:19.5,color:"Red",prevo:"torchic",evos:["blaziken"],evoLevel:16,eggGroups:["Field"]}, blaziken:{num:257,species:"Blaziken",types:["Fire","Fighting"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:80,atk:120,def:70,spa:110,spd:70,spe:80},abilities:{0:"Blaze",H:"Speed Boost"},heightm:1.9,weightkg:52,color:"Red",prevo:"combusken",evoLevel:36,eggGroups:["Field"],otherFormes:["blazikenmega"]}, blazikenmega:{num:257,species:"Blaziken-Mega",baseSpecies:"Blaziken",forme:"Mega",formeLetter:"M",types:["Fire","Fighting"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:80,atk:160,def:80,spa:130,spd:80,spe:100},abilities:{0:"Speed Boost"},heightm:1.9,weightkg:52,color:"Red",prevo:"combusken",evoLevel:36,eggGroups:["Field"]}, mudkip:{num:258,species:"Mudkip",types:["Water"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:50,atk:70,def:50,spa:50,spd:50,spe:40},abilities:{0:"Torrent",H:"Damp"},heightm:0.4,weightkg:7.6,color:"Blue",evos:["marshtomp"],eggGroups:["Monster","Water 1"]}, marshtomp:{num:259,species:"Marshtomp",types:["Water","Ground"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:70,atk:85,def:70,spa:60,spd:70,spe:50},abilities:{0:"Torrent",H:"Damp"},heightm:0.7,weightkg:28,color:"Blue",prevo:"mudkip",evos:["swampert"],evoLevel:16,eggGroups:["Monster","Water 1"]}, swampert:{num:260,species:"Swampert",types:["Water","Ground"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:100,atk:110,def:90,spa:85,spd:90,spe:60},abilities:{0:"Torrent",H:"Damp"},heightm:1.5,weightkg:81.9,color:"Blue",prevo:"marshtomp",evoLevel:36,eggGroups:["Monster","Water 1"]}, poochyena:{num:261,species:"Poochyena",types:["Dark"],baseStats:{hp:35,atk:55,def:35,spa:30,spd:30,spe:35},abilities:{0:"Run Away",1:"Quick Feet",H:"Rattled"},heightm:0.5,weightkg:13.6,color:"Gray",evos:["mightyena"],eggGroups:["Field"]}, mightyena:{num:262,species:"Mightyena",types:["Dark"],baseStats:{hp:70,atk:90,def:70,spa:60,spd:60,spe:70},abilities:{0:"Intimidate",1:"Quick Feet",H:"Moxie"},heightm:1,weightkg:37,color:"Gray",prevo:"poochyena",evoLevel:18,eggGroups:["Field"]}, zigzagoon:{num:263,species:"Zigzagoon",types:["Normal"],baseStats:{hp:38,atk:30,def:41,spa:30,spd:41,spe:60},abilities:{0:"Pickup",1:"Gluttony",H:"Quick Feet"},heightm:0.4,weightkg:17.5,color:"Brown",evos:["linoone"],eggGroups:["Field"]}, linoone:{num:264,species:"Linoone",types:["Normal"],baseStats:{hp:78,atk:70,def:61,spa:50,spd:61,spe:100},abilities:{0:"Pickup",1:"Gluttony",H:"Quick Feet"},heightm:0.5,weightkg:32.5,color:"White",prevo:"zigzagoon",evoLevel:20,eggGroups:["Field"]}, wurmple:{num:265,species:"Wurmple",types:["Bug"],baseStats:{hp:45,atk:45,def:35,spa:20,spd:30,spe:20},abilities:{0:"Shield Dust",H:"Run Away"},heightm:0.3,weightkg:3.6,color:"Red",evos:["silcoon","cascoon"],eggGroups:["Bug"]}, silcoon:{num:266,species:"Silcoon",types:["Bug"],baseStats:{hp:50,atk:35,def:55,spa:25,spd:25,spe:15},abilities:{0:"Shed Skin"},heightm:0.6,weightkg:10,color:"White",prevo:"wurmple",evos:["beautifly"],evoLevel:7,eggGroups:["Bug"]}, beautifly:{num:267,species:"Beautifly",types:["Bug","Flying"],baseStats:{hp:60,atk:70,def:50,spa:100,spd:50,spe:65},abilities:{0:"Swarm",H:"Rivalry"},heightm:1,weightkg:28.4,color:"Yellow",prevo:"silcoon",evoLevel:10,eggGroups:["Bug"]}, cascoon:{num:268,species:"Cascoon",types:["Bug"],baseStats:{hp:50,atk:35,def:55,spa:25,spd:25,spe:15},abilities:{0:"Shed Skin"},heightm:0.7,weightkg:11.5,color:"Purple",prevo:"wurmple",evos:["dustox"],evoLevel:7,eggGroups:["Bug"]}, dustox:{num:269,species:"Dustox",types:["Bug","Poison"],baseStats:{hp:60,atk:50,def:70,spa:50,spd:90,spe:65},abilities:{0:"Shield Dust",H:"Compound Eyes"},heightm:1.2,weightkg:31.6,color:"Green",prevo:"cascoon",evoLevel:10,eggGroups:["Bug"]}, lotad:{num:270,species:"Lotad",types:["Water","Grass"],baseStats:{hp:40,atk:30,def:30,spa:40,spd:50,spe:30},abilities:{0:"Swift Swim",1:"Rain Dish",H:"Own Tempo"},heightm:0.5,weightkg:2.6,color:"Green",evos:["lombre"],eggGroups:["Water 1","Grass"]}, lombre:{num:271,species:"Lombre",types:["Water","Grass"],baseStats:{hp:60,atk:50,def:50,spa:60,spd:70,spe:50},abilities:{0:"Swift Swim",1:"Rain Dish",H:"Own Tempo"},heightm:1.2,weightkg:32.5,color:"Green",prevo:"lotad",evos:["ludicolo"],evoLevel:14,eggGroups:["Water 1","Grass"]}, ludicolo:{num:272,species:"Ludicolo",types:["Water","Grass"],baseStats:{hp:80,atk:70,def:70,spa:90,spd:100,spe:70},abilities:{0:"Swift Swim",1:"Rain Dish",H:"Own Tempo"},heightm:1.5,weightkg:55,color:"Green",prevo:"lombre",evoLevel:14,eggGroups:["Water 1","Grass"]}, seedot:{num:273,species:"Seedot",types:["Grass"],baseStats:{hp:40,atk:40,def:50,spa:30,spd:30,spe:30},abilities:{0:"Chlorophyll",1:"Early Bird",H:"Pickpocket"},heightm:0.5,weightkg:4,color:"Brown",evos:["nuzleaf"],eggGroups:["Field","Grass"]}, nuzleaf:{num:274,species:"Nuzleaf",types:["Grass","Dark"],baseStats:{hp:70,atk:70,def:40,spa:60,spd:40,spe:60},abilities:{0:"Chlorophyll",1:"Early Bird",H:"Pickpocket"},heightm:1,weightkg:28,color:"Brown",prevo:"seedot",evos:["shiftry"],evoLevel:14,eggGroups:["Field","Grass"]}, shiftry:{num:275,species:"Shiftry",types:["Grass","Dark"],baseStats:{hp:90,atk:100,def:60,spa:90,spd:60,spe:80},abilities:{0:"Chlorophyll",1:"Early Bird",H:"Pickpocket"},heightm:1.3,weightkg:59.6,color:"Brown",prevo:"nuzleaf",evoLevel:14,eggGroups:["Field","Grass"]}, taillow:{num:276,species:"Taillow",types:["Normal","Flying"],baseStats:{hp:40,atk:55,def:30,spa:30,spd:30,spe:85},abilities:{0:"Guts",H:"Scrappy"},heightm:0.3,weightkg:2.3,color:"Blue",evos:["swellow"],eggGroups:["Flying"]}, swellow:{num:277,species:"Swellow",types:["Normal","Flying"],baseStats:{hp:60,atk:85,def:60,spa:50,spd:50,spe:125},abilities:{0:"Guts",H:"Scrappy"},heightm:0.7,weightkg:19.8,color:"Blue",prevo:"taillow",evoLevel:22,eggGroups:["Flying"]}, wingull:{num:278,species:"Wingull",types:["Water","Flying"],baseStats:{hp:40,atk:30,def:30,spa:55,spd:30,spe:85},abilities:{0:"Keen Eye",H:"Rain Dish"},heightm:0.6,weightkg:9.5,color:"White",evos:["pelipper"],eggGroups:["Water 1","Flying"]}, pelipper:{num:279,species:"Pelipper",types:["Water","Flying"],baseStats:{hp:60,atk:50,def:100,spa:85,spd:70,spe:65},abilities:{0:"Keen Eye",H:"Rain Dish"},heightm:1.2,weightkg:28,color:"Yellow",prevo:"wingull",evoLevel:25,eggGroups:["Water 1","Flying"]}, ralts:{num:280,species:"Ralts",types:["Psychic","Fairy"],baseStats:{hp:28,atk:25,def:25,spa:45,spd:35,spe:40},abilities:{0:"Synchronize",1:"Trace",H:"Telepathy"},heightm:0.4,weightkg:6.6,color:"White",evos:["kirlia"],eggGroups:["Amorphous"]}, kirlia:{num:281,species:"Kirlia",types:["Psychic","Fairy"],baseStats:{hp:38,atk:35,def:35,spa:65,spd:55,spe:50},abilities:{0:"Synchronize",1:"Trace",H:"Telepathy"},heightm:0.8,weightkg:20.2,color:"White",prevo:"ralts",evos:["gardevoir","gallade"],evoLevel:20,eggGroups:["Amorphous"]}, gardevoir:{num:282,species:"Gardevoir",types:["Psychic","Fairy"],baseStats:{hp:68,atk:65,def:65,spa:125,spd:115,spe:80},abilities:{0:"Synchronize",1:"Trace",H:"Telepathy"},heightm:1.6,weightkg:48.4,color:"White",prevo:"kirlia",evoLevel:30,eggGroups:["Amorphous"],otherFormes:["gardevoirmega"]}, gardevoirmega:{num:282,species:"Gardevoir-Mega",baseSpecies:"Gardevoir",forme:"Mega",formeLetter:"M",types:["Psychic","Fairy"],baseStats:{hp:68,atk:85,def:65,spa:165,spd:135,spe:100},abilities:{0:"Pixilate"},heightm:1.6,weightkg:48.4,color:"White",prevo:"kirlia",evoLevel:30,eggGroups:["Amorphous"]}, surskit:{num:283,species:"Surskit",types:["Bug","Water"],baseStats:{hp:40,atk:30,def:32,spa:50,spd:52,spe:65},abilities:{0:"Swift Swim",H:"Rain Dish"},heightm:0.5,weightkg:1.7,color:"Blue",evos:["masquerain"],eggGroups:["Water 1","Bug"]}, masquerain:{num:284,species:"Masquerain",types:["Bug","Flying"],baseStats:{hp:70,atk:60,def:62,spa:80,spd:82,spe:60},abilities:{0:"Intimidate",H:"Unnerve"},heightm:0.8,weightkg:3.6,color:"Blue",prevo:"surskit",evoLevel:22,eggGroups:["Water 1","Bug"]}, shroomish:{num:285,species:"Shroomish",types:["Grass"],baseStats:{hp:60,atk:40,def:60,spa:40,spd:60,spe:35},abilities:{0:"Effect Spore",1:"Poison Heal",H:"Quick Feet"},heightm:0.4,weightkg:4.5,color:"Brown",evos:["breloom"],eggGroups:["Fairy","Grass"]}, breloom:{num:286,species:"Breloom",types:["Grass","Fighting"],baseStats:{hp:60,atk:130,def:80,spa:60,spd:60,spe:70},abilities:{0:"Effect Spore",1:"Poison Heal",H:"Technician"},heightm:1.2,weightkg:39.2,color:"Green",prevo:"shroomish",evoLevel:23,eggGroups:["Fairy","Grass"]}, slakoth:{num:287,species:"Slakoth",types:["Normal"],baseStats:{hp:60,atk:60,def:60,spa:35,spd:35,spe:30},abilities:{0:"Truant"},heightm:0.8,weightkg:24,color:"Brown",evos:["vigoroth"],eggGroups:["Field"]}, vigoroth:{num:288,species:"Vigoroth",types:["Normal"],baseStats:{hp:80,atk:80,def:80,spa:55,spd:55,spe:90},abilities:{0:"Vital Spirit"},heightm:1.4,weightkg:46.5,color:"White",prevo:"slakoth",evos:["slaking"],evoLevel:18,eggGroups:["Field"]}, slaking:{num:289,species:"Slaking",types:["Normal"],baseStats:{hp:150,atk:160,def:100,spa:95,spd:65,spe:100},abilities:{0:"Truant"},heightm:2,weightkg:130.5,color:"Brown",prevo:"vigoroth",evoLevel:36,eggGroups:["Field"]}, nincada:{num:290,species:"Nincada",types:["Bug","Ground"],baseStats:{hp:31,atk:45,def:90,spa:30,spd:30,spe:40},abilities:{0:"Compound Eyes",H:"Run Away"},heightm:0.5,weightkg:5.5,color:"Gray",evos:["ninjask","shedinja"],eggGroups:["Bug"]}, ninjask:{num:291,species:"Ninjask",types:["Bug","Flying"],baseStats:{hp:61,atk:90,def:45,spa:50,spd:50,spe:160},abilities:{0:"Speed Boost",H:"Infiltrator"},heightm:0.8,weightkg:12,color:"Yellow",prevo:"nincada",evoLevel:20,eggGroups:["Bug"]}, shedinja:{num:292,species:"Shedinja",types:["Bug","Ghost"],gender:"N",baseStats:{hp:1,atk:90,def:45,spa:30,spd:30,spe:40},abilities:{0:"Wonder Guard"},heightm:0.8,weightkg:1.2,color:"Brown",prevo:"nincada",evoLevel:20,eggGroups:["Mineral"]}, whismur:{num:293,species:"Whismur",types:["Normal"],baseStats:{hp:64,atk:51,def:23,spa:51,spd:23,spe:28},abilities:{0:"Soundproof",H:"Rattled"},heightm:0.6,weightkg:16.3,color:"Pink",evos:["loudred"],eggGroups:["Monster","Field"]}, loudred:{num:294,species:"Loudred",types:["Normal"],baseStats:{hp:84,atk:71,def:43,spa:71,spd:43,spe:48},abilities:{0:"Soundproof",H:"Scrappy"},heightm:1,weightkg:40.5,color:"Blue",prevo:"whismur",evos:["exploud"],evoLevel:20,eggGroups:["Monster","Field"]}, exploud:{num:295,species:"Exploud",types:["Normal"],baseStats:{hp:104,atk:91,def:63,spa:91,spd:73,spe:68},abilities:{0:"Soundproof",H:"Scrappy"},heightm:1.5,weightkg:84,color:"Blue",prevo:"loudred",evoLevel:40,eggGroups:["Monster","Field"]}, makuhita:{num:296,species:"Makuhita",types:["Fighting"],genderRatio:{M:0.75,F:0.25},baseStats:{hp:72,atk:60,def:30,spa:20,spd:30,spe:25},abilities:{0:"Thick Fat",1:"Guts",H:"Sheer Force"},heightm:1,weightkg:86.4,color:"Yellow",evos:["hariyama"],eggGroups:["Human-Like"]}, hariyama:{num:297,species:"Hariyama",types:["Fighting"],genderRatio:{M:0.75,F:0.25},baseStats:{hp:144,atk:120,def:60,spa:40,spd:60,spe:50},abilities:{0:"Thick Fat",1:"Guts",H:"Sheer Force"},heightm:2.3,weightkg:253.8,color:"Brown",prevo:"makuhita",evoLevel:24,eggGroups:["Human-Like"]}, azurill:{num:298,species:"Azurill",types:["Normal","Fairy"],genderRatio:{M:0.25,F:0.75},baseStats:{hp:50,atk:20,def:40,spa:20,spd:40,spe:20},abilities:{0:"Thick Fat",1:"Huge Power",H:"Sap Sipper"},heightm:0.2,weightkg:2,color:"Blue",evos:["marill"],eggGroups:["Undiscovered"]}, nosepass:{num:299,species:"Nosepass",types:["Rock"],baseStats:{hp:30,atk:45,def:135,spa:45,spd:90,spe:30},abilities:{0:"Sturdy",1:"Magnet Pull",H:"Sand Force"},heightm:1,weightkg:97,color:"Gray",evos:["probopass"],eggGroups:["Mineral"]}, skitty:{num:300,species:"Skitty",types:["Normal"],genderRatio:{M:0.25,F:0.75},baseStats:{hp:50,atk:45,def:45,spa:35,spd:35,spe:50},abilities:{0:"Cute Charm",1:"Normalize",H:"Wonder Skin"},heightm:0.6,weightkg:11,color:"Pink",evos:["delcatty"],eggGroups:["Field","Fairy"]}, delcatty:{num:301,species:"Delcatty",types:["Normal"],genderRatio:{M:0.25,F:0.75},baseStats:{hp:70,atk:65,def:65,spa:55,spd:55,spe:70},abilities:{0:"Cute Charm",1:"Normalize",H:"Wonder Skin"},heightm:1.1,weightkg:32.6,color:"Purple",prevo:"skitty",evoLevel:1,eggGroups:["Field","Fairy"]}, sableye:{num:302,species:"Sableye",types:["Dark","Ghost"],baseStats:{hp:50,atk:75,def:75,spa:65,spd:65,spe:50},abilities:{0:"Keen Eye",1:"Stall",H:"Prankster"},heightm:0.5,weightkg:11,color:"Purple",eggGroups:["Human-Like"]}, mawile:{num:303,species:"Mawile",types:["Steel","Fairy"],baseStats:{hp:50,atk:85,def:85,spa:55,spd:55,spe:50},abilities:{0:"Hyper Cutter",1:"Intimidate",H:"Sheer Force"},heightm:0.6,weightkg:11.5,color:"Black",eggGroups:["Field","Fairy"],otherFormes:["mawilemega"]}, mawilemega:{num:303,species:"Mawile-Mega",baseSpecies:"Mawile",forme:"Mega",formeLetter:"M",types:["Steel","Fairy"],baseStats:{hp:50,atk:105,def:125,spa:55,spd:95,spe:50},abilities:{0:"Huge Power"},heightm:1,weightkg:23.5,color:"Black",eggGroups:["Field","Fairy"]}, aron:{num:304,species:"Aron",types:["Steel","Rock"],baseStats:{hp:50,atk:70,def:100,spa:40,spd:40,spe:30},abilities:{0:"Sturdy",1:"Rock Head",H:"Heavy Metal"},heightm:0.4,weightkg:60,color:"Gray",evos:["lairon"],eggGroups:["Monster"]}, lairon:{num:305,species:"Lairon",types:["Steel","Rock"],baseStats:{hp:60,atk:90,def:140,spa:50,spd:50,spe:40},abilities:{0:"Sturdy",1:"Rock Head",H:"Heavy Metal"},heightm:0.9,weightkg:120,color:"Gray",prevo:"aron",evos:["aggron"],evoLevel:32,eggGroups:["Monster"]}, aggron:{num:306,species:"Aggron",types:["Steel","Rock"],baseStats:{hp:70,atk:110,def:180,spa:60,spd:60,spe:50},abilities:{0:"Sturdy",1:"Rock Head",H:"Heavy Metal"},heightm:2.1,weightkg:360,color:"Gray",prevo:"lairon",evoLevel:42,eggGroups:["Monster"],otherFormes:["aggronmega"]}, aggronmega:{num:306,species:"Aggron-Mega",baseSpecies:"Aggron",forme:"Mega",formeLetter:"M",types:["Steel"],baseStats:{hp:70,atk:140,def:230,spa:60,spd:80,spe:50},abilities:{0:"Filter"},heightm:2.2,weightkg:395,color:"Gray",prevo:"lairon",evoLevel:42,eggGroups:["Monster"]}, meditite:{num:307,species:"Meditite",types:["Fighting","Psychic"],baseStats:{hp:30,atk:40,def:55,spa:40,spd:55,spe:60},abilities:{0:"Pure Power",H:"Telepathy"},heightm:0.6,weightkg:11.2,color:"Blue",evos:["medicham"],eggGroups:["Human-Like"]}, medicham:{num:308,species:"Medicham",types:["Fighting","Psychic"],baseStats:{hp:60,atk:60,def:75,spa:60,spd:75,spe:80},abilities:{0:"Pure Power",H:"Telepathy"},heightm:1.3,weightkg:31.5,color:"Red",prevo:"meditite",evoLevel:37,eggGroups:["Human-Like"],otherFormes:["medichammega"]}, medichammega:{num:308,species:"Medicham-Mega",baseSpecies:"Medicham",forme:"Mega",formeLetter:"M",types:["Fighting","Psychic"],baseStats:{hp:60,atk:100,def:85,spa:80,spd:85,spe:100},abilities:{0:"Pure Power"},heightm:1.3,weightkg:31.5,color:"Red",prevo:"meditite",evoLevel:37,eggGroups:["Human-Like"]}, electrike:{num:309,species:"Electrike",types:["Electric"],baseStats:{hp:40,atk:45,def:40,spa:65,spd:40,spe:65},abilities:{0:"Static",1:"Lightningrod",H:"Minus"},heightm:0.6,weightkg:15.2,color:"Green",evos:["manectric"],eggGroups:["Field"]}, manectric:{num:310,species:"Manectric",types:["Electric"],baseStats:{hp:70,atk:75,def:60,spa:105,spd:60,spe:105},abilities:{0:"Static",1:"Lightningrod",H:"Minus"},heightm:1.5,weightkg:40.2,color:"Yellow",prevo:"electrike",evoLevel:26,eggGroups:["Field"],otherFormes:["manectricmega"]}, manectricmega:{num:310,species:"Manectric-Mega",baseSpecies:"Manectric",forme:"Mega",formeLetter:"M",types:["Electric"],baseStats:{hp:70,atk:75,def:80,spa:135,spd:80,spe:135},abilities:{0:"Intimidate"},heightm:1.8,weightkg:44,color:"Yellow",prevo:"electrike",evoLevel:26,eggGroups:["Field"]}, plusle:{num:311,species:"Plusle",types:["Electric"],baseStats:{hp:60,atk:50,def:40,spa:85,spd:75,spe:95},abilities:{0:"Plus",H:"Lightningrod"},heightm:0.4,weightkg:4.2,color:"Yellow",eggGroups:["Fairy"]}, minun:{num:312,species:"Minun",types:["Electric"],baseStats:{hp:60,atk:40,def:50,spa:75,spd:85,spe:95},abilities:{0:"Minus",H:"Volt Absorb"},heightm:0.4,weightkg:4.2,color:"Yellow",eggGroups:["Fairy"]}, volbeat:{num:313,species:"Volbeat",types:["Bug"],gender:"M",baseStats:{hp:65,atk:73,def:55,spa:47,spd:75,spe:85},abilities:{0:"Illuminate",1:"Swarm",H:"Prankster"},heightm:0.7,weightkg:17.7,color:"Gray",eggGroups:["Bug","Human-Like"]}, illumise:{num:314,species:"Illumise",types:["Bug"],gender:"F",baseStats:{hp:65,atk:47,def:55,spa:73,spd:75,spe:85},abilities:{0:"Oblivious",1:"Tinted Lens",H:"Prankster"},heightm:0.6,weightkg:17.7,color:"Purple",eggGroups:["Bug","Human-Like"]}, roselia:{num:315,species:"Roselia",types:["Grass","Poison"],baseStats:{hp:50,atk:60,def:45,spa:100,spd:80,spe:65},abilities:{0:"Natural Cure",1:"Poison Point",H:"Leaf Guard"},heightm:0.3,weightkg:2,color:"Green",prevo:"budew",evos:["roserade"],evoLevel:1,eggGroups:["Fairy","Grass"]}, gulpin:{num:316,species:"Gulpin",types:["Poison"],baseStats:{hp:70,atk:43,def:53,spa:43,spd:53,spe:40},abilities:{0:"Liquid Ooze",1:"Sticky Hold",H:"Gluttony"},heightm:0.4,weightkg:10.3,color:"Green",evos:["swalot"],eggGroups:["Amorphous"]}, swalot:{num:317,species:"Swalot",types:["Poison"],baseStats:{hp:100,atk:73,def:83,spa:73,spd:83,spe:55},abilities:{0:"Liquid Ooze",1:"Sticky Hold",H:"Gluttony"},heightm:1.7,weightkg:80,color:"Purple",prevo:"gulpin",evoLevel:26,eggGroups:["Amorphous"]}, carvanha:{num:318,species:"Carvanha",types:["Water","Dark"],baseStats:{hp:45,atk:90,def:20,spa:65,spd:20,spe:65},abilities:{0:"Rough Skin",H:"Speed Boost"},heightm:0.8,weightkg:20.8,color:"Red",evos:["sharpedo"],eggGroups:["Water 2"]}, sharpedo:{num:319,species:"Sharpedo",types:["Water","Dark"],baseStats:{hp:70,atk:120,def:40,spa:95,spd:40,spe:95},abilities:{0:"Rough Skin",H:"Speed Boost"},heightm:1.8,weightkg:88.8,color:"Blue",prevo:"carvanha",evoLevel:30,eggGroups:["Water 2"]}, wailmer:{num:320,species:"Wailmer",types:["Water"],baseStats:{hp:130,atk:70,def:35,spa:70,spd:35,spe:60},abilities:{0:"Water Veil",1:"Oblivious",H:"Pressure"},heightm:2,weightkg:130,color:"Blue",evos:["wailord"],eggGroups:["Field","Water 2"]}, wailord:{num:321,species:"Wailord",types:["Water"],baseStats:{hp:170,atk:90,def:45,spa:90,spd:45,spe:60},abilities:{0:"Water Veil",1:"Oblivious",H:"Pressure"},heightm:14.5,weightkg:398,color:"Blue",prevo:"wailmer",evoLevel:40,eggGroups:["Field","Water 2"]}, numel:{num:322,species:"Numel",types:["Fire","Ground"],baseStats:{hp:60,atk:60,def:40,spa:65,spd:45,spe:35},abilities:{0:"Oblivious",1:"Simple",H:"Own Tempo"},heightm:0.7,weightkg:24,color:"Yellow",evos:["camerupt"],eggGroups:["Field"]}, camerupt:{num:323,species:"Camerupt",types:["Fire","Ground"],baseStats:{hp:70,atk:100,def:70,spa:105,spd:75,spe:40},abilities:{0:"Magma Armor",1:"Solid Rock",H:"Anger Point"},heightm:1.9,weightkg:220,color:"Red",prevo:"numel",evoLevel:33,eggGroups:["Field"]}, torkoal:{num:324,species:"Torkoal",types:["Fire"],baseStats:{hp:70,atk:85,def:140,spa:85,spd:70,spe:20},abilities:{0:"White Smoke",H:"Shell Armor"},heightm:0.5,weightkg:80.4,color:"Brown",eggGroups:["Field"]}, spoink:{num:325,species:"Spoink",types:["Psychic"],baseStats:{hp:60,atk:25,def:35,spa:70,spd:80,spe:60},abilities:{0:"Thick Fat",1:"Own Tempo",H:"Gluttony"},heightm:0.7,weightkg:30.6,color:"Black",evos:["grumpig"],eggGroups:["Field"]}, grumpig:{num:326,species:"Grumpig",types:["Psychic"],baseStats:{hp:80,atk:45,def:65,spa:90,spd:110,spe:80},abilities:{0:"Thick Fat",1:"Own Tempo",H:"Gluttony"},heightm:0.9,weightkg:71.5,color:"Purple",prevo:"spoink",evoLevel:32,eggGroups:["Field"]}, spinda:{num:327,species:"Spinda",types:["Normal"],baseStats:{hp:60,atk:60,def:60,spa:60,spd:60,spe:60},abilities:{0:"Own Tempo",1:"Tangled Feet",H:"Contrary"},heightm:1.1,weightkg:5,color:"Brown",eggGroups:["Field","Human-Like"]}, trapinch:{num:328,species:"Trapinch",types:["Ground"],baseStats:{hp:45,atk:100,def:45,spa:45,spd:45,spe:10},abilities:{0:"Hyper Cutter",1:"Arena Trap",H:"Sheer Force"},heightm:0.7,weightkg:15,color:"Brown",evos:["vibrava"],eggGroups:["Bug"]}, vibrava:{num:329,species:"Vibrava",types:["Ground","Dragon"],baseStats:{hp:50,atk:70,def:50,spa:50,spd:50,spe:70},abilities:{0:"Levitate"},heightm:1.1,weightkg:15.3,color:"Green",prevo:"trapinch",evos:["flygon"],evoLevel:35,eggGroups:["Bug"]}, flygon:{num:330,species:"Flygon",types:["Ground","Dragon"],baseStats:{hp:80,atk:100,def:80,spa:80,spd:80,spe:100},abilities:{0:"Levitate"},heightm:2,weightkg:82,color:"Green",prevo:"vibrava",evoLevel:45,eggGroups:["Bug"]}, cacnea:{num:331,species:"Cacnea",types:["Grass"],baseStats:{hp:50,atk:85,def:40,spa:85,spd:40,spe:35},abilities:{0:"Sand Veil",H:"Water Absorb"},heightm:0.4,weightkg:51.3,color:"Green",evos:["cacturne"],eggGroups:["Grass","Human-Like"]}, cacturne:{num:332,species:"Cacturne",types:["Grass","Dark"],baseStats:{hp:70,atk:115,def:60,spa:115,spd:60,spe:55},abilities:{0:"Sand Veil",H:"Water Absorb"},heightm:1.3,weightkg:77.4,color:"Green",prevo:"cacnea",evoLevel:32,eggGroups:["Grass","Human-Like"]}, swablu:{num:333,species:"Swablu",types:["Normal","Flying"],baseStats:{hp:45,atk:40,def:60,spa:40,spd:75,spe:50},abilities:{0:"Natural Cure",H:"Cloud Nine"},heightm:0.4,weightkg:1.2,color:"Blue",evos:["altaria"],eggGroups:["Flying","Dragon"]}, altaria:{num:334,species:"Altaria",types:["Dragon","Flying"],baseStats:{hp:75,atk:70,def:90,spa:70,spd:105,spe:80},abilities:{0:"Natural Cure",H:"Cloud Nine"},heightm:1.1,weightkg:20.6,color:"Blue",prevo:"swablu",evoLevel:35,eggGroups:["Flying","Dragon"]}, zangoose:{num:335,species:"Zangoose",types:["Normal"],baseStats:{hp:73,atk:115,def:60,spa:60,spd:60,spe:90},abilities:{0:"Immunity",H:"Toxic Boost"},heightm:1.3,weightkg:40.3,color:"White",eggGroups:["Field"]}, seviper:{num:336,species:"Seviper",types:["Poison"],baseStats:{hp:73,atk:100,def:60,spa:100,spd:60,spe:65},abilities:{0:"Shed Skin",H:"Infiltrator"},heightm:2.7,weightkg:52.5,color:"Black",eggGroups:["Field","Dragon"]}, lunatone:{num:337,species:"Lunatone",types:["Rock","Psychic"],gender:"N",baseStats:{hp:70,atk:55,def:65,spa:95,spd:85,spe:70},abilities:{0:"Levitate"},heightm:1,weightkg:168,color:"Yellow",eggGroups:["Mineral"]}, solrock:{num:338,species:"Solrock",types:["Rock","Psychic"],gender:"N",baseStats:{hp:70,atk:95,def:85,spa:55,spd:65,spe:70},abilities:{0:"Levitate"},heightm:1.2,weightkg:154,color:"Red",eggGroups:["Mineral"]}, barboach:{num:339,species:"Barboach",types:["Water","Ground"],baseStats:{hp:50,atk:48,def:43,spa:46,spd:41,spe:60},abilities:{0:"Oblivious",1:"Anticipation",H:"Hydration"},heightm:0.4,weightkg:1.9,color:"Gray",evos:["whiscash"],eggGroups:["Water 2"]}, whiscash:{num:340,species:"Whiscash",types:["Water","Ground"],baseStats:{hp:110,atk:78,def:73,spa:76,spd:71,spe:60},abilities:{0:"Oblivious",1:"Anticipation",H:"Hydration"},heightm:0.9,weightkg:23.6,color:"Blue",prevo:"barboach",evoLevel:30,eggGroups:["Water 2"]}, corphish:{num:341,species:"Corphish",types:["Water"],baseStats:{hp:43,atk:80,def:65,spa:50,spd:35,spe:35},abilities:{0:"Hyper Cutter",1:"Shell Armor",H:"Adaptability"},heightm:0.6,weightkg:11.5,color:"Red",evos:["crawdaunt"],eggGroups:["Water 1","Water 3"]}, crawdaunt:{num:342,species:"Crawdaunt",types:["Water","Dark"],baseStats:{hp:63,atk:120,def:85,spa:90,spd:55,spe:55},abilities:{0:"Hyper Cutter",1:"Shell Armor",H:"Adaptability"},heightm:1.1,weightkg:32.8,color:"Red",prevo:"corphish",evoLevel:30,eggGroups:["Water 1","Water 3"]}, baltoy:{num:343,species:"Baltoy",types:["Ground","Psychic"],gender:"N",baseStats:{hp:40,atk:40,def:55,spa:40,spd:70,spe:55},abilities:{0:"Levitate"},heightm:0.5,weightkg:21.5,color:"Brown",evos:["claydol"],eggGroups:["Mineral"]}, claydol:{num:344,species:"Claydol",types:["Ground","Psychic"],gender:"N",baseStats:{hp:60,atk:70,def:105,spa:70,spd:120,spe:75},abilities:{0:"Levitate"},heightm:1.5,weightkg:108,color:"Black",prevo:"baltoy",evoLevel:36,eggGroups:["Mineral"]}, lileep:{num:345,species:"Lileep",types:["Rock","Grass"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:66,atk:41,def:77,spa:61,spd:87,spe:23},abilities:{0:"Suction Cups",H:"Storm Drain"},heightm:1,weightkg:23.8,color:"Purple",evos:["cradily"],eggGroups:["Water 3"]}, cradily:{num:346,species:"Cradily",types:["Rock","Grass"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:86,atk:81,def:97,spa:81,spd:107,spe:43},abilities:{0:"Suction Cups",H:"Storm Drain"},heightm:1.5,weightkg:60.4,color:"Green",prevo:"lileep",evoLevel:40,eggGroups:["Water 3"]}, anorith:{num:347,species:"Anorith",types:["Rock","Bug"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:45,atk:95,def:50,spa:40,spd:50,spe:75},abilities:{0:"Battle Armor",H:"Swift Swim"},heightm:0.7,weightkg:12.5,color:"Gray",evos:["armaldo"],eggGroups:["Water 3"]}, armaldo:{num:348,species:"Armaldo",types:["Rock","Bug"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:75,atk:125,def:100,spa:70,spd:80,spe:45},abilities:{0:"Battle Armor",H:"Swift Swim"},heightm:1.5,weightkg:68.2,color:"Gray",prevo:"anorith",evoLevel:40,eggGroups:["Water 3"]}, feebas:{num:349,species:"Feebas",types:["Water"],baseStats:{hp:20,atk:15,def:20,spa:10,spd:55,spe:80},abilities:{0:"Swift Swim",1:"Oblivious",H:"Adaptability"},heightm:0.6,weightkg:7.4,color:"Brown",evos:["milotic"],eggGroups:["Water 1","Dragon"]}, milotic:{num:350,species:"Milotic",types:["Water"],baseStats:{hp:95,atk:60,def:79,spa:100,spd:125,spe:81},abilities:{0:"Marvel Scale",1:"Competitive",H:"Cute Charm"},heightm:6.2,weightkg:162,color:"Pink",prevo:"feebas",evoLevel:1,eggGroups:["Water 1","Dragon"]}, castform:{num:351,species:"Castform",types:["Normal"],baseStats:{hp:70,atk:70,def:70,spa:70,spd:70,spe:70},abilities:{0:"Forecast"},heightm:0.3,weightkg:0.8,color:"White",eggGroups:["Fairy","Amorphous"],otherFormes:["castformsunny","castformrainy","castformsnowy"]}, castformsunny:{num:351,species:"Castform-Sunny",baseSpecies:"Castform",forme:"Sunny",formeLetter:"S",types:["Fire"],baseStats:{hp:70,atk:70,def:70,spa:70,spd:70,spe:70},abilities:{0:"Forecast"},heightm:0.3,weightkg:0.8,color:"White",eggGroups:["Fairy","Amorphous"]}, castformrainy:{num:351,species:"Castform-Rainy",baseSpecies:"Castform",forme:"Rainy",formeLetter:"R",types:["Water"],baseStats:{hp:70,atk:70,def:70,spa:70,spd:70,spe:70},abilities:{0:"Forecast"},heightm:0.3,weightkg:0.8,color:"White",eggGroups:["Fairy","Amorphous"]}, castformsnowy:{num:351,species:"Castform-Snowy",baseSpecies:"Castform",forme:"Snowy",formeLetter:"S",types:["Ice"],baseStats:{hp:70,atk:70,def:70,spa:70,spd:70,spe:70},abilities:{0:"Forecast"},heightm:0.3,weightkg:0.8,color:"White",eggGroups:["Fairy","Amorphous"]}, kecleon:{num:352,species:"Kecleon",types:["Normal"],baseStats:{hp:60,atk:90,def:70,spa:60,spd:120,spe:40},abilities:{0:"Color Change",H:"Protean"},heightm:1,weightkg:22,color:"Green",eggGroups:["Field"]}, shuppet:{num:353,species:"Shuppet",types:["Ghost"],baseStats:{hp:44,atk:75,def:35,spa:63,spd:33,spe:45},abilities:{0:"Insomnia",1:"Frisk",H:"Cursed Body"},heightm:0.6,weightkg:2.3,color:"Black",evos:["banette"],eggGroups:["Amorphous"]}, banette:{num:354,species:"Banette",types:["Ghost"],baseStats:{hp:64,atk:115,def:65,spa:83,spd:63,spe:65},abilities:{0:"Insomnia",1:"Frisk",H:"Cursed Body"},heightm:1.1,weightkg:12.5,color:"Black",prevo:"shuppet",evoLevel:37,eggGroups:["Amorphous"],otherFormes:["banettemega"]}, banettemega:{num:354,species:"Banette-Mega",baseSpecies:"Banette",forme:"Mega",formeLetter:"M",types:["Ghost"],baseStats:{hp:64,atk:165,def:75,spa:93,spd:83,spe:75},abilities:{0:"Prankster"},heightm:1.2,weightkg:13,color:"Black",prevo:"shuppet",evoLevel:37,eggGroups:["Amorphous"]}, duskull:{num:355,species:"Duskull",types:["Ghost"],baseStats:{hp:20,atk:40,def:90,spa:30,spd:90,spe:25},abilities:{0:"Levitate",H:"Frisk"},heightm:0.8,weightkg:15,color:"Black",evos:["dusclops"],eggGroups:["Amorphous"]}, dusclops:{num:356,species:"Dusclops",types:["Ghost"],baseStats:{hp:40,atk:70,def:130,spa:60,spd:130,spe:25},abilities:{0:"Pressure",H:"Frisk"},heightm:1.6,weightkg:30.6,color:"Black",prevo:"duskull",evos:["dusknoir"],evoLevel:37,eggGroups:["Amorphous"]}, tropius:{num:357,species:"Tropius",types:["Grass","Flying"],baseStats:{hp:99,atk:68,def:83,spa:72,spd:87,spe:51},abilities:{0:"Chlorophyll",1:"Solar Power",H:"Harvest"},heightm:2,weightkg:100,color:"Green",eggGroups:["Monster","Grass"]}, chimecho:{num:358,species:"Chimecho",types:["Psychic"],baseStats:{hp:65,atk:50,def:70,spa:95,spd:80,spe:65},abilities:{0:"Levitate"},heightm:0.6,weightkg:1,color:"Blue",prevo:"chingling",evoLevel:1,eggGroups:["Amorphous"]}, absol:{num:359,species:"Absol",types:["Dark"],baseStats:{hp:65,atk:130,def:60,spa:75,spd:60,spe:75},abilities:{0:"Pressure",1:"Super Luck",H:"Justified"},heightm:1.2,weightkg:47,color:"White",eggGroups:["Field"],otherFormes:["absolmega"]}, absolmega:{num:359,species:"Absol-Mega",baseSpecies:"Absol",forme:"Mega",formeLetter:"M",types:["Dark"],baseStats:{hp:65,atk:150,def:60,spa:115,spd:60,spe:115},abilities:{0:"Magic Bounce"},heightm:1.2,weightkg:49,color:"White",eggGroups:["Field"]}, wynaut:{num:360,species:"Wynaut",types:["Psychic"],baseStats:{hp:95,atk:23,def:48,spa:23,spd:48,spe:23},abilities:{0:"Shadow Tag",H:"Telepathy"},heightm:0.6,weightkg:14,color:"Blue",evos:["wobbuffet"],eggGroups:["Undiscovered"]}, snorunt:{num:361,species:"Snorunt",types:["Ice"],baseStats:{hp:50,atk:50,def:50,spa:50,spd:50,spe:50},abilities:{0:"Inner Focus",1:"Ice Body",H:"Moody"},heightm:0.7,weightkg:16.8,color:"Gray",evos:["glalie","froslass"],eggGroups:["Fairy","Mineral"]}, glalie:{num:362,species:"Glalie",types:["Ice"],baseStats:{hp:80,atk:80,def:80,spa:80,spd:80,spe:80},abilities:{0:"Inner Focus",1:"Ice Body",H:"Moody"},heightm:1.5,weightkg:256.5,color:"Gray",prevo:"snorunt",evoLevel:42,eggGroups:["Fairy","Mineral"]}, spheal:{num:363,species:"Spheal",types:["Ice","Water"],baseStats:{hp:70,atk:40,def:50,spa:55,spd:50,spe:25},abilities:{0:"Thick Fat",1:"Ice Body",H:"Oblivious"},heightm:0.8,weightkg:39.5,color:"Blue",evos:["sealeo"],eggGroups:["Water 1","Field"]}, sealeo:{num:364,species:"Sealeo",types:["Ice","Water"],baseStats:{hp:90,atk:60,def:70,spa:75,spd:70,spe:45},abilities:{0:"Thick Fat",1:"Ice Body",H:"Oblivious"},heightm:1.1,weightkg:87.6,color:"Blue",prevo:"spheal",evos:["walrein"],evoLevel:32,eggGroups:["Water 1","Field"]}, walrein:{num:365,species:"Walrein",types:["Ice","Water"],baseStats:{hp:110,atk:80,def:90,spa:95,spd:90,spe:65},abilities:{0:"Thick Fat",1:"Ice Body",H:"Oblivious"},heightm:1.4,weightkg:150.6,color:"Blue",prevo:"sealeo",evoLevel:44,eggGroups:["Water 1","Field"]}, clamperl:{num:366,species:"Clamperl",types:["Water"],baseStats:{hp:35,atk:64,def:85,spa:74,spd:55,spe:32},abilities:{0:"Shell Armor",H:"Rattled"},heightm:0.4,weightkg:52.5,color:"Blue",evos:["huntail","gorebyss"],eggGroups:["Water 1"]}, huntail:{num:367,species:"Huntail",types:["Water"],baseStats:{hp:55,atk:104,def:105,spa:94,spd:75,spe:52},abilities:{0:"Swift Swim",H:"Water Veil"},heightm:1.7,weightkg:27,color:"Blue",prevo:"clamperl",evoLevel:1,eggGroups:["Water 1"]}, gorebyss:{num:368,species:"Gorebyss",types:["Water"],baseStats:{hp:55,atk:84,def:105,spa:114,spd:75,spe:52},abilities:{0:"Swift Swim",H:"Hydration"},heightm:1.8,weightkg:22.6,color:"Pink",prevo:"clamperl",evoLevel:1,eggGroups:["Water 1"]}, relicanth:{num:369,species:"Relicanth",types:["Water","Rock"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:100,atk:90,def:130,spa:45,spd:65,spe:55},abilities:{0:"Swift Swim",1:"Rock Head",H:"Sturdy"},heightm:1,weightkg:23.4,color:"Gray",eggGroups:["Water 1","Water 2"]}, luvdisc:{num:370,species:"Luvdisc",types:["Water"],genderRatio:{M:0.25,F:0.75},baseStats:{hp:43,atk:30,def:55,spa:40,spd:65,spe:97},abilities:{0:"Swift Swim",H:"Hydration"},heightm:0.6,weightkg:8.7,color:"Pink",eggGroups:["Water 2"]}, bagon:{num:371,species:"Bagon",types:["Dragon"],baseStats:{hp:45,atk:75,def:60,spa:40,spd:30,spe:50},abilities:{0:"Rock Head",H:"Sheer Force"},heightm:0.6,weightkg:42.1,color:"Blue",evos:["shelgon"],eggGroups:["Dragon"]}, shelgon:{num:372,species:"Shelgon",types:["Dragon"],baseStats:{hp:65,atk:95,def:100,spa:60,spd:50,spe:50},abilities:{0:"Rock Head",H:"Overcoat"},heightm:1.1,weightkg:110.5,color:"White",prevo:"bagon",evos:["salamence"],evoLevel:30,eggGroups:["Dragon"]}, salamence:{num:373,species:"Salamence",types:["Dragon","Flying"],baseStats:{hp:95,atk:135,def:80,spa:110,spd:80,spe:100},abilities:{0:"Intimidate",H:"Moxie"},heightm:1.5,weightkg:102.6,color:"Blue",prevo:"shelgon",evoLevel:50,eggGroups:["Dragon"]}, beldum:{num:374,species:"Beldum",types:["Steel","Psychic"],gender:"N",baseStats:{hp:40,atk:55,def:80,spa:35,spd:60,spe:30},abilities:{0:"Clear Body",H:"Light Metal"},heightm:0.6,weightkg:95.2,color:"Blue",evos:["metang"],eggGroups:["Mineral"]}, metang:{num:375,species:"Metang",types:["Steel","Psychic"],gender:"N",baseStats:{hp:60,atk:75,def:100,spa:55,spd:80,spe:50},abilities:{0:"Clear Body",H:"Light Metal"},heightm:1.2,weightkg:202.5,color:"Blue",prevo:"beldum",evos:["metagross"],evoLevel:20,eggGroups:["Mineral"]}, metagross:{num:376,species:"Metagross",types:["Steel","Psychic"],gender:"N",baseStats:{hp:80,atk:135,def:130,spa:95,spd:90,spe:70},abilities:{0:"Clear Body",H:"Light Metal"},heightm:1.6,weightkg:550,color:"Blue",prevo:"metang",evoLevel:45,eggGroups:["Mineral"]}, regirock:{num:377,species:"Regirock",types:["Rock"],gender:"N",baseStats:{hp:80,atk:100,def:200,spa:50,spd:100,spe:50},abilities:{0:"Clear Body",H:"Sturdy"},heightm:1.7,weightkg:230,color:"Brown",eggGroups:["Undiscovered"]}, regice:{num:378,species:"Regice",types:["Ice"],gender:"N",baseStats:{hp:80,atk:50,def:100,spa:100,spd:200,spe:50},abilities:{0:"Clear Body",H:"Ice Body"},heightm:1.8,weightkg:175,color:"Blue",eggGroups:["Undiscovered"]}, registeel:{num:379,species:"Registeel",types:["Steel"],gender:"N",baseStats:{hp:80,atk:75,def:150,spa:75,spd:150,spe:50},abilities:{0:"Clear Body",H:"Light Metal"},heightm:1.9,weightkg:205,color:"Gray",eggGroups:["Undiscovered"]}, latias:{num:380,species:"Latias",types:["Dragon","Psychic"],gender:"F",baseStats:{hp:80,atk:80,def:90,spa:110,spd:130,spe:110},abilities:{0:"Levitate"},heightm:1.4,weightkg:40,color:"Red",eggGroups:["Undiscovered"],otherFormes:["latiasmega"]}, latiasmega:{num:380,species:"Latias-Mega",baseSpecies:"Latias",forme:"Mega",formeLetter:"M",types:["Dragon","Psychic"],gender:"F",baseStats:{hp:80,atk:100,def:120,spa:140,spd:150,spe:110},abilities:{0:"Levitate"},heightm:1.8,weightkg:52,color:"Red",eggGroups:["Undiscovered"]}, latios:{num:381,species:"Latios",types:["Dragon","Psychic"],gender:"M",baseStats:{hp:80,atk:90,def:80,spa:130,spd:110,spe:110},abilities:{0:"Levitate"},heightm:2,weightkg:60,color:"Blue",eggGroups:["Undiscovered"],otherFormes:["latiosmega"]}, latiosmega:{num:381,species:"Latios-Mega",baseSpecies:"Latios",forme:"Mega",formeLetter:"M",types:["Dragon","Psychic"],gender:"M",baseStats:{hp:80,atk:130,def:100,spa:160,spd:120,spe:110},abilities:{0:"Levitate"},heightm:2.3,weightkg:70,color:"Blue",eggGroups:["Undiscovered"]}, kyogre:{num:382,species:"Kyogre",types:["Water"],gender:"N",baseStats:{hp:100,atk:100,def:90,spa:150,spd:140,spe:90},abilities:{0:"Drizzle"},heightm:4.5,weightkg:352,color:"Blue",eggGroups:["Undiscovered"]}, groudon:{num:383,species:"Groudon",types:["Ground"],gender:"N",baseStats:{hp:100,atk:150,def:140,spa:100,spd:90,spe:90},abilities:{0:"Drought"},heightm:3.5,weightkg:950,color:"Red",eggGroups:["Undiscovered"]}, rayquaza:{num:384,species:"Rayquaza",types:["Dragon","Flying"],gender:"N",baseStats:{hp:105,atk:150,def:90,spa:150,spd:90,spe:95},abilities:{0:"Air Lock"},heightm:7,weightkg:206.5,color:"Green",eggGroups:["Undiscovered"]}, jirachi:{num:385,species:"Jirachi",types:["Steel","Psychic"],gender:"N",baseStats:{hp:100,atk:100,def:100,spa:100,spd:100,spe:100},abilities:{0:"Serene Grace"},heightm:0.3,weightkg:1.1,color:"Yellow",eggGroups:["Undiscovered"]}, deoxys:{num:386,species:"Deoxys",baseForme:"Normal",types:["Psychic"],gender:"N",baseStats:{hp:50,atk:150,def:50,spa:150,spd:50,spe:150},abilities:{0:"Pressure"},heightm:1.7,weightkg:60.8,color:"Red",eggGroups:["Undiscovered"],otherFormes:["deoxysattack","deoxysdefense","deoxysspeed"]}, deoxysattack:{num:386,species:"Deoxys-Attack",baseSpecies:"Deoxys",forme:"Attack",formeLetter:"A",types:["Psychic"],gender:"N",baseStats:{hp:50,atk:180,def:20,spa:180,spd:20,spe:150},abilities:{0:"Pressure"},heightm:1.7,weightkg:60.8,color:"Red",eggGroups:["Undiscovered"]}, deoxysdefense:{num:386,species:"Deoxys-Defense",baseSpecies:"Deoxys",forme:"Defense",formeLetter:"D",types:["Psychic"],gender:"N",baseStats:{hp:50,atk:70,def:160,spa:70,spd:160,spe:90},abilities:{0:"Pressure"},heightm:1.7,weightkg:60.8,color:"Red",eggGroups:["Undiscovered"]}, deoxysspeed:{num:386,species:"Deoxys-Speed",baseSpecies:"Deoxys",forme:"Speed",formeLetter:"S",types:["Psychic"],gender:"N",baseStats:{hp:50,atk:95,def:90,spa:95,spd:90,spe:180},abilities:{0:"Pressure"},heightm:1.7,weightkg:60.8,color:"Red",eggGroups:["Undiscovered"]}, turtwig:{num:387,species:"Turtwig",types:["Grass"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:55,atk:68,def:64,spa:45,spd:55,spe:31},abilities:{0:"Overgrow",H:"Shell Armor"},heightm:0.4,weightkg:10.2,color:"Green",evos:["grotle"],eggGroups:["Monster","Grass"]}, grotle:{num:388,species:"Grotle",types:["Grass"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:75,atk:89,def:85,spa:55,spd:65,spe:36},abilities:{0:"Overgrow",H:"Shell Armor"},heightm:1.1,weightkg:97,color:"Green",prevo:"turtwig",evos:["torterra"],evoLevel:18,eggGroups:["Monster","Grass"]}, torterra:{num:389,species:"Torterra",types:["Grass","Ground"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:95,atk:109,def:105,spa:75,spd:85,spe:56},abilities:{0:"Overgrow",H:"Shell Armor"},heightm:2.2,weightkg:310,color:"Green",prevo:"grotle",evoLevel:32,eggGroups:["Monster","Grass"]}, chimchar:{num:390,species:"Chimchar",types:["Fire"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:44,atk:58,def:44,spa:58,spd:44,spe:61},abilities:{0:"Blaze",H:"Iron Fist"},heightm:0.5,weightkg:6.2,color:"Brown",evos:["monferno"],eggGroups:["Field","Human-Like"]}, monferno:{num:391,species:"Monferno",types:["Fire","Fighting"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:64,atk:78,def:52,spa:78,spd:52,spe:81},abilities:{0:"Blaze",H:"Iron Fist"},heightm:0.9,weightkg:22,color:"Brown",prevo:"chimchar",evos:["infernape"],evoLevel:14,eggGroups:["Field","Human-Like"]}, infernape:{num:392,species:"Infernape",types:["Fire","Fighting"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:76,atk:104,def:71,spa:104,spd:71,spe:108},abilities:{0:"Blaze",H:"Iron Fist"},heightm:1.2,weightkg:55,color:"Brown",prevo:"monferno",evoLevel:36,eggGroups:["Field","Human-Like"]}, piplup:{num:393,species:"Piplup",types:["Water"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:53,atk:51,def:53,spa:61,spd:56,spe:40},abilities:{0:"Torrent",H:"Defiant"},heightm:0.4,weightkg:5.2,color:"Blue",evos:["prinplup"],eggGroups:["Water 1","Field"]}, prinplup:{num:394,species:"Prinplup",types:["Water"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:64,atk:66,def:68,spa:81,spd:76,spe:50},abilities:{0:"Torrent",H:"Defiant"},heightm:0.8,weightkg:23,color:"Blue",prevo:"piplup",evos:["empoleon"],evoLevel:16,eggGroups:["Water 1","Field"]}, empoleon:{num:395,species:"Empoleon",types:["Water","Steel"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:84,atk:86,def:88,spa:111,spd:101,spe:60},abilities:{0:"Torrent",H:"Defiant"},heightm:1.7,weightkg:84.5,color:"Blue",prevo:"prinplup",evoLevel:36,eggGroups:["Water 1","Field"]}, starly:{num:396,species:"Starly",types:["Normal","Flying"],baseStats:{hp:40,atk:55,def:30,spa:30,spd:30,spe:60},abilities:{0:"Keen Eye",H:"Reckless"},heightm:0.3,weightkg:2,color:"Brown",evos:["staravia"],eggGroups:["Flying"]}, staravia:{num:397,species:"Staravia",types:["Normal","Flying"],baseStats:{hp:55,atk:75,def:50,spa:40,spd:40,spe:80},abilities:{0:"Intimidate",H:"Reckless"},heightm:0.6,weightkg:15.5,color:"Brown",prevo:"starly",evos:["staraptor"],evoLevel:14,eggGroups:["Flying"]}, staraptor:{num:398,species:"Staraptor",types:["Normal","Flying"],baseStats:{hp:85,atk:120,def:70,spa:50,spd:60,spe:100},abilities:{0:"Intimidate",H:"Reckless"},heightm:1.2,weightkg:24.9,color:"Brown",prevo:"staravia",evoLevel:34,eggGroups:["Flying"]}, bidoof:{num:399,species:"Bidoof",types:["Normal"],baseStats:{hp:59,atk:45,def:40,spa:35,spd:40,spe:31},abilities:{0:"Simple",1:"Unaware",H:"Moody"},heightm:0.5,weightkg:20,color:"Brown",evos:["bibarel"],eggGroups:["Water 1","Field"]}, bibarel:{num:400,species:"Bibarel",types:["Normal","Water"],baseStats:{hp:79,atk:85,def:60,spa:55,spd:60,spe:71},abilities:{0:"Simple",1:"Unaware",H:"Moody"},heightm:1,weightkg:31.5,color:"Brown",prevo:"bidoof",evoLevel:15,eggGroups:["Water 1","Field"]}, kricketot:{num:401,species:"Kricketot",types:["Bug"],baseStats:{hp:37,atk:25,def:41,spa:25,spd:41,spe:25},abilities:{0:"Shed Skin",H:"Run Away"},heightm:0.3,weightkg:2.2,color:"Red",evos:["kricketune"],eggGroups:["Bug"]}, kricketune:{num:402,species:"Kricketune",types:["Bug"],baseStats:{hp:77,atk:85,def:51,spa:55,spd:51,spe:65},abilities:{0:"Swarm",H:"Technician"},heightm:1,weightkg:25.5,color:"Red",prevo:"kricketot",evoLevel:10,eggGroups:["Bug"]}, shinx:{num:403,species:"Shinx",types:["Electric"],baseStats:{hp:45,atk:65,def:34,spa:40,spd:34,spe:45},abilities:{0:"Rivalry",1:"Intimidate",H:"Guts"},heightm:0.5,weightkg:9.5,color:"Blue",evos:["luxio"],eggGroups:["Field"]}, luxio:{num:404,species:"Luxio",types:["Electric"],baseStats:{hp:60,atk:85,def:49,spa:60,spd:49,spe:60},abilities:{0:"Rivalry",1:"Intimidate",H:"Guts"},heightm:0.9,weightkg:30.5,color:"Blue",prevo:"shinx",evos:["luxray"],evoLevel:15,eggGroups:["Field"]}, luxray:{num:405,species:"Luxray",types:["Electric"],baseStats:{hp:80,atk:120,def:79,spa:95,spd:79,spe:70},abilities:{0:"Rivalry",1:"Intimidate",H:"Guts"},heightm:1.4,weightkg:42,color:"Blue",prevo:"luxio",evoLevel:30,eggGroups:["Field"]}, budew:{num:406,species:"Budew",types:["Grass","Poison"],baseStats:{hp:40,atk:30,def:35,spa:50,spd:70,spe:55},abilities:{0:"Natural Cure",1:"Poison Point",H:"Leaf Guard"},heightm:0.2,weightkg:1.2,color:"Green",evos:["roselia"],eggGroups:["Undiscovered"]}, roserade:{num:407,species:"Roserade",types:["Grass","Poison"],baseStats:{hp:60,atk:70,def:65,spa:125,spd:105,spe:90},abilities:{0:"Natural Cure",1:"Poison Point",H:"Technician"},heightm:0.9,weightkg:14.5,color:"Green",prevo:"roselia",evoLevel:1,eggGroups:["Fairy","Grass"]}, cranidos:{num:408,species:"Cranidos",types:["Rock"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:67,atk:125,def:40,spa:30,spd:30,spe:58},abilities:{0:"Mold Breaker",H:"Sheer Force"},heightm:0.9,weightkg:31.5,color:"Blue",evos:["rampardos"],eggGroups:["Monster"]}, rampardos:{num:409,species:"Rampardos",types:["Rock"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:97,atk:165,def:60,spa:65,spd:50,spe:58},abilities:{0:"Mold Breaker",H:"Sheer Force"},heightm:1.6,weightkg:102.5,color:"Blue",prevo:"cranidos",evoLevel:30,eggGroups:["Monster"]}, shieldon:{num:410,species:"Shieldon",types:["Rock","Steel"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:30,atk:42,def:118,spa:42,spd:88,spe:30},abilities:{0:"Sturdy",H:"Soundproof"},heightm:0.5,weightkg:57,color:"Gray",evos:["bastiodon"],eggGroups:["Monster"]}, bastiodon:{num:411,species:"Bastiodon",types:["Rock","Steel"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:60,atk:52,def:168,spa:47,spd:138,spe:30},abilities:{0:"Sturdy",H:"Soundproof"},heightm:1.3,weightkg:149.5,color:"Gray",prevo:"shieldon",evoLevel:30,eggGroups:["Monster"]}, burmy:{num:412,species:"Burmy",baseForme:"Grass",types:["Bug"],baseStats:{hp:40,atk:29,def:45,spa:29,spd:45,spe:36},abilities:{0:"Shed Skin",H:"Overcoat"},heightm:0.2,weightkg:3.4,color:"Gray",evos:["wormadam","wormadamsandy","wormadamtrash","mothim"],eggGroups:["Bug"],otherForms:["burmysandy","burmytrash"]}, wormadam:{num:413,species:"Wormadam",baseForme:"Grass",types:["Bug","Grass"],gender:"F",baseStats:{hp:60,atk:59,def:85,spa:79,spd:105,spe:36},abilities:{0:"Anticipation",H:"Overcoat"},heightm:0.5,weightkg:6.5,color:"Gray",prevo:"burmy",evoLevel:20,eggGroups:["Bug"],otherFormes:["wormadamsandy","wormadamtrash"]}, wormadamsandy:{num:413,species:"Wormadam-Sandy",baseSpecies:"Wormadam",forme:"Sandy",formeLetter:"G",types:["Bug","Ground"],gender:"F",baseStats:{hp:60,atk:79,def:105,spa:59,spd:85,spe:36},abilities:{0:"Anticipation",H:"Overcoat"},heightm:0.5,weightkg:6.5,color:"Gray",prevo:"burmy",evoLevel:20,eggGroups:["Bug"]}, wormadamtrash:{num:413,species:"Wormadam-Trash",baseSpecies:"Wormadam",forme:"Trash",formeLetter:"S",types:["Bug","Steel"],gender:"F",baseStats:{hp:60,atk:69,def:95,spa:69,spd:95,spe:36},abilities:{0:"Anticipation",H:"Overcoat"},heightm:0.5,weightkg:6.5,color:"Gray",prevo:"burmy",evoLevel:20,eggGroups:["Bug"]}, mothim:{num:414,species:"Mothim",types:["Bug","Flying"],gender:"M",baseStats:{hp:70,atk:94,def:50,spa:94,spd:50,spe:66},abilities:{0:"Swarm",H:"Tinted Lens"},heightm:0.9,weightkg:23.3,color:"Yellow",prevo:"burmy",evoLevel:20,eggGroups:["Bug"]}, combee:{num:415,species:"Combee",types:["Bug","Flying"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:30,atk:30,def:42,spa:30,spd:42,spe:70},abilities:{0:"Honey Gather",H:"Hustle"},heightm:0.3,weightkg:5.5,color:"Yellow",evos:["vespiquen"],eggGroups:["Bug"]}, vespiquen:{num:416,species:"Vespiquen",types:["Bug","Flying"],gender:"F",baseStats:{hp:70,atk:80,def:102,spa:80,spd:102,spe:40},abilities:{0:"Pressure",H:"Unnerve"},heightm:1.2,weightkg:38.5,color:"Yellow",prevo:"combee",evoLevel:21,eggGroups:["Bug"]}, pachirisu:{num:417,species:"Pachirisu",types:["Electric"],baseStats:{hp:60,atk:45,def:70,spa:45,spd:90,spe:95},abilities:{0:"Run Away",1:"Pickup",H:"Volt Absorb"},heightm:0.4,weightkg:3.9,color:"White",eggGroups:["Field","Fairy"]}, buizel:{num:418,species:"Buizel",types:["Water"],baseStats:{hp:55,atk:65,def:35,spa:60,spd:30,spe:85},abilities:{0:"Swift Swim",H:"Water Veil"},heightm:0.7,weightkg:29.5,color:"Brown",evos:["floatzel"],eggGroups:["Water 1","Field"]}, floatzel:{num:419,species:"Floatzel",types:["Water"],baseStats:{hp:85,atk:105,def:55,spa:85,spd:50,spe:115},abilities:{0:"Swift Swim",H:"Water Veil"},heightm:1.1,weightkg:33.5,color:"Brown",prevo:"buizel",evoLevel:26,eggGroups:["Water 1","Field"]}, cherubi:{num:420,species:"Cherubi",types:["Grass"],baseStats:{hp:45,atk:35,def:45,spa:62,spd:53,spe:35},abilities:{0:"Chlorophyll"},heightm:0.4,weightkg:3.3,color:"Pink",evos:["cherrim"],eggGroups:["Fairy","Grass"]}, cherrim:{num:421,species:"Cherrim",baseForme:"Overcast",types:["Grass"],baseStats:{hp:70,atk:60,def:70,spa:87,spd:78,spe:85},abilities:{0:"Flower Gift"},heightm:0.5,weightkg:9.3,color:"Pink",prevo:"cherubi",evoLevel:25,eggGroups:["Fairy","Grass"],otherFormes:["cherrimsunshine"]}, cherrimsunshine:{num:421,species:"Cherrim-Sunshine",baseSpecies:"Cherrim",forme:"Sunshine",formeLetter:"S",types:["Grass"],baseStats:{hp:70,atk:60,def:70,spa:87,spd:78,spe:85},abilities:{0:"Flower Gift"},heightm:0.5,weightkg:9.3,color:"Pink",prevo:"cherubi",evoLevel:25,eggGroups:["Fairy","Grass"]}, shellos:{num:422,species:"Shellos",baseForme:"West",types:["Water"],baseStats:{hp:76,atk:48,def:48,spa:57,spd:62,spe:34},abilities:{0:"Sticky Hold",1:"Storm Drain",H:"Sand Force"},heightm:0.3,weightkg:6.3,color:"Purple",evos:["gastrodon"],eggGroups:["Water 1","Amorphous"],otherForms:["shelloseast"]}, gastrodon:{num:423,species:"Gastrodon",baseForme:"West",types:["Water","Ground"],baseStats:{hp:111,atk:83,def:68,spa:92,spd:82,spe:39},abilities:{0:"Sticky Hold",1:"Storm Drain",H:"Sand Force"},heightm:0.9,weightkg:29.9,color:"Purple",prevo:"shellos",evoLevel:30,eggGroups:["Water 1","Amorphous"],otherForms:["gastrodoneast"]}, ambipom:{num:424,species:"Ambipom",types:["Normal"],baseStats:{hp:75,atk:100,def:66,spa:60,spd:66,spe:115},abilities:{0:"Technician",1:"Pickup",H:"Skill Link"},heightm:1.2,weightkg:20.3,color:"Purple",prevo:"aipom",evoLevel:2,evoMove:"Double Hit",eggGroups:["Field"]}, drifloon:{num:425,species:"Drifloon",types:["Ghost","Flying"],baseStats:{hp:90,atk:50,def:34,spa:60,spd:44,spe:70},abilities:{0:"Aftermath",1:"Unburden",H:"Flare Boost"},heightm:0.4,weightkg:1.2,color:"Purple",evos:["drifblim"],eggGroups:["Amorphous"]}, drifblim:{num:426,species:"Drifblim",types:["Ghost","Flying"],baseStats:{hp:150,atk:80,def:44,spa:90,spd:54,spe:80},abilities:{0:"Aftermath",1:"Unburden",H:"Flare Boost"},heightm:1.2,weightkg:15,color:"Purple",prevo:"drifloon",evoLevel:28,eggGroups:["Amorphous"]}, buneary:{num:427,species:"Buneary",types:["Normal"],baseStats:{hp:55,atk:66,def:44,spa:44,spd:56,spe:85},abilities:{0:"Run Away",1:"Klutz",H:"Limber"},heightm:0.4,weightkg:5.5,color:"Brown",evos:["lopunny"],eggGroups:["Field","Human-Like"]}, lopunny:{num:428,species:"Lopunny",types:["Normal"],baseStats:{hp:65,atk:76,def:84,spa:54,spd:96,spe:105},abilities:{0:"Cute Charm",1:"Klutz",H:"Limber"},heightm:1.2,weightkg:33.3,color:"Brown",prevo:"buneary",evoLevel:2,eggGroups:["Field","Human-Like"]}, mismagius:{num:429,species:"Mismagius",types:["Ghost"],baseStats:{hp:60,atk:60,def:60,spa:105,spd:105,spe:105},abilities:{0:"Levitate"},heightm:0.9,weightkg:4.4,color:"Purple",prevo:"misdreavus",evoLevel:1,eggGroups:["Amorphous"]}, honchkrow:{num:430,species:"Honchkrow",types:["Dark","Flying"],baseStats:{hp:100,atk:125,def:52,spa:105,spd:52,spe:71},abilities:{0:"Insomnia",1:"Super Luck",H:"Moxie"},heightm:0.9,weightkg:27.3,color:"Black",prevo:"murkrow",evoLevel:1,eggGroups:["Flying"]}, glameow:{num:431,species:"Glameow",types:["Normal"],genderRatio:{M:0.25,F:0.75},baseStats:{hp:49,atk:55,def:42,spa:42,spd:37,spe:85},abilities:{0:"Limber",1:"Own Tempo",H:"Keen Eye"},heightm:0.5,weightkg:3.9,color:"Gray",evos:["purugly"],eggGroups:["Field"]}, purugly:{num:432,species:"Purugly",types:["Normal"],genderRatio:{M:0.25,F:0.75},baseStats:{hp:71,atk:82,def:64,spa:64,spd:59,spe:112},abilities:{0:"Thick Fat",1:"Own Tempo",H:"Defiant"},heightm:1,weightkg:43.8,color:"Gray",prevo:"glameow",evoLevel:38,eggGroups:["Field"]}, chingling:{num:433,species:"Chingling",types:["Psychic"],baseStats:{hp:45,atk:30,def:50,spa:65,spd:50,spe:45},abilities:{0:"Levitate"},heightm:0.2,weightkg:0.6,color:"Yellow",evos:["chimecho"],eggGroups:["Undiscovered"]}, stunky:{num:434,species:"Stunky",types:["Poison","Dark"],baseStats:{hp:63,atk:63,def:47,spa:41,spd:41,spe:74},abilities:{0:"Stench",1:"Aftermath",H:"Keen Eye"},heightm:0.4,weightkg:19.2,color:"Purple",evos:["skuntank"],eggGroups:["Field"]}, skuntank:{num:435,species:"Skuntank",types:["Poison","Dark"],baseStats:{hp:103,atk:93,def:67,spa:71,spd:61,spe:84},abilities:{0:"Stench",1:"Aftermath",H:"Keen Eye"},heightm:1,weightkg:38,color:"Purple",prevo:"stunky",evoLevel:34,eggGroups:["Field"]}, bronzor:{num:436,species:"Bronzor",types:["Steel","Psychic"],gender:"N",baseStats:{hp:57,atk:24,def:86,spa:24,spd:86,spe:23},abilities:{0:"Levitate",1:"Heatproof",H:"Heavy Metal"},heightm:0.5,weightkg:60.5,color:"Green",evos:["bronzong"],eggGroups:["Mineral"]}, bronzong:{num:437,species:"Bronzong",types:["Steel","Psychic"],gender:"N",baseStats:{hp:67,atk:89,def:116,spa:79,spd:116,spe:33},abilities:{0:"Levitate",1:"Heatproof",H:"Heavy Metal"},heightm:1.3,weightkg:187,color:"Green",prevo:"bronzor",evoLevel:33,eggGroups:["Mineral"]}, bonsly:{num:438,species:"Bonsly",types:["Rock"],baseStats:{hp:50,atk:80,def:95,spa:10,spd:45,spe:10},abilities:{0:"Sturdy",1:"Rock Head",H:"Rattled"},heightm:0.5,weightkg:15,color:"Brown",evos:["sudowoodo"],eggGroups:["Undiscovered"]}, mimejr:{num:439,species:"Mime Jr.",types:["Psychic","Fairy"],baseStats:{hp:20,atk:25,def:45,spa:70,spd:90,spe:60},abilities:{0:"Soundproof",1:"Filter",H:"Technician"},heightm:0.6,weightkg:13,color:"Pink",evos:["mrmime"],eggGroups:["Undiscovered"]}, happiny:{num:440,species:"Happiny",types:["Normal"],gender:"F",baseStats:{hp:100,atk:5,def:5,spa:15,spd:65,spe:30},abilities:{0:"Natural Cure",1:"Serene Grace",H:"Friend Guard"},heightm:0.6,weightkg:24.4,color:"Pink",evos:["chansey"],eggGroups:["Undiscovered"]}, chatot:{num:441,species:"Chatot",types:["Normal","Flying"],baseStats:{hp:76,atk:65,def:45,spa:92,spd:42,spe:91},abilities:{0:"Keen Eye",1:"Tangled Feet",H:"Big Pecks"},heightm:0.5,weightkg:1.9,color:"Black",eggGroups:["Flying"]}, spiritomb:{num:442,species:"Spiritomb",types:["Ghost","Dark"],baseStats:{hp:50,atk:92,def:108,spa:92,spd:108,spe:35},abilities:{0:"Pressure",H:"Infiltrator"},heightm:1,weightkg:108,color:"Purple",eggGroups:["Amorphous"]}, gible:{num:443,species:"Gible",types:["Dragon","Ground"],baseStats:{hp:58,atk:70,def:45,spa:40,spd:45,spe:42},abilities:{0:"Sand Veil",H:"Rough Skin"},heightm:0.7,weightkg:20.5,color:"Blue",evos:["gabite"],eggGroups:["Monster","Dragon"]}, gabite:{num:444,species:"Gabite",types:["Dragon","Ground"],baseStats:{hp:68,atk:90,def:65,spa:50,spd:55,spe:82},abilities:{0:"Sand Veil",H:"Rough Skin"},heightm:1.4,weightkg:56,color:"Blue",prevo:"gible",evos:["garchomp"],evoLevel:24,eggGroups:["Monster","Dragon"]}, garchomp:{num:445,species:"Garchomp",types:["Dragon","Ground"],baseStats:{hp:108,atk:130,def:95,spa:80,spd:85,spe:102},abilities:{0:"Sand Veil",H:"Rough Skin"},heightm:1.9,weightkg:95,color:"Blue",prevo:"gabite",evoLevel:48,eggGroups:["Monster","Dragon"],otherFormes:["garchompmega"]}, garchompmega:{num:445,species:"Garchomp-Mega",baseSpecies:"Garchomp",forme:"Mega",formeLetter:"M",types:["Dragon","Ground"],baseStats:{hp:108,atk:170,def:115,spa:120,spd:95,spe:92},abilities:{0:"Sand Force"},heightm:1.9,weightkg:95,color:"Blue",prevo:"gabite",evoLevel:48,eggGroups:["Monster","Dragon"]}, munchlax:{num:446,species:"Munchlax",types:["Normal"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:135,atk:85,def:40,spa:40,spd:85,spe:5},abilities:{0:"Pickup",1:"Thick Fat",H:"Gluttony"},heightm:0.6,weightkg:105,color:"Black",evos:["snorlax"],eggGroups:["Undiscovered"]}, riolu:{num:447,species:"Riolu",types:["Fighting"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:40,atk:70,def:40,spa:35,spd:40,spe:60},abilities:{0:"Steadfast",1:"Inner Focus",H:"Prankster"},heightm:0.7,weightkg:20.2,color:"Blue",evos:["lucario"],eggGroups:["Undiscovered"]}, lucario:{num:448,species:"Lucario",types:["Fighting","Steel"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:70,atk:110,def:70,spa:115,spd:70,spe:90},abilities:{0:"Steadfast",1:"Inner Focus",H:"Justified"},heightm:1.2,weightkg:54,color:"Blue",prevo:"riolu",evoLevel:2,eggGroups:["Field","Human-Like"],otherFormes:["lucariomega"]}, lucariomega:{num:448,species:"Lucario-Mega",baseSpecies:"Lucario",forme:"Mega",formeLetter:"M",types:["Fighting","Steel"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:70,atk:145,def:88,spa:140,spd:70,spe:112},abilities:{0:"Adaptability"},heightm:1.3,weightkg:57.5,color:"Blue",prevo:"riolu",evoLevel:2,eggGroups:["Field","Human-Like"]}, hippopotas:{num:449,species:"Hippopotas",types:["Ground"],baseStats:{hp:68,atk:72,def:78,spa:38,spd:42,spe:32},abilities:{0:"Sand Stream",H:"Sand Force"},heightm:0.8,weightkg:49.5,color:"Brown",evos:["hippowdon"],eggGroups:["Field"]}, hippowdon:{num:450,species:"Hippowdon",types:["Ground"],baseStats:{hp:108,atk:112,def:118,spa:68,spd:72,spe:47},abilities:{0:"Sand Stream",H:"Sand Force"},heightm:2,weightkg:300,color:"Brown",prevo:"hippopotas",evoLevel:34,eggGroups:["Field"]}, skorupi:{num:451,species:"Skorupi",types:["Poison","Bug"],baseStats:{hp:40,atk:50,def:90,spa:30,spd:55,spe:65},abilities:{0:"Battle Armor",1:"Sniper",H:"Keen Eye"},heightm:0.8,weightkg:12,color:"Purple",evos:["drapion"],eggGroups:["Bug","Water 3"]}, drapion:{num:452,species:"Drapion",types:["Poison","Dark"],baseStats:{hp:70,atk:90,def:110,spa:60,spd:75,spe:95},abilities:{0:"Battle Armor",1:"Sniper",H:"Keen Eye"},heightm:1.3,weightkg:61.5,color:"Purple",prevo:"skorupi",evoLevel:40,eggGroups:["Bug","Water 3"]}, croagunk:{num:453,species:"Croagunk",types:["Poison","Fighting"],baseStats:{hp:48,atk:61,def:40,spa:61,spd:40,spe:50},abilities:{0:"Anticipation",1:"Dry Skin",H:"Poison Touch"},heightm:0.7,weightkg:23,color:"Blue",evos:["toxicroak"],eggGroups:["Human-Like"]}, toxicroak:{num:454,species:"Toxicroak",types:["Poison","Fighting"],baseStats:{hp:83,atk:106,def:65,spa:86,spd:65,spe:85},abilities:{0:"Anticipation",1:"Dry Skin",H:"Poison Touch"},heightm:1.3,weightkg:44.4,color:"Blue",prevo:"croagunk",evoLevel:37,eggGroups:["Human-Like"]}, carnivine:{num:455,species:"Carnivine",types:["Grass"],baseStats:{hp:74,atk:100,def:72,spa:90,spd:72,spe:46},abilities:{0:"Levitate"},heightm:1.4,weightkg:27,color:"Green",eggGroups:["Grass"]}, finneon:{num:456,species:"Finneon",types:["Water"],baseStats:{hp:49,atk:49,def:56,spa:49,spd:61,spe:66},abilities:{0:"Swift Swim",1:"Storm Drain",H:"Water Veil"},heightm:0.4,weightkg:7,color:"Blue",evos:["lumineon"],eggGroups:["Water 2"]}, lumineon:{num:457,species:"Lumineon",types:["Water"],baseStats:{hp:69,atk:69,def:76,spa:69,spd:86,spe:91},abilities:{0:"Swift Swim",1:"Storm Drain",H:"Water Veil"},heightm:1.2,weightkg:24,color:"Blue",prevo:"finneon",evoLevel:31,eggGroups:["Water 2"]}, mantyke:{num:458,species:"Mantyke",types:["Water","Flying"],baseStats:{hp:45,atk:20,def:50,spa:60,spd:120,spe:50},abilities:{0:"Swift Swim",1:"Water Absorb",H:"Water Veil"},heightm:1,weightkg:65,color:"Blue",evos:["mantine"],eggGroups:["Undiscovered"]}, snover:{num:459,species:"Snover",types:["Grass","Ice"],baseStats:{hp:60,atk:62,def:50,spa:62,spd:60,spe:40},abilities:{0:"Snow Warning",H:"Soundproof"},heightm:1,weightkg:50.5,color:"White",evos:["abomasnow"],eggGroups:["Monster","Grass"]}, abomasnow:{num:460,species:"Abomasnow",types:["Grass","Ice"],baseStats:{hp:90,atk:92,def:75,spa:92,spd:85,spe:60},abilities:{0:"Snow Warning",H:"Soundproof"},heightm:2.2,weightkg:135.5,color:"White",prevo:"snover",evoLevel:40,eggGroups:["Monster","Grass"],otherFormes:["abomasnowmega"]}, abomasnowmega:{num:460,species:"Abomasnow-Mega",baseSpecies:"Abomasnow",forme:"Mega",formeLetter:"M",types:["Grass","Ice"],baseStats:{hp:90,atk:132,def:105,spa:132,spd:105,spe:30},abilities:{0:"Snow Warning"},heightm:2.7,weightkg:185,color:"White",prevo:"snover",evoLevel:40,eggGroups:["Monster","Grass"]}, weavile:{num:461,species:"Weavile",types:["Dark","Ice"],baseStats:{hp:70,atk:120,def:65,spa:45,spd:85,spe:125},abilities:{0:"Pressure",H:"Pickpocket"},heightm:1.1,weightkg:34,color:"Black",prevo:"sneasel",evoLevel:2,eggGroups:["Field"]}, magnezone:{num:462,species:"Magnezone",types:["Electric","Steel"],gender:"N",baseStats:{hp:70,atk:70,def:115,spa:130,spd:90,spe:60},abilities:{0:"Magnet Pull",1:"Sturdy",H:"Analytic"},heightm:1.2,weightkg:180,color:"Gray",prevo:"magneton",evoLevel:31,eggGroups:["Mineral"]}, lickilicky:{num:463,species:"Lickilicky",types:["Normal"],baseStats:{hp:110,atk:85,def:95,spa:80,spd:95,spe:50},abilities:{0:"Own Tempo",1:"Oblivious",H:"Cloud Nine"},heightm:1.7,weightkg:140,color:"Pink",prevo:"lickitung",evoLevel:2,evoMove:"Rollout",eggGroups:["Monster"]}, rhyperior:{num:464,species:"Rhyperior",types:["Ground","Rock"],baseStats:{hp:115,atk:140,def:130,spa:55,spd:55,spe:40},abilities:{0:"Lightningrod",1:"Solid Rock",H:"Reckless"},heightm:2.4,weightkg:282.8,color:"Gray",prevo:"rhydon",evoLevel:42,eggGroups:["Monster","Field"]}, tangrowth:{num:465,species:"Tangrowth",types:["Grass"],baseStats:{hp:100,atk:100,def:125,spa:110,spd:50,spe:50},abilities:{0:"Chlorophyll",1:"Leaf Guard",H:"Regenerator"},heightm:2,weightkg:128.6,color:"Blue",prevo:"tangela",evoLevel:2,evoMove:"AncientPower",eggGroups:["Grass"]}, electivire:{num:466,species:"Electivire",types:["Electric"],genderRatio:{M:0.75,F:0.25},baseStats:{hp:75,atk:123,def:67,spa:95,spd:85,spe:95},abilities:{0:"Motor Drive",H:"Vital Spirit"},heightm:1.8,weightkg:138.6,color:"Yellow",prevo:"electabuzz",evoLevel:30,eggGroups:["Human-Like"]}, magmortar:{num:467,species:"Magmortar",types:["Fire"],genderRatio:{M:0.75,F:0.25},baseStats:{hp:75,atk:95,def:67,spa:125,spd:95,spe:83},abilities:{0:"Flame Body",H:"Vital Spirit"},heightm:1.6,weightkg:68,color:"Red",prevo:"magmar",evoLevel:30,eggGroups:["Human-Like"]}, togekiss:{num:468,species:"Togekiss",types:["Fairy","Flying"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:85,atk:50,def:95,spa:120,spd:115,spe:80},abilities:{0:"Hustle",1:"Serene Grace",H:"Super Luck"},heightm:1.5,weightkg:38,color:"White",prevo:"togetic",evoLevel:2,eggGroups:["Flying","Fairy"]}, yanmega:{num:469,species:"Yanmega",types:["Bug","Flying"],baseStats:{hp:86,atk:76,def:86,spa:116,spd:56,spe:95},abilities:{0:"Speed Boost",1:"Tinted Lens",H:"Frisk"},heightm:1.9,weightkg:51.5,color:"Green",prevo:"yanma",evoLevel:2,evoMove:"AncientPower",eggGroups:["Bug"]}, leafeon:{num:470,species:"Leafeon",types:["Grass"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:65,atk:110,def:130,spa:60,spd:65,spe:95},abilities:{0:"Leaf Guard",H:"Chlorophyll"},heightm:1,weightkg:25.5,color:"Green",prevo:"eevee",evoLevel:2,eggGroups:["Field"]}, glaceon:{num:471,species:"Glaceon",types:["Ice"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:65,atk:60,def:110,spa:130,spd:95,spe:65},abilities:{0:"Snow Cloak",H:"Ice Body"},heightm:0.8,weightkg:25.9,color:"Blue",prevo:"eevee",evoLevel:2,eggGroups:["Field"]}, gliscor:{num:472,species:"Gliscor",types:["Ground","Flying"],baseStats:{hp:75,atk:95,def:125,spa:45,spd:75,spe:95},abilities:{0:"Hyper Cutter",1:"Sand Veil",H:"Poison Heal"},heightm:2,weightkg:42.5,color:"Purple",prevo:"gligar",evoLevel:2,eggGroups:["Bug"]}, mamoswine:{num:473,species:"Mamoswine",types:["Ice","Ground"],baseStats:{hp:110,atk:130,def:80,spa:70,spd:60,spe:80},abilities:{0:"Oblivious",1:"Snow Cloak",H:"Thick Fat"},heightm:2.5,weightkg:291,color:"Brown",prevo:"piloswine",evoLevel:34,evoMove:"AncientPower",eggGroups:["Field"]}, porygonz:{num:474,species:"Porygon-Z",types:["Normal"],gender:"N",baseStats:{hp:85,atk:80,def:70,spa:135,spd:75,spe:90},abilities:{0:"Adaptability",1:"Download",H:"Analytic"},heightm:0.9,weightkg:34,color:"Red",prevo:"porygon2",evoLevel:1,eggGroups:["Mineral"]}, gallade:{num:475,species:"Gallade",types:["Psychic","Fighting"],gender:"M",baseStats:{hp:68,atk:125,def:65,spa:65,spd:115,spe:80},abilities:{0:"Steadfast",H:"Justified"},heightm:1.6,weightkg:52,color:"White",prevo:"kirlia",evoLevel:20,eggGroups:["Amorphous"]}, probopass:{num:476,species:"Probopass",types:["Rock","Steel"],baseStats:{hp:60,atk:55,def:145,spa:75,spd:150,spe:40},abilities:{0:"Sturdy",1:"Magnet Pull",H:"Sand Force"},heightm:1.4,weightkg:340,color:"Gray",prevo:"nosepass",evoLevel:2,eggGroups:["Mineral"]}, dusknoir:{num:477,species:"Dusknoir",types:["Ghost"],baseStats:{hp:45,atk:100,def:135,spa:65,spd:135,spe:45},abilities:{0:"Pressure",H:"Frisk"},heightm:2.2,weightkg:106.6,color:"Black",prevo:"dusclops",evoLevel:37,eggGroups:["Amorphous"]}, froslass:{num:478,species:"Froslass",types:["Ice","Ghost"],gender:"F",baseStats:{hp:70,atk:80,def:70,spa:80,spd:70,spe:110},abilities:{0:"Snow Cloak",H:"Cursed Body"},heightm:1.3,weightkg:26.6,color:"White",prevo:"snorunt",evoLevel:1,eggGroups:["Fairy","Mineral"]}, rotom:{num:479,species:"Rotom",types:["Electric","Ghost"],gender:"N",baseStats:{hp:50,atk:50,def:77,spa:95,spd:77,spe:91},abilities:{0:"Levitate"},heightm:0.3,weightkg:0.3,color:"Red",eggGroups:["Amorphous"],otherFormes:["rotomheat","rotomwash","rotomfrost","rotomfan","rotommow"]}, rotomheat:{num:479,species:"Rotom-Heat",baseSpecies:"Rotom",forme:"Heat",formeLetter:"H",types:["Electric","Fire"],gender:"N",baseStats:{hp:50,atk:65,def:107,spa:105,spd:107,spe:86},abilities:{0:"Levitate"},heightm:0.3,weightkg:0.3,color:"Red",eggGroups:["Amorphous"]}, rotomwash:{num:479,species:"Rotom-Wash",baseSpecies:"Rotom",forme:"Wash",formeLetter:"W",types:["Electric","Water"],gender:"N",baseStats:{hp:50,atk:65,def:107,spa:105,spd:107,spe:86},abilities:{0:"Levitate"},heightm:0.3,weightkg:0.3,color:"Red",eggGroups:["Amorphous"]}, rotomfrost:{num:479,species:"Rotom-Frost",baseSpecies:"Rotom",forme:"Frost",formeLetter:"F",types:["Electric","Ice"],gender:"N",baseStats:{hp:50,atk:65,def:107,spa:105,spd:107,spe:86},abilities:{0:"Levitate"},heightm:0.3,weightkg:0.3,color:"Red",eggGroups:["Amorphous"]}, rotomfan:{num:479,species:"Rotom-Fan",baseSpecies:"Rotom",forme:"Fan",formeLetter:"S",types:["Electric","Flying"],gender:"N",baseStats:{hp:50,atk:65,def:107,spa:105,spd:107,spe:86},abilities:{0:"Levitate"},heightm:0.3,weightkg:0.3,color:"Red",eggGroups:["Amorphous"]}, rotommow:{num:479,species:"Rotom-Mow",baseSpecies:"Rotom",forme:"Mow",formeLetter:"C",types:["Electric","Grass"],gender:"N",baseStats:{hp:50,atk:65,def:107,spa:105,spd:107,spe:86},abilities:{0:"Levitate"},heightm:0.3,weightkg:0.3,color:"Red",eggGroups:["Amorphous"]}, uxie:{num:480,species:"Uxie",types:["Psychic"],gender:"N",baseStats:{hp:75,atk:75,def:130,spa:75,spd:130,spe:95},abilities:{0:"Levitate"},heightm:0.3,weightkg:0.3,color:"Yellow",eggGroups:["Undiscovered"]}, mesprit:{num:481,species:"Mesprit",types:["Psychic"],gender:"N",baseStats:{hp:80,atk:105,def:105,spa:105,spd:105,spe:80},abilities:{0:"Levitate"},heightm:0.3,weightkg:0.3,color:"Pink",eggGroups:["Undiscovered"]}, azelf:{num:482,species:"Azelf",types:["Psychic"],gender:"N",baseStats:{hp:75,atk:125,def:70,spa:125,spd:70,spe:115},abilities:{0:"Levitate"},heightm:0.3,weightkg:0.3,color:"Blue",eggGroups:["Undiscovered"]}, dialga:{num:483,species:"Dialga",types:["Steel","Dragon"],gender:"N",baseStats:{hp:100,atk:120,def:120,spa:150,spd:100,spe:90},abilities:{0:"Pressure",H:"Telepathy"},heightm:5.4,weightkg:683,color:"White",eggGroups:["Undiscovered"]}, palkia:{num:484,species:"Palkia",types:["Water","Dragon"],gender:"N",baseStats:{hp:90,atk:120,def:100,spa:150,spd:120,spe:100},abilities:{0:"Pressure",H:"Telepathy"},heightm:4.2,weightkg:336,color:"Purple",eggGroups:["Undiscovered"]}, heatran:{num:485,species:"Heatran",types:["Fire","Steel"],baseStats:{hp:91,atk:90,def:106,spa:130,spd:106,spe:77},abilities:{0:"Flash Fire",H:"Flame Body"},heightm:1.7,weightkg:430,color:"Brown",eggGroups:["Undiscovered"]}, regigigas:{num:486,species:"Regigigas",types:["Normal"],gender:"N",baseStats:{hp:110,atk:160,def:110,spa:80,spd:110,spe:100},abilities:{0:"Slow Start"},heightm:3.7,weightkg:420,color:"White",eggGroups:["Undiscovered"]}, giratina:{num:487,species:"Giratina",baseForme:"Altered",types:["Ghost","Dragon"],gender:"N",baseStats:{hp:150,atk:100,def:120,spa:100,spd:120,spe:90},abilities:{0:"Pressure",H:"Telepathy"},heightm:4.5,weightkg:750,color:"Black",eggGroups:["Undiscovered"],otherFormes:["giratinaorigin"]}, giratinaorigin:{num:487,species:"Giratina-Origin",baseSpecies:"Giratina",forme:"Origin",formeLetter:"O",types:["Ghost","Dragon"],gender:"N",baseStats:{hp:150,atk:120,def:100,spa:120,spd:100,spe:90},abilities:{0:"Levitate"},heightm:6.9,weightkg:650,color:"Black",eggGroups:["Undiscovered"]}, cresselia:{num:488,species:"Cresselia",types:["Psychic"],gender:"F",baseStats:{hp:120,atk:70,def:120,spa:75,spd:130,spe:85},abilities:{0:"Levitate"},heightm:1.5,weightkg:85.6,color:"Yellow",eggGroups:["Undiscovered"]}, phione:{num:489,species:"Phione",types:["Water"],gender:"N",baseStats:{hp:80,atk:80,def:80,spa:80,spd:80,spe:80},abilities:{0:"Hydration"},heightm:0.4,weightkg:3.1,color:"Blue",eggGroups:["Water 1","Fairy"]}, manaphy:{num:490,species:"Manaphy",types:["Water"],gender:"N",baseStats:{hp:100,atk:100,def:100,spa:100,spd:100,spe:100},abilities:{0:"Hydration"},heightm:0.3,weightkg:1.4,color:"Blue",eggGroups:["Water 1","Fairy"]}, darkrai:{num:491,species:"Darkrai",types:["Dark"],gender:"N",baseStats:{hp:70,atk:90,def:90,spa:135,spd:90,spe:125},abilities:{0:"Bad Dreams"},heightm:1.5,weightkg:50.5,color:"Black",eggGroups:["Undiscovered"]}, shaymin:{num:492,species:"Shaymin",baseForme:"Land",types:["Grass"],gender:"N",baseStats:{hp:100,atk:100,def:100,spa:100,spd:100,spe:100},abilities:{0:"Natural Cure"},heightm:0.2,weightkg:2.1,color:"Green",eggGroups:["Undiscovered"],otherFormes:["shayminsky"]}, shayminsky:{num:492,species:"Shaymin-Sky",baseSpecies:"Shaymin",forme:"Sky",formeLetter:"S",types:["Grass","Flying"],gender:"N",baseStats:{hp:100,atk:103,def:75,spa:120,spd:75,spe:127},abilities:{0:"Serene Grace"},heightm:0.4,weightkg:5.2,color:"Green",eggGroups:["Undiscovered"]}, arceus:{num:493,species:"Arceus",baseForme:"Normal",types:["Normal"],gender:"N",baseStats:{hp:120,atk:120,def:120,spa:120,spd:120,spe:120},abilities:{0:"Multitype"},heightm:3.2,weightkg:320,color:"Gray",eggGroups:["Undiscovered"],otherFormes:["arceusbug","arceusdark","arceusdragon","arceuselectric","arceusfairy","arceusfighting","arceusfire","arceusflying","arceusghost","arceusgrass","arceusground","arceusice","arceuspoison","arceuspsychic","arceusrock","arceussteel","arceuswater"]}, arceusbug:{num:493,species:"Arceus-Bug",baseSpecies:"Arceus",forme:"Bug",formeLetter:"B",types:["Bug"],gender:"N",baseStats:{hp:120,atk:120,def:120,spa:120,spd:120,spe:120},abilities:{0:"Multitype"},heightm:3.2,weightkg:320,color:"Gray",eggGroups:["Undiscovered"]}, arceusdark:{num:493,species:"Arceus-Dark",baseSpecies:"Arceus",forme:"Dark",formeLetter:"D",types:["Dark"],gender:"N",baseStats:{hp:120,atk:120,def:120,spa:120,spd:120,spe:120},abilities:{0:"Multitype"},heightm:3.2,weightkg:320,color:"Gray",eggGroups:["Undiscovered"]}, arceusdragon:{num:493,species:"Arceus-Dragon",baseSpecies:"Arceus",forme:"Dragon",formeLetter:"D",types:["Dragon"],gender:"N",baseStats:{hp:120,atk:120,def:120,spa:120,spd:120,spe:120},abilities:{0:"Multitype"},heightm:3.2,weightkg:320,color:"Gray",eggGroups:["Undiscovered"]}, arceuselectric:{num:493,species:"Arceus-Electric",baseSpecies:"Arceus",forme:"Electric",formeLetter:"E",types:["Electric"],gender:"N",baseStats:{hp:120,atk:120,def:120,spa:120,spd:120,spe:120},abilities:{0:"Multitype"},heightm:3.2,weightkg:320,color:"Gray",eggGroups:["Undiscovered"]}, arceusfairy:{num:493,species:"Arceus-Fairy",baseSpecies:"Arceus",forme:"Fairy",formeLetter:"F",types:["Fairy"],gender:"N",baseStats:{hp:120,atk:120,def:120,spa:120,spd:120,spe:120},abilities:{0:"Multitype"},heightm:3.2,weightkg:320,color:"Gray",eggGroups:["Undiscovered"]}, arceusfighting:{num:493,species:"Arceus-Fighting",baseSpecies:"Arceus",forme:"Fighting",formeLetter:"F",types:["Fighting"],gender:"N",baseStats:{hp:120,atk:120,def:120,spa:120,spd:120,spe:120},abilities:{0:"Multitype"},heightm:3.2,weightkg:320,color:"Gray",eggGroups:["Undiscovered"]}, arceusfire:{num:493,species:"Arceus-Fire",baseSpecies:"Arceus",forme:"Fire",formeLetter:"F",types:["Fire"],gender:"N",baseStats:{hp:120,atk:120,def:120,spa:120,spd:120,spe:120},abilities:{0:"Multitype"},heightm:3.2,weightkg:320,color:"Gray",eggGroups:["Undiscovered"]}, arceusflying:{num:493,species:"Arceus-Flying",baseSpecies:"Arceus",forme:"Flying",formeLetter:"F",types:["Flying"],gender:"N",baseStats:{hp:120,atk:120,def:120,spa:120,spd:120,spe:120},abilities:{0:"Multitype"},heightm:3.2,weightkg:320,color:"Gray",eggGroups:["Undiscovered"]}, arceusghost:{num:493,species:"Arceus-Ghost",baseSpecies:"Arceus",forme:"Ghost",formeLetter:"G",types:["Ghost"],gender:"N",baseStats:{hp:120,atk:120,def:120,spa:120,spd:120,spe:120},abilities:{0:"Multitype"},heightm:3.2,weightkg:320,color:"Gray",eggGroups:["Undiscovered"]}, arceusgrass:{num:493,species:"Arceus-Grass",baseSpecies:"Arceus",forme:"Grass",formeLetter:"G",types:["Grass"],gender:"N",baseStats:{hp:120,atk:120,def:120,spa:120,spd:120,spe:120},abilities:{0:"Multitype"},heightm:3.2,weightkg:320,color:"Gray",eggGroups:["Undiscovered"]}, arceusground:{num:493,species:"Arceus-Ground",baseSpecies:"Arceus",forme:"Ground",formeLetter:"G",types:["Ground"],gender:"N",baseStats:{hp:120,atk:120,def:120,spa:120,spd:120,spe:120},abilities:{0:"Multitype"},heightm:3.2,weightkg:320,color:"Gray",eggGroups:["Undiscovered"]}, arceusice:{num:493,species:"Arceus-Ice",baseSpecies:"Arceus",forme:"Ice",formeLetter:"I",types:["Ice"],gender:"N",baseStats:{hp:120,atk:120,def:120,spa:120,spd:120,spe:120},abilities:{0:"Multitype"},heightm:3.2,weightkg:320,color:"Gray",eggGroups:["Undiscovered"]}, arceuspoison:{num:493,species:"Arceus-Poison",baseSpecies:"Arceus",forme:"Poison",formeLetter:"P",types:["Poison"],gender:"N",baseStats:{hp:120,atk:120,def:120,spa:120,spd:120,spe:120},abilities:{0:"Multitype"},heightm:3.2,weightkg:320,color:"Gray",eggGroups:["Undiscovered"]}, arceuspsychic:{num:493,species:"Arceus-Psychic",baseSpecies:"Arceus",forme:"Psychic",formeLetter:"P",types:["Psychic"],gender:"N",baseStats:{hp:120,atk:120,def:120,spa:120,spd:120,spe:120},abilities:{0:"Multitype"},heightm:3.2,weightkg:320,color:"Gray",eggGroups:["Undiscovered"]}, arceusrock:{num:493,species:"Arceus-Rock",baseSpecies:"Arceus",forme:"Rock",formeLetter:"R",types:["Rock"],gender:"N",baseStats:{hp:120,atk:120,def:120,spa:120,spd:120,spe:120},abilities:{0:"Multitype"},heightm:3.2,weightkg:320,color:"Gray",eggGroups:["Undiscovered"]}, arceussteel:{num:493,species:"Arceus-Steel",baseSpecies:"Arceus",forme:"Steel",formeLetter:"S",types:["Steel"],gender:"N",baseStats:{hp:120,atk:120,def:120,spa:120,spd:120,spe:120},abilities:{0:"Multitype"},heightm:3.2,weightkg:320,color:"Gray",eggGroups:["Undiscovered"]}, arceuswater:{num:493,species:"Arceus-Water",baseSpecies:"Arceus",forme:"Water",formeLetter:"W",types:["Water"],gender:"N",baseStats:{hp:120,atk:120,def:120,spa:120,spd:120,spe:120},abilities:{0:"Multitype"},heightm:3.2,weightkg:320,color:"Gray",eggGroups:["Undiscovered"]}, victini:{num:494,species:"Victini",types:["Psychic","Fire"],gender:"N",baseStats:{hp:100,atk:100,def:100,spa:100,spd:100,spe:100},abilities:{0:"Victory Star"},heightm:0.4,weightkg:4,color:"Yellow",eggGroups:["Undiscovered"]}, snivy:{num:495,species:"Snivy",types:["Grass"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:45,atk:45,def:55,spa:45,spd:55,spe:63},abilities:{0:"Overgrow",H:"Contrary"},heightm:0.6,weightkg:8.1,color:"Green",evos:["servine"],eggGroups:["Field","Grass"]}, servine:{num:496,species:"Servine",types:["Grass"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:60,atk:60,def:75,spa:60,spd:75,spe:83},abilities:{0:"Overgrow",H:"Contrary"},heightm:0.8,weightkg:16,color:"Green",prevo:"snivy",evos:["serperior"],evoLevel:17,eggGroups:["Field","Grass"]}, serperior:{num:497,species:"Serperior",types:["Grass"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:75,atk:75,def:95,spa:75,spd:95,spe:113},abilities:{0:"Overgrow",H:"Contrary"},heightm:3.3,weightkg:63,color:"Green",prevo:"servine",evoLevel:36,eggGroups:["Field","Grass"]}, tepig:{num:498,species:"Tepig",types:["Fire"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:65,atk:63,def:45,spa:45,spd:45,spe:45},abilities:{0:"Blaze",H:"Thick Fat"},heightm:0.5,weightkg:9.9,color:"Red",evos:["pignite"],eggGroups:["Field"]}, pignite:{num:499,species:"Pignite",types:["Fire","Fighting"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:90,atk:93,def:55,spa:70,spd:55,spe:55},abilities:{0:"Blaze",H:"Thick Fat"},heightm:1,weightkg:55.5,color:"Red",prevo:"tepig",evos:["emboar"],evoLevel:17,eggGroups:["Field"]}, emboar:{num:500,species:"Emboar",types:["Fire","Fighting"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:110,atk:123,def:65,spa:100,spd:65,spe:65},abilities:{0:"Blaze",H:"Reckless"},heightm:1.6,weightkg:150,color:"Red",prevo:"pignite",evoLevel:36,eggGroups:["Field"]}, oshawott:{num:501,species:"Oshawott",types:["Water"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:55,atk:55,def:45,spa:63,spd:45,spe:45},abilities:{0:"Torrent",H:"Shell Armor"},heightm:0.5,weightkg:5.9,color:"Blue",evos:["dewott"],eggGroups:["Field"]}, dewott:{num:502,species:"Dewott",types:["Water"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:75,atk:75,def:60,spa:83,spd:60,spe:60},abilities:{0:"Torrent",H:"Shell Armor"},heightm:0.8,weightkg:24.5,color:"Blue",prevo:"oshawott",evos:["samurott"],evoLevel:17,eggGroups:["Field"]}, samurott:{num:503,species:"Samurott",types:["Water"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:95,atk:100,def:85,spa:108,spd:70,spe:70},abilities:{0:"Torrent",H:"Shell Armor"},heightm:1.5,weightkg:94.6,color:"Blue",prevo:"dewott",evoLevel:36,eggGroups:["Field"]}, patrat:{num:504,species:"Patrat",types:["Normal"],baseStats:{hp:45,atk:55,def:39,spa:35,spd:39,spe:42},abilities:{0:"Run Away",1:"Keen Eye",H:"Analytic"},heightm:0.5,weightkg:11.6,color:"Brown",evos:["watchog"],eggGroups:["Field"]}, watchog:{num:505,species:"Watchog",types:["Normal"],baseStats:{hp:60,atk:85,def:69,spa:60,spd:69,spe:77},abilities:{0:"Illuminate",1:"Keen Eye",H:"Analytic"},heightm:1.1,weightkg:27,color:"Brown",prevo:"patrat",evoLevel:20,eggGroups:["Field"]}, lillipup:{num:506,species:"Lillipup",types:["Normal"],baseStats:{hp:45,atk:60,def:45,spa:25,spd:45,spe:55},abilities:{0:"Vital Spirit",1:"Pickup",H:"Run Away"},heightm:0.4,weightkg:4.1,color:"Brown",evos:["herdier"],eggGroups:["Field"]}, herdier:{num:507,species:"Herdier",types:["Normal"],baseStats:{hp:65,atk:80,def:65,spa:35,spd:65,spe:60},abilities:{0:"Intimidate",1:"Sand Rush",H:"Scrappy"},heightm:0.9,weightkg:14.7,color:"Gray",prevo:"lillipup",evos:["stoutland"],evoLevel:16,eggGroups:["Field"]}, stoutland:{num:508,species:"Stoutland",types:["Normal"],baseStats:{hp:85,atk:110,def:90,spa:45,spd:90,spe:80},abilities:{0:"Intimidate",1:"Sand Rush",H:"Scrappy"},heightm:1.2,weightkg:61,color:"Gray",prevo:"herdier",evoLevel:32,eggGroups:["Field"]}, purrloin:{num:509,species:"Purrloin",types:["Dark"],baseStats:{hp:41,atk:50,def:37,spa:50,spd:37,spe:66},abilities:{0:"Limber",1:"Unburden",H:"Prankster"},heightm:0.4,weightkg:10.1,color:"Purple",evos:["liepard"],eggGroups:["Field"]}, liepard:{num:510,species:"Liepard",types:["Dark"],baseStats:{hp:64,atk:88,def:50,spa:88,spd:50,spe:106},abilities:{0:"Limber",1:"Unburden",H:"Prankster"},heightm:1.1,weightkg:37.5,color:"Purple",prevo:"purrloin",evoLevel:20,eggGroups:["Field"]}, pansage:{num:511,species:"Pansage",types:["Grass"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:50,atk:53,def:48,spa:53,spd:48,spe:64},abilities:{0:"Gluttony",H:"Overgrow"},heightm:0.6,weightkg:10.5,color:"Green",evos:["simisage"],eggGroups:["Field"]}, simisage:{num:512,species:"Simisage",types:["Grass"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:75,atk:98,def:63,spa:98,spd:63,spe:101},abilities:{0:"Gluttony",H:"Overgrow"},heightm:1.1,weightkg:30.5,color:"Green",prevo:"pansage",evoLevel:1,eggGroups:["Field"]}, pansear:{num:513,species:"Pansear",types:["Fire"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:50,atk:53,def:48,spa:53,spd:48,spe:64},abilities:{0:"Gluttony",H:"Blaze"},heightm:0.6,weightkg:11,color:"Red",evos:["simisear"],eggGroups:["Field"]}, simisear:{num:514,species:"Simisear",types:["Fire"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:75,atk:98,def:63,spa:98,spd:63,spe:101},abilities:{0:"Gluttony",H:"Blaze"},heightm:1,weightkg:28,color:"Red",prevo:"pansear",evoLevel:1,eggGroups:["Field"]}, panpour:{num:515,species:"Panpour",types:["Water"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:50,atk:53,def:48,spa:53,spd:48,spe:64},abilities:{0:"Gluttony",H:"Torrent"},heightm:0.6,weightkg:13.5,color:"Blue",evos:["simipour"],eggGroups:["Field"]}, simipour:{num:516,species:"Simipour",types:["Water"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:75,atk:98,def:63,spa:98,spd:63,spe:101},abilities:{0:"Gluttony",H:"Torrent"},heightm:1,weightkg:29,color:"Blue",prevo:"panpour",evoLevel:1,eggGroups:["Field"]}, munna:{num:517,species:"Munna",types:["Psychic"],baseStats:{hp:76,atk:25,def:45,spa:67,spd:55,spe:24},abilities:{0:"Forewarn",1:"Synchronize",H:"Telepathy"},heightm:0.6,weightkg:23.3,color:"Pink",evos:["musharna"],eggGroups:["Field"]}, musharna:{num:518,species:"Musharna",types:["Psychic"],baseStats:{hp:116,atk:55,def:85,spa:107,spd:95,spe:29},abilities:{0:"Forewarn",1:"Synchronize",H:"Telepathy"},heightm:1.1,weightkg:60.5,color:"Pink",prevo:"munna",evoLevel:1,eggGroups:["Field"]}, pidove:{num:519,species:"Pidove",types:["Normal","Flying"],baseStats:{hp:50,atk:55,def:50,spa:36,spd:30,spe:43},abilities:{0:"Big Pecks",1:"Super Luck",H:"Rivalry"},heightm:0.3,weightkg:2.1,color:"Gray",evos:["tranquill"],eggGroups:["Flying"]}, tranquill:{num:520,species:"Tranquill",types:["Normal","Flying"],baseStats:{hp:62,atk:77,def:62,spa:50,spd:42,spe:65},abilities:{0:"Big Pecks",1:"Super Luck",H:"Rivalry"},heightm:0.6,weightkg:15,color:"Gray",prevo:"pidove",evos:["unfezant"],evoLevel:21,eggGroups:["Flying"]}, unfezant:{num:521,species:"Unfezant",types:["Normal","Flying"],baseStats:{hp:80,atk:115,def:80,spa:65,spd:55,spe:93},abilities:{0:"Big Pecks",1:"Super Luck",H:"Rivalry"},heightm:1.2,weightkg:29,color:"Gray",prevo:"tranquill",evoLevel:32,eggGroups:["Flying"]}, blitzle:{num:522,species:"Blitzle",types:["Electric"],baseStats:{hp:45,atk:60,def:32,spa:50,spd:32,spe:76},abilities:{0:"Lightningrod",1:"Motor Drive",H:"Sap Sipper"},heightm:0.8,weightkg:29.8,color:"Black",evos:["zebstrika"],eggGroups:["Field"]}, zebstrika:{num:523,species:"Zebstrika",types:["Electric"],baseStats:{hp:75,atk:100,def:63,spa:80,spd:63,spe:116},abilities:{0:"Lightningrod",1:"Motor Drive",H:"Sap Sipper"},heightm:1.6,weightkg:79.5,color:"Black",prevo:"blitzle",evoLevel:27,eggGroups:["Field"]}, roggenrola:{num:524,species:"Roggenrola",types:["Rock"],baseStats:{hp:55,atk:75,def:85,spa:25,spd:25,spe:15},abilities:{0:"Sturdy",H:"Sand Force"},heightm:0.4,weightkg:18,color:"Blue",evos:["boldore"],eggGroups:["Mineral"]}, boldore:{num:525,species:"Boldore",types:["Rock"],baseStats:{hp:70,atk:105,def:105,spa:50,spd:40,spe:20},abilities:{0:"Sturdy",H:"Sand Force"},heightm:0.9,weightkg:102,color:"Blue",prevo:"roggenrola",evos:["gigalith"],evoLevel:25,eggGroups:["Mineral"]}, gigalith:{num:526,species:"Gigalith",types:["Rock"],baseStats:{hp:85,atk:135,def:130,spa:60,spd:80,spe:25},abilities:{0:"Sturdy",H:"Sand Force"},heightm:1.7,weightkg:260,color:"Blue",prevo:"boldore",evoLevel:25,eggGroups:["Mineral"]}, woobat:{num:527,species:"Woobat",types:["Psychic","Flying"],baseStats:{hp:55,atk:45,def:43,spa:55,spd:43,spe:72},abilities:{0:"Unaware",1:"Klutz",H:"Simple"},heightm:0.4,weightkg:2.1,color:"Blue",evos:["swoobat"],eggGroups:["Flying","Field"]}, swoobat:{num:528,species:"Swoobat",types:["Psychic","Flying"],baseStats:{hp:67,atk:57,def:55,spa:77,spd:55,spe:114},abilities:{0:"Unaware",1:"Klutz",H:"Simple"},heightm:0.9,weightkg:10.5,color:"Blue",prevo:"woobat",evoLevel:2,eggGroups:["Flying","Field"]}, drilbur:{num:529,species:"Drilbur",types:["Ground"],baseStats:{hp:60,atk:85,def:40,spa:30,spd:45,spe:68},abilities:{0:"Sand Rush",1:"Sand Force",H:"Mold Breaker"},heightm:0.3,weightkg:8.5,color:"Gray",evos:["excadrill"],eggGroups:["Field"]}, excadrill:{num:530,species:"Excadrill",types:["Ground","Steel"],baseStats:{hp:110,atk:135,def:60,spa:50,spd:65,spe:88},abilities:{0:"Sand Rush",1:"Sand Force",H:"Mold Breaker"},heightm:0.7,weightkg:40.4,color:"Gray",prevo:"drilbur",evoLevel:31,eggGroups:["Field"]}, audino:{num:531,species:"Audino",types:["Normal"],baseStats:{hp:103,atk:60,def:86,spa:60,spd:86,spe:50},abilities:{0:"Healer",1:"Regenerator",H:"Klutz"},heightm:1.1,weightkg:31,color:"Pink",eggGroups:["Fairy"]}, timburr:{num:532,species:"Timburr",types:["Fighting"],genderRatio:{M:0.75,F:0.25},baseStats:{hp:75,atk:80,def:55,spa:25,spd:35,spe:35},abilities:{0:"Guts",1:"Sheer Force",H:"Iron Fist"},heightm:0.6,weightkg:12.5,color:"Gray",evos:["gurdurr"],eggGroups:["Human-Like"]}, gurdurr:{num:533,species:"Gurdurr",types:["Fighting"],genderRatio:{M:0.75,F:0.25},baseStats:{hp:85,atk:105,def:85,spa:40,spd:50,spe:40},abilities:{0:"Guts",1:"Sheer Force",H:"Iron Fist"},heightm:1.2,weightkg:40,color:"Gray",prevo:"timburr",evos:["conkeldurr"],evoLevel:25,eggGroups:["Human-Like"]}, conkeldurr:{num:534,species:"Conkeldurr",types:["Fighting"],genderRatio:{M:0.75,F:0.25},baseStats:{hp:105,atk:140,def:95,spa:55,spd:65,spe:45},abilities:{0:"Guts",1:"Sheer Force",H:"Iron Fist"},heightm:1.4,weightkg:87,color:"Brown",prevo:"gurdurr",evoLevel:25,eggGroups:["Human-Like"]}, tympole:{num:535,species:"Tympole",types:["Water"],baseStats:{hp:50,atk:50,def:40,spa:50,spd:40,spe:64},abilities:{0:"Swift Swim",1:"Hydration",H:"Water Absorb"},heightm:0.5,weightkg:4.5,color:"Blue",evos:["palpitoad"],eggGroups:["Water 1"]}, palpitoad:{num:536,species:"Palpitoad",types:["Water","Ground"],baseStats:{hp:75,atk:65,def:55,spa:65,spd:55,spe:69},abilities:{0:"Swift Swim",1:"Hydration",H:"Water Absorb"},heightm:0.8,weightkg:17,color:"Blue",prevo:"tympole",evos:["seismitoad"],evoLevel:25,eggGroups:["Water 1"]}, seismitoad:{num:537,species:"Seismitoad",types:["Water","Ground"],baseStats:{hp:105,atk:95,def:75,spa:85,spd:75,spe:74},abilities:{0:"Swift Swim",1:"Poison Touch",H:"Water Absorb"},heightm:1.5,weightkg:62,color:"Blue",prevo:"palpitoad",evoLevel:36,eggGroups:["Water 1"]}, throh:{num:538,species:"Throh",types:["Fighting"],gender:"M",baseStats:{hp:120,atk:100,def:85,spa:30,spd:85,spe:45},abilities:{0:"Guts",1:"Inner Focus",H:"Mold Breaker"},heightm:1.3,weightkg:55.5,color:"Red",eggGroups:["Human-Like"]}, sawk:{num:539,species:"Sawk",types:["Fighting"],gender:"M",baseStats:{hp:75,atk:125,def:75,spa:30,spd:75,spe:85},abilities:{0:"Sturdy",1:"Inner Focus",H:"Mold Breaker"},heightm:1.4,weightkg:51,color:"Blue",eggGroups:["Human-Like"]}, sewaddle:{num:540,species:"Sewaddle",types:["Bug","Grass"],baseStats:{hp:45,atk:53,def:70,spa:40,spd:60,spe:42},abilities:{0:"Swarm",1:"Chlorophyll",H:"Overcoat"},heightm:0.3,weightkg:2.5,color:"Yellow",evos:["swadloon"],eggGroups:["Bug"]}, swadloon:{num:541,species:"Swadloon",types:["Bug","Grass"],baseStats:{hp:55,atk:63,def:90,spa:50,spd:80,spe:42},abilities:{0:"Leaf Guard",1:"Chlorophyll",H:"Overcoat"},heightm:0.5,weightkg:7.3,color:"Green",prevo:"sewaddle",evos:["leavanny"],evoLevel:20,eggGroups:["Bug"]}, leavanny:{num:542,species:"Leavanny",types:["Bug","Grass"],baseStats:{hp:75,atk:103,def:80,spa:70,spd:80,spe:92},abilities:{0:"Swarm",1:"Chlorophyll",H:"Overcoat"},heightm:1.2,weightkg:20.5,color:"Yellow",prevo:"swadloon",evoLevel:21,eggGroups:["Bug"]}, venipede:{num:543,species:"Venipede",types:["Bug","Poison"],baseStats:{hp:30,atk:45,def:59,spa:30,spd:39,spe:57},abilities:{0:"Poison Point",1:"Swarm",H:"Speed Boost"},heightm:0.4,weightkg:5.3,color:"Red",evos:["whirlipede"],eggGroups:["Bug"]}, whirlipede:{num:544,species:"Whirlipede",types:["Bug","Poison"],baseStats:{hp:40,atk:55,def:99,spa:40,spd:79,spe:47},abilities:{0:"Poison Point",1:"Swarm",H:"Speed Boost"},heightm:1.2,weightkg:58.5,color:"Gray",prevo:"venipede",evos:["scolipede"],evoLevel:22,eggGroups:["Bug"]}, scolipede:{num:545,species:"Scolipede",types:["Bug","Poison"],baseStats:{hp:60,atk:100,def:89,spa:55,spd:69,spe:112},abilities:{0:"Poison Point",1:"Swarm",H:"Speed Boost"},heightm:2.5,weightkg:200.5,color:"Red",prevo:"whirlipede",evoLevel:30,eggGroups:["Bug"]}, cottonee:{num:546,species:"Cottonee",types:["Grass","Fairy"],baseStats:{hp:40,atk:27,def:60,spa:37,spd:50,spe:66},abilities:{0:"Prankster",1:"Infiltrator",H:"Chlorophyll"},heightm:0.3,weightkg:0.6,color:"Green",evos:["whimsicott"],eggGroups:["Fairy","Grass"]}, whimsicott:{num:547,species:"Whimsicott",types:["Grass","Fairy"],baseStats:{hp:60,atk:67,def:85,spa:77,spd:75,spe:116},abilities:{0:"Prankster",1:"Infiltrator",H:"Chlorophyll"},heightm:0.7,weightkg:6.6,color:"Green",prevo:"cottonee",evoLevel:1,eggGroups:["Fairy","Grass"]}, petilil:{num:548,species:"Petilil",types:["Grass"],gender:"F",baseStats:{hp:45,atk:35,def:50,spa:70,spd:50,spe:30},abilities:{0:"Chlorophyll",1:"Own Tempo",H:"Leaf Guard"},heightm:0.5,weightkg:6.6,color:"Green",evos:["lilligant"],eggGroups:["Grass"]}, lilligant:{num:549,species:"Lilligant",types:["Grass"],gender:"F",baseStats:{hp:70,atk:60,def:75,spa:110,spd:75,spe:90},abilities:{0:"Chlorophyll",1:"Own Tempo",H:"Leaf Guard"},heightm:1.1,weightkg:16.3,color:"Green",prevo:"petilil",evoLevel:1,eggGroups:["Grass"]}, basculin:{num:550,species:"Basculin",baseForme:"Red-Striped",types:["Water"],baseStats:{hp:70,atk:92,def:65,spa:80,spd:55,spe:98},abilities:{0:"Reckless",1:"Adaptability",H:"Mold Breaker"},heightm:1,weightkg:18,color:"Green",eggGroups:["Water 2"],otherFormes:["basculinbluestriped"]}, basculinbluestriped:{num:550,species:"Basculin-Blue-Striped",baseSpecies:"Basculin",forme:"Blue-Striped",formeLetter:"B",types:["Water"],baseStats:{hp:70,atk:92,def:65,spa:80,spd:55,spe:98},abilities:{0:"Rock Head",1:"Adaptability",H:"Mold Breaker"},heightm:1,weightkg:18,color:"Green",eggGroups:["Water 2"]}, sandile:{num:551,species:"Sandile",types:["Ground","Dark"],baseStats:{hp:50,atk:72,def:35,spa:35,spd:35,spe:65},abilities:{0:"Intimidate",1:"Moxie",H:"Anger Point"},heightm:0.7,weightkg:15.2,color:"Brown",evos:["krokorok"],eggGroups:["Field"]}, krokorok:{num:552,species:"Krokorok",types:["Ground","Dark"],baseStats:{hp:60,atk:82,def:45,spa:45,spd:45,spe:74},abilities:{0:"Intimidate",1:"Moxie",H:"Anger Point"},heightm:1,weightkg:33.4,color:"Brown",prevo:"sandile",evos:["krookodile"],evoLevel:29,eggGroups:["Field"]}, krookodile:{num:553,species:"Krookodile",types:["Ground","Dark"],baseStats:{hp:95,atk:117,def:80,spa:65,spd:70,spe:92},abilities:{0:"Intimidate",1:"Moxie",H:"Anger Point"},heightm:1.5,weightkg:96.3,color:"Red",prevo:"krokorok",evoLevel:40,eggGroups:["Field"]}, darumaka:{num:554,species:"Darumaka",types:["Fire"],baseStats:{hp:70,atk:90,def:45,spa:15,spd:45,spe:50},abilities:{0:"Hustle",H:"Inner Focus"},heightm:0.6,weightkg:37.5,color:"Red",evos:["darmanitan"],eggGroups:["Field"]}, darmanitan:{num:555,species:"Darmanitan",baseForme:"Standard",types:["Fire"],baseStats:{hp:105,atk:140,def:55,spa:30,spd:55,spe:95},abilities:{0:"Sheer Force",H:"Zen Mode"},heightm:1.3,weightkg:92.9,color:"Red",prevo:"darumaka",evoLevel:35,eggGroups:["Field"],otherFormes:["darmanitanzen"]}, darmanitanzen:{num:555,species:"Darmanitan-Zen",baseSpecies:"Darmanitan",forme:"Zen",formeLetter:"Z",types:["Fire","Psychic"],baseStats:{hp:105,atk:30,def:105,spa:140,spd:105,spe:55},abilities:{0:"Sheer Force",H:"Zen Mode"},heightm:1.3,weightkg:92.9,color:"Red",prevo:"darumaka",evoLevel:35,eggGroups:["Field"]}, maractus:{num:556,species:"Maractus",types:["Grass"],baseStats:{hp:75,atk:86,def:67,spa:106,spd:67,spe:60},abilities:{0:"Water Absorb",1:"Chlorophyll",H:"Storm Drain"},heightm:1,weightkg:28,color:"Green",eggGroups:["Grass"]}, dwebble:{num:557,species:"Dwebble",types:["Bug","Rock"],baseStats:{hp:50,atk:65,def:85,spa:35,spd:35,spe:55},abilities:{0:"Sturdy",1:"Shell Armor",H:"Weak Armor"},heightm:0.3,weightkg:14.5,color:"Red",evos:["crustle"],eggGroups:["Bug","Mineral"]}, crustle:{num:558,species:"Crustle",types:["Bug","Rock"],baseStats:{hp:70,atk:95,def:125,spa:65,spd:75,spe:45},abilities:{0:"Sturdy",1:"Shell Armor",H:"Weak Armor"},heightm:1.4,weightkg:200,color:"Red",prevo:"dwebble",evoLevel:34,eggGroups:["Bug","Mineral"]}, scraggy:{num:559,species:"Scraggy",types:["Dark","Fighting"],baseStats:{hp:50,atk:75,def:70,spa:35,spd:70,spe:48},abilities:{0:"Shed Skin",1:"Moxie",H:"Intimidate"},heightm:0.6,weightkg:11.8,color:"Yellow",evos:["scrafty"],eggGroups:["Field","Dragon"]}, scrafty:{num:560,species:"Scrafty",types:["Dark","Fighting"],baseStats:{hp:65,atk:90,def:115,spa:45,spd:115,spe:58},abilities:{0:"Shed Skin",1:"Moxie",H:"Intimidate"},heightm:1.1,weightkg:30,color:"Red",prevo:"scraggy",evoLevel:39,eggGroups:["Field","Dragon"]}, sigilyph:{num:561,species:"Sigilyph",types:["Psychic","Flying"],baseStats:{hp:72,atk:58,def:80,spa:103,spd:80,spe:97},abilities:{0:"Wonder Skin",1:"Magic Guard",H:"Tinted Lens"},heightm:1.4,weightkg:14,color:"Black",eggGroups:["Flying"]}, yamask:{num:562,species:"Yamask",types:["Ghost"],baseStats:{hp:38,atk:30,def:85,spa:55,spd:65,spe:30},abilities:{0:"Mummy"},heightm:0.5,weightkg:1.5,color:"Black",evos:["cofagrigus"],eggGroups:["Mineral","Amorphous"]}, cofagrigus:{num:563,species:"Cofagrigus",types:["Ghost"],baseStats:{hp:58,atk:50,def:145,spa:95,spd:105,spe:30},abilities:{0:"Mummy"},heightm:1.7,weightkg:76.5,color:"Yellow",prevo:"yamask",evoLevel:34,eggGroups:["Mineral","Amorphous"]}, tirtouga:{num:564,species:"Tirtouga",types:["Water","Rock"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:54,atk:78,def:103,spa:53,spd:45,spe:22},abilities:{0:"Solid Rock",1:"Sturdy",H:"Swift Swim"},heightm:0.7,weightkg:16.5,color:"Blue",evos:["carracosta"],eggGroups:["Water 1","Water 3"]}, carracosta:{num:565,species:"Carracosta",types:["Water","Rock"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:74,atk:108,def:133,spa:83,spd:65,spe:32},abilities:{0:"Solid Rock",1:"Sturdy",H:"Swift Swim"},heightm:1.2,weightkg:81,color:"Blue",prevo:"tirtouga",evoLevel:37,eggGroups:["Water 1","Water 3"]}, archen:{num:566,species:"Archen",types:["Rock","Flying"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:55,atk:112,def:45,spa:74,spd:45,spe:70},abilities:{0:"Defeatist"},heightm:0.5,weightkg:9.5,color:"Yellow",evos:["archeops"],eggGroups:["Flying","Water 3"]}, archeops:{num:567,species:"Archeops",types:["Rock","Flying"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:75,atk:140,def:65,spa:112,spd:65,spe:110},abilities:{0:"Defeatist"},heightm:1.4,weightkg:32,color:"Yellow",prevo:"archen",evoLevel:37,eggGroups:["Flying","Water 3"]}, trubbish:{num:568,species:"Trubbish",types:["Poison"],baseStats:{hp:50,atk:50,def:62,spa:40,spd:62,spe:65},abilities:{0:"Stench",1:"Sticky Hold",H:"Aftermath"},heightm:0.6,weightkg:31,color:"Green",evos:["garbodor"],eggGroups:["Mineral"]}, garbodor:{num:569,species:"Garbodor",types:["Poison"],baseStats:{hp:80,atk:95,def:82,spa:60,spd:82,spe:75},abilities:{0:"Stench",1:"Weak Armor",H:"Aftermath"},heightm:1.9,weightkg:107.3,color:"Green",prevo:"trubbish",evoLevel:36,eggGroups:["Mineral"]}, zorua:{num:570,species:"Zorua",types:["Dark"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:40,atk:65,def:40,spa:80,spd:40,spe:65},abilities:{0:"Illusion"},heightm:0.7,weightkg:12.5,color:"Gray",evos:["zoroark"],eggGroups:["Field"]}, zoroark:{num:571,species:"Zoroark",types:["Dark"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:60,atk:105,def:60,spa:120,spd:60,spe:105},abilities:{0:"Illusion"},heightm:1.6,weightkg:81.1,color:"Gray",prevo:"zorua",evoLevel:30,eggGroups:["Field"]}, minccino:{num:572,species:"Minccino",types:["Normal"],genderRatio:{M:0.25,F:0.75},baseStats:{hp:55,atk:50,def:40,spa:40,spd:40,spe:75},abilities:{0:"Cute Charm",1:"Technician",H:"Skill Link"},heightm:0.4,weightkg:5.8,color:"Gray",evos:["cinccino"],eggGroups:["Field"]}, cinccino:{num:573,species:"Cinccino",types:["Normal"],genderRatio:{M:0.25,F:0.75},baseStats:{hp:75,atk:95,def:60,spa:65,spd:60,spe:115},abilities:{0:"Cute Charm",1:"Technician",H:"Skill Link"},heightm:0.5,weightkg:7.5,color:"Gray",prevo:"minccino",evoLevel:1,eggGroups:["Field"]}, gothita:{num:574,species:"Gothita",types:["Psychic"],genderRatio:{M:0.25,F:0.75},baseStats:{hp:45,atk:30,def:50,spa:55,spd:65,spe:45},abilities:{0:"Frisk",1:"Competitive",H:"Shadow Tag"},heightm:0.4,weightkg:5.8,color:"Purple",evos:["gothorita"],eggGroups:["Human-Like"]}, gothorita:{num:575,species:"Gothorita",types:["Psychic"],genderRatio:{M:0.25,F:0.75},baseStats:{hp:60,atk:45,def:70,spa:75,spd:85,spe:55},abilities:{0:"Frisk",1:"Competitive",H:"Shadow Tag"},heightm:0.7,weightkg:18,color:"Purple",prevo:"gothita",evos:["gothitelle"],evoLevel:32,eggGroups:["Human-Like"]}, gothitelle:{num:576,species:"Gothitelle",types:["Psychic"],genderRatio:{M:0.25,F:0.75},baseStats:{hp:70,atk:55,def:95,spa:95,spd:110,spe:65},abilities:{0:"Frisk",1:"Competitive",H:"Shadow Tag"},heightm:1.5,weightkg:44,color:"Purple",prevo:"gothorita",evoLevel:41,eggGroups:["Human-Like"]}, solosis:{num:577,species:"Solosis",types:["Psychic"],baseStats:{hp:45,atk:30,def:40,spa:105,spd:50,spe:20},abilities:{0:"Overcoat",1:"Magic Guard",H:"Regenerator"},heightm:0.3,weightkg:1,color:"Green",evos:["duosion"],eggGroups:["Amorphous"]}, duosion:{num:578,species:"Duosion",types:["Psychic"],baseStats:{hp:65,atk:40,def:50,spa:125,spd:60,spe:30},abilities:{0:"Overcoat",1:"Magic Guard",H:"Regenerator"},heightm:0.6,weightkg:8,color:"Green",prevo:"solosis",evos:["reuniclus"],evoLevel:32,eggGroups:["Amorphous"]}, reuniclus:{num:579,species:"Reuniclus",types:["Psychic"],baseStats:{hp:110,atk:65,def:75,spa:125,spd:85,spe:30},abilities:{0:"Overcoat",1:"Magic Guard",H:"Regenerator"},heightm:1,weightkg:20.1,color:"Green",prevo:"duosion",evoLevel:41,eggGroups:["Amorphous"]}, ducklett:{num:580,species:"Ducklett",types:["Water","Flying"],baseStats:{hp:62,atk:44,def:50,spa:44,spd:50,spe:55},abilities:{0:"Keen Eye",1:"Big Pecks",H:"Hydration"},heightm:0.5,weightkg:5.5,color:"Blue",evos:["swanna"],eggGroups:["Water 1","Flying"]}, swanna:{num:581,species:"Swanna",types:["Water","Flying"],baseStats:{hp:75,atk:87,def:63,spa:87,spd:63,spe:98},abilities:{0:"Keen Eye",1:"Big Pecks",H:"Hydration"},heightm:1.3,weightkg:24.2,color:"White",prevo:"ducklett",evoLevel:35,eggGroups:["Water 1","Flying"]}, vanillite:{num:582,species:"Vanillite",types:["Ice"],baseStats:{hp:36,atk:50,def:50,spa:65,spd:60,spe:44},abilities:{0:"Ice Body",H:"Weak Armor"},heightm:0.4,weightkg:5.7,color:"White",evos:["vanillish"],eggGroups:["Mineral"]}, vanillish:{num:583,species:"Vanillish",types:["Ice"],baseStats:{hp:51,atk:65,def:65,spa:80,spd:75,spe:59},abilities:{0:"Ice Body",H:"Weak Armor"},heightm:1.1,weightkg:41,color:"White",prevo:"vanillite",evos:["vanilluxe"],evoLevel:35,eggGroups:["Mineral"]}, vanilluxe:{num:584,species:"Vanilluxe",types:["Ice"],baseStats:{hp:71,atk:95,def:85,spa:110,spd:95,spe:79},abilities:{0:"Ice Body",H:"Weak Armor"},heightm:1.3,weightkg:57.5,color:"White",prevo:"vanillish",evoLevel:47,eggGroups:["Mineral"]}, deerling:{num:585,species:"Deerling",baseForme:"Spring",types:["Normal","Grass"],baseStats:{hp:60,atk:60,def:50,spa:40,spd:50,spe:75},abilities:{0:"Chlorophyll",1:"Sap Sipper",H:"Serene Grace"},heightm:0.6,weightkg:19.5,color:"Yellow",evos:["sawsbuck"],eggGroups:["Field"],otherForms:["deerlingsummer","deerlingautumn","deerlingwinter"]}, sawsbuck:{num:586,species:"Sawsbuck",baseForme:"Spring",types:["Normal","Grass"],baseStats:{hp:80,atk:100,def:70,spa:60,spd:70,spe:95},abilities:{0:"Chlorophyll",1:"Sap Sipper",H:"Serene Grace"},heightm:1.9,weightkg:92.5,color:"Brown",prevo:"deerling",evoLevel:34,eggGroups:["Field"],otherForms:["sawsbucksummer","sawsbuckautumn","sawsbuckwinter"]}, emolga:{num:587,species:"Emolga",types:["Electric","Flying"],baseStats:{hp:55,atk:75,def:60,spa:75,spd:60,spe:103},abilities:{0:"Static",H:"Motor Drive"},heightm:0.4,weightkg:5,color:"White",eggGroups:["Field"]}, karrablast:{num:588,species:"Karrablast",types:["Bug"],baseStats:{hp:50,atk:75,def:45,spa:40,spd:45,spe:60},abilities:{0:"Swarm",1:"Shed Skin",H:"No Guard"},heightm:0.5,weightkg:5.9,color:"Blue",evos:["escavalier"],eggGroups:["Bug"]}, escavalier:{num:589,species:"Escavalier",types:["Bug","Steel"],baseStats:{hp:70,atk:135,def:105,spa:60,spd:105,spe:20},abilities:{0:"Swarm",1:"Shell Armor",H:"Overcoat"},heightm:1,weightkg:33,color:"Gray",prevo:"karrablast",evoLevel:1,eggGroups:["Bug"]}, foongus:{num:590,species:"Foongus",types:["Grass","Poison"],baseStats:{hp:69,atk:55,def:45,spa:55,spd:55,spe:15},abilities:{0:"Effect Spore",H:"Regenerator"},heightm:0.2,weightkg:1,color:"White",evos:["amoonguss"],eggGroups:["Grass"]}, amoonguss:{num:591,species:"Amoonguss",types:["Grass","Poison"],baseStats:{hp:114,atk:85,def:70,spa:85,spd:80,spe:30},abilities:{0:"Effect Spore",H:"Regenerator"},heightm:0.6,weightkg:10.5,color:"White",prevo:"foongus",evoLevel:39,eggGroups:["Grass"]}, frillish:{num:592,species:"Frillish",types:["Water","Ghost"],baseStats:{hp:55,atk:40,def:50,spa:65,spd:85,spe:40},abilities:{0:"Water Absorb",1:"Cursed Body",H:"Damp"},heightm:1.2,weightkg:33,color:"White",evos:["jellicent"],eggGroups:["Amorphous"]}, jellicent:{num:593,species:"Jellicent",types:["Water","Ghost"],baseStats:{hp:100,atk:60,def:70,spa:85,spd:105,spe:60},abilities:{0:"Water Absorb",1:"Cursed Body",H:"Damp"},heightm:2.2,weightkg:135,color:"White",prevo:"frillish",evoLevel:40,eggGroups:["Amorphous"]}, alomomola:{num:594,species:"Alomomola",types:["Water"],baseStats:{hp:165,atk:75,def:80,spa:40,spd:45,spe:65},abilities:{0:"Healer",1:"Hydration",H:"Regenerator"},heightm:1.2,weightkg:31.6,color:"Pink",eggGroups:["Water 1","Water 2"]}, joltik:{num:595,species:"Joltik",types:["Bug","Electric"],baseStats:{hp:50,atk:47,def:50,spa:57,spd:50,spe:65},abilities:{0:"Compound Eyes",1:"Unnerve",H:"Swarm"},heightm:0.1,weightkg:0.6,color:"Yellow",evos:["galvantula"],eggGroups:["Bug"]}, galvantula:{num:596,species:"Galvantula",types:["Bug","Electric"],baseStats:{hp:70,atk:77,def:60,spa:97,spd:60,spe:108},abilities:{0:"Compound Eyes",1:"Unnerve",H:"Swarm"},heightm:0.8,weightkg:14.3,color:"Yellow",prevo:"joltik",evoLevel:36,eggGroups:["Bug"]}, ferroseed:{num:597,species:"Ferroseed",types:["Grass","Steel"],baseStats:{hp:44,atk:50,def:91,spa:24,spd:86,spe:10},abilities:{0:"Iron Barbs"},heightm:0.6,weightkg:18.8,color:"Gray",evos:["ferrothorn"],eggGroups:["Grass","Mineral"]}, ferrothorn:{num:598,species:"Ferrothorn",types:["Grass","Steel"],baseStats:{hp:74,atk:94,def:131,spa:54,spd:116,spe:20},abilities:{0:"Iron Barbs",H:"Anticipation"},heightm:1,weightkg:110,color:"Gray",prevo:"ferroseed",evoLevel:40,eggGroups:["Grass","Mineral"]}, klink:{num:599,species:"Klink",types:["Steel"],gender:"N",baseStats:{hp:40,atk:55,def:70,spa:45,spd:60,spe:30},abilities:{0:"Plus",1:"Minus",H:"Clear Body"},heightm:0.3,weightkg:21,color:"Gray",evos:["klang"],eggGroups:["Mineral"]}, klang:{num:600,species:"Klang",types:["Steel"],gender:"N",baseStats:{hp:60,atk:80,def:95,spa:70,spd:85,spe:50},abilities:{0:"Plus",1:"Minus",H:"Clear Body"},heightm:0.6,weightkg:51,color:"Gray",prevo:"klink",evos:["klinklang"],evoLevel:38,eggGroups:["Mineral"]}, klinklang:{num:601,species:"Klinklang",types:["Steel"],gender:"N",baseStats:{hp:60,atk:100,def:115,spa:70,spd:85,spe:90},abilities:{0:"Plus",1:"Minus",H:"Clear Body"},heightm:0.6,weightkg:81,color:"Gray",prevo:"klang",evoLevel:49,eggGroups:["Mineral"]}, tynamo:{num:602,species:"Tynamo",types:["Electric"],baseStats:{hp:35,atk:55,def:40,spa:45,spd:40,spe:60},abilities:{0:"Levitate"},heightm:0.2,weightkg:0.3,color:"White",evos:["eelektrik"],eggGroups:["Amorphous"]}, eelektrik:{num:603,species:"Eelektrik",types:["Electric"],baseStats:{hp:65,atk:85,def:70,spa:75,spd:70,spe:40},abilities:{0:"Levitate"},heightm:1.2,weightkg:22,color:"Blue",prevo:"tynamo",evos:["eelektross"],evoLevel:39,eggGroups:["Amorphous"]}, eelektross:{num:604,species:"Eelektross",types:["Electric"],baseStats:{hp:85,atk:115,def:80,spa:105,spd:80,spe:50},abilities:{0:"Levitate"},heightm:2.1,weightkg:80.5,color:"Blue",prevo:"eelektrik",evoLevel:39,eggGroups:["Amorphous"]}, elgyem:{num:605,species:"Elgyem",types:["Psychic"],baseStats:{hp:55,atk:55,def:55,spa:85,spd:55,spe:30},abilities:{0:"Telepathy",1:"Synchronize",H:"Analytic"},heightm:0.5,weightkg:9,color:"Blue",evos:["beheeyem"],eggGroups:["Human-Like"]}, beheeyem:{num:606,species:"Beheeyem",types:["Psychic"],baseStats:{hp:75,atk:75,def:75,spa:125,spd:95,spe:40},abilities:{0:"Telepathy",1:"Synchronize",H:"Analytic"},heightm:1,weightkg:34.5,color:"Brown",prevo:"elgyem",evoLevel:42,eggGroups:["Human-Like"]}, litwick:{num:607,species:"Litwick",types:["Ghost","Fire"],baseStats:{hp:50,atk:30,def:55,spa:65,spd:55,spe:20},abilities:{0:"Flash Fire",1:"Flame Body",H:"Infiltrator"},heightm:0.3,weightkg:3.1,color:"White",evos:["lampent"],eggGroups:["Amorphous"]}, lampent:{num:608,species:"Lampent",types:["Ghost","Fire"],baseStats:{hp:60,atk:40,def:60,spa:95,spd:60,spe:55},abilities:{0:"Flash Fire",1:"Flame Body",H:"Infiltrator"},heightm:0.6,weightkg:13,color:"Black",prevo:"litwick",evos:["chandelure"],evoLevel:41,eggGroups:["Amorphous"]}, chandelure:{num:609,species:"Chandelure",types:["Ghost","Fire"],baseStats:{hp:60,atk:55,def:90,spa:145,spd:90,spe:80},abilities:{0:"Flash Fire",1:"Flame Body",H:"Infiltrator"},heightm:1,weightkg:34.3,color:"Black",prevo:"lampent",evoLevel:41,eggGroups:["Amorphous"]}, axew:{num:610,species:"Axew",types:["Dragon"],baseStats:{hp:46,atk:87,def:60,spa:30,spd:40,spe:57},abilities:{0:"Rivalry",1:"Mold Breaker",H:"Unnerve"},heightm:0.6,weightkg:18,color:"Green",evos:["fraxure"],eggGroups:["Monster","Dragon"]}, fraxure:{num:611,species:"Fraxure",types:["Dragon"],baseStats:{hp:66,atk:117,def:70,spa:40,spd:50,spe:67},abilities:{0:"Rivalry",1:"Mold Breaker",H:"Unnerve"},heightm:1,weightkg:36,color:"Green",prevo:"axew",evos:["haxorus"],evoLevel:38,eggGroups:["Monster","Dragon"]}, haxorus:{num:612,species:"Haxorus",types:["Dragon"],baseStats:{hp:76,atk:147,def:90,spa:60,spd:70,spe:97},abilities:{0:"Rivalry",1:"Mold Breaker",H:"Unnerve"},heightm:1.8,weightkg:105.5,color:"Yellow",prevo:"fraxure",evoLevel:48,eggGroups:["Monster","Dragon"]}, cubchoo:{num:613,species:"Cubchoo",types:["Ice"],baseStats:{hp:55,atk:70,def:40,spa:60,spd:40,spe:40},abilities:{0:"Snow Cloak",H:"Rattled"},heightm:0.5,weightkg:8.5,color:"White",evos:["beartic"],eggGroups:["Field"]}, beartic:{num:614,species:"Beartic",types:["Ice"],baseStats:{hp:95,atk:110,def:80,spa:70,spd:80,spe:50},abilities:{0:"Snow Cloak",H:"Swift Swim"},heightm:2.6,weightkg:260,color:"White",prevo:"cubchoo",evoLevel:37,eggGroups:["Field"]}, cryogonal:{num:615,species:"Cryogonal",types:["Ice"],gender:"N",baseStats:{hp:70,atk:50,def:30,spa:95,spd:135,spe:105},abilities:{0:"Levitate"},heightm:1.1,weightkg:148,color:"Blue",eggGroups:["Mineral"]}, shelmet:{num:616,species:"Shelmet",types:["Bug"],baseStats:{hp:50,atk:40,def:85,spa:40,spd:65,spe:25},abilities:{0:"Hydration",1:"Shell Armor",H:"Overcoat"},heightm:0.4,weightkg:7.7,color:"Red",evos:["accelgor"],eggGroups:["Bug"]}, accelgor:{num:617,species:"Accelgor",types:["Bug"],baseStats:{hp:80,atk:70,def:40,spa:100,spd:60,spe:145},abilities:{0:"Hydration",1:"Sticky Hold",H:"Unburden"},heightm:0.8,weightkg:25.3,color:"Red",prevo:"shelmet",evoLevel:1,eggGroups:["Bug"]}, stunfisk:{num:618,species:"Stunfisk",types:["Ground","Electric"],baseStats:{hp:109,atk:66,def:84,spa:81,spd:99,spe:32},abilities:{0:"Static",1:"Limber",H:"Sand Veil"},heightm:0.7,weightkg:11,color:"Brown",eggGroups:["Water 1","Amorphous"]}, mienfoo:{num:619,species:"Mienfoo",types:["Fighting"],baseStats:{hp:45,atk:85,def:50,spa:55,spd:50,spe:65},abilities:{0:"Inner Focus",1:"Regenerator",H:"Reckless"},heightm:0.9,weightkg:20,color:"Yellow",evos:["mienshao"],eggGroups:["Field","Human-Like"]}, mienshao:{num:620,species:"Mienshao",types:["Fighting"],baseStats:{hp:65,atk:125,def:60,spa:95,spd:60,spe:105},abilities:{0:"Inner Focus",1:"Regenerator",H:"Reckless"},heightm:1.4,weightkg:35.5,color:"Purple",prevo:"mienfoo",evoLevel:50,eggGroups:["Field","Human-Like"]}, druddigon:{num:621,species:"Druddigon",types:["Dragon"],baseStats:{hp:77,atk:120,def:90,spa:60,spd:90,spe:48},abilities:{0:"Rough Skin",1:"Sheer Force",H:"Mold Breaker"},heightm:1.6,weightkg:139,color:"Red",eggGroups:["Monster","Dragon"]}, golett:{num:622,species:"Golett",types:["Ground","Ghost"],gender:"N",baseStats:{hp:59,atk:74,def:50,spa:35,spd:50,spe:35},abilities:{0:"Iron Fist",1:"Klutz",H:"No Guard"},heightm:1,weightkg:92,color:"Green",evos:["golurk"],eggGroups:["Mineral"]}, golurk:{num:623,species:"Golurk",types:["Ground","Ghost"],gender:"N",baseStats:{hp:89,atk:124,def:80,spa:55,spd:80,spe:55},abilities:{0:"Iron Fist",1:"Klutz",H:"No Guard"},heightm:2.8,weightkg:330,color:"Green",prevo:"golett",evoLevel:43,eggGroups:["Mineral"]}, pawniard:{num:624,species:"Pawniard",types:["Dark","Steel"],baseStats:{hp:45,atk:85,def:70,spa:40,spd:40,spe:60},abilities:{0:"Defiant",1:"Inner Focus",H:"Pressure"},heightm:0.5,weightkg:10.2,color:"Red",evos:["bisharp"],eggGroups:["Human-Like"]}, bisharp:{num:625,species:"Bisharp",types:["Dark","Steel"],baseStats:{hp:65,atk:125,def:100,spa:60,spd:70,spe:70},abilities:{0:"Defiant",1:"Inner Focus",H:"Pressure"},heightm:1.6,weightkg:70,color:"Red",prevo:"pawniard",evoLevel:52,eggGroups:["Human-Like"]}, bouffalant:{num:626,species:"Bouffalant",types:["Normal"],baseStats:{hp:95,atk:110,def:95,spa:40,spd:95,spe:55},abilities:{0:"Reckless",1:"Sap Sipper",H:"Soundproof"},heightm:1.6,weightkg:94.6,color:"Brown",eggGroups:["Field"]}, rufflet:{num:627,species:"Rufflet",types:["Normal","Flying"],gender:"M",baseStats:{hp:70,atk:83,def:50,spa:37,spd:50,spe:60},abilities:{0:"Keen Eye",1:"Sheer Force",H:"Hustle"},heightm:0.5,weightkg:10.5,color:"White",evos:["braviary"],eggGroups:["Flying"]}, braviary:{num:628,species:"Braviary",types:["Normal","Flying"],gender:"M",baseStats:{hp:100,atk:123,def:75,spa:57,spd:75,spe:80},abilities:{0:"Keen Eye",1:"Sheer Force",H:"Defiant"},heightm:1.5,weightkg:41,color:"Red",prevo:"rufflet",evoLevel:54,eggGroups:["Flying"]}, vullaby:{num:629,species:"Vullaby",types:["Dark","Flying"],gender:"F",baseStats:{hp:70,atk:55,def:75,spa:45,spd:65,spe:60},abilities:{0:"Big Pecks",1:"Overcoat",H:"Weak Armor"},heightm:0.5,weightkg:9,color:"Brown",evos:["mandibuzz"],eggGroups:["Flying"]}, mandibuzz:{num:630,species:"Mandibuzz",types:["Dark","Flying"],gender:"F",baseStats:{hp:110,atk:65,def:105,spa:55,spd:95,spe:80},abilities:{0:"Big Pecks",1:"Overcoat",H:"Weak Armor"},heightm:1.2,weightkg:39.5,color:"Brown",prevo:"vullaby",evoLevel:54,eggGroups:["Flying"]}, heatmor:{num:631,species:"Heatmor",types:["Fire"],baseStats:{hp:85,atk:97,def:66,spa:105,spd:66,spe:65},abilities:{0:"Gluttony",1:"Flash Fire",H:"White Smoke"},heightm:1.4,weightkg:58,color:"Red",eggGroups:["Field"]}, durant:{num:632,species:"Durant",types:["Bug","Steel"],baseStats:{hp:58,atk:109,def:112,spa:48,spd:48,spe:109},abilities:{0:"Swarm",1:"Hustle",H:"Truant"},heightm:0.3,weightkg:33,color:"Gray",eggGroups:["Bug"]}, deino:{num:633,species:"Deino",types:["Dark","Dragon"],baseStats:{hp:52,atk:65,def:50,spa:45,spd:50,spe:38},abilities:{0:"Hustle"},heightm:0.8,weightkg:17.3,color:"Blue",evos:["zweilous"],eggGroups:["Dragon"]}, zweilous:{num:634,species:"Zweilous",types:["Dark","Dragon"],baseStats:{hp:72,atk:85,def:70,spa:65,spd:70,spe:58},abilities:{0:"Hustle"},heightm:1.4,weightkg:50,color:"Blue",prevo:"deino",evos:["hydreigon"],evoLevel:50,eggGroups:["Dragon"]}, hydreigon:{num:635,species:"Hydreigon",types:["Dark","Dragon"],baseStats:{hp:92,atk:105,def:90,spa:125,spd:90,spe:98},abilities:{0:"Levitate"},heightm:1.8,weightkg:160,color:"Blue",prevo:"zweilous",evoLevel:64,eggGroups:["Dragon"]}, larvesta:{num:636,species:"Larvesta",types:["Bug","Fire"],baseStats:{hp:55,atk:85,def:55,spa:50,spd:55,spe:60},abilities:{0:"Flame Body",H:"Swarm"},heightm:1.1,weightkg:28.8,color:"White",evos:["volcarona"],eggGroups:["Bug"]}, volcarona:{num:637,species:"Volcarona",types:["Bug","Fire"],baseStats:{hp:85,atk:60,def:65,spa:135,spd:105,spe:100},abilities:{0:"Flame Body",H:"Swarm"},heightm:1.6,weightkg:46,color:"White",prevo:"larvesta",evoLevel:59,eggGroups:["Bug"]}, cobalion:{num:638,species:"Cobalion",types:["Steel","Fighting"],gender:"N",baseStats:{hp:91,atk:90,def:129,spa:90,spd:72,spe:108},abilities:{0:"Justified"},heightm:2.1,weightkg:250,color:"Blue",eggGroups:["Undiscovered"]}, terrakion:{num:639,species:"Terrakion",types:["Rock","Fighting"],gender:"N",baseStats:{hp:91,atk:129,def:90,spa:72,spd:90,spe:108},abilities:{0:"Justified"},heightm:1.9,weightkg:260,color:"Gray",eggGroups:["Undiscovered"]}, virizion:{num:640,species:"Virizion",types:["Grass","Fighting"],gender:"N",baseStats:{hp:91,atk:90,def:72,spa:90,spd:129,spe:108},abilities:{0:"Justified"},heightm:2,weightkg:200,color:"Green",eggGroups:["Undiscovered"]}, tornadus:{num:641,species:"Tornadus",baseForme:"Incarnate",types:["Flying"],gender:"M",baseStats:{hp:79,atk:115,def:70,spa:125,spd:80,spe:111},abilities:{0:"Prankster",H:"Defiant"},heightm:1.5,weightkg:63,color:"Green",eggGroups:["Undiscovered"],otherFormes:["tornadustherian"]}, tornadustherian:{num:641,species:"Tornadus-Therian",baseSpecies:"Tornadus",forme:"Therian",formeLetter:"T",types:["Flying"],gender:"M",baseStats:{hp:79,atk:100,def:80,spa:110,spd:90,spe:121},abilities:{0:"Regenerator"},heightm:1.4,weightkg:63,color:"Green",eggGroups:["Undiscovered"]}, thundurus:{num:642,species:"Thundurus",baseForme:"Incarnate",types:["Electric","Flying"],gender:"M",baseStats:{hp:79,atk:115,def:70,spa:125,spd:80,spe:111},abilities:{0:"Prankster",H:"Defiant"},heightm:1.5,weightkg:61,color:"Blue",eggGroups:["Undiscovered"],otherFormes:["thundurustherian"]}, thundurustherian:{num:642,species:"Thundurus-Therian",baseSpecies:"Thundurus",forme:"Therian",formeLetter:"T",types:["Electric","Flying"],gender:"M",baseStats:{hp:79,atk:105,def:70,spa:145,spd:80,spe:101},abilities:{0:"Volt Absorb"},heightm:3,weightkg:61,color:"Blue",eggGroups:["Undiscovered"]}, reshiram:{num:643,species:"Reshiram",types:["Dragon","Fire"],gender:"N",baseStats:{hp:100,atk:120,def:100,spa:150,spd:120,spe:90},abilities:{0:"Turboblaze"},heightm:3.2,weightkg:330,color:"White",eggGroups:["Undiscovered"]}, zekrom:{num:644,species:"Zekrom",types:["Dragon","Electric"],gender:"N",baseStats:{hp:100,atk:150,def:120,spa:120,spd:100,spe:90},abilities:{0:"Teravolt"},heightm:2.9,weightkg:345,color:"Black",eggGroups:["Undiscovered"]}, landorus:{num:645,species:"Landorus",baseForme:"Incarnate",types:["Ground","Flying"],gender:"M",baseStats:{hp:89,atk:125,def:90,spa:115,spd:80,spe:101},abilities:{0:"Sand Force",H:"Sheer Force"},heightm:1.5,weightkg:68,color:"Brown",eggGroups:["Undiscovered"],otherFormes:["landorustherian"]}, landorustherian:{num:645,species:"Landorus-Therian",baseSpecies:"Landorus",forme:"Therian",formeLetter:"T",types:["Ground","Flying"],gender:"M",baseStats:{hp:89,atk:145,def:90,spa:105,spd:80,spe:91},abilities:{0:"Intimidate"},heightm:1.3,weightkg:68,color:"Brown",eggGroups:["Undiscovered"]}, kyurem:{num:646,species:"Kyurem",types:["Dragon","Ice"],gender:"N",baseStats:{hp:125,atk:130,def:90,spa:130,spd:90,spe:95},abilities:{0:"Pressure"},heightm:3,weightkg:325,color:"Gray",eggGroups:["Undiscovered"],otherFormes:["kyuremblack","kyuremwhite"]}, kyuremblack:{num:646,species:"Kyurem-Black",baseSpecies:"Kyurem",forme:"Black",formeLetter:"B",types:["Dragon","Ice"],gender:"N",baseStats:{hp:125,atk:170,def:100,spa:120,spd:90,spe:95},abilities:{0:"Teravolt"},heightm:3.3,weightkg:325,color:"Gray",eggGroups:["Undiscovered"]}, kyuremwhite:{num:646,species:"Kyurem-White",baseSpecies:"Kyurem",forme:"White",formeLetter:"W",types:["Dragon","Ice"],gender:"N",baseStats:{hp:125,atk:120,def:90,spa:170,spd:100,spe:95},abilities:{0:"Turboblaze"},heightm:3.6,weightkg:325,color:"Gray",eggGroups:["Undiscovered"]}, keldeo:{num:647,species:"Keldeo",baseForme:"Ordinary",types:["Water","Fighting"],gender:"N",baseStats:{hp:91,atk:72,def:90,spa:129,spd:90,spe:108},abilities:{0:"Justified"},heightm:1.4,weightkg:48.5,color:"Yellow",eggGroups:["Undiscovered"],otherFormes:["keldeoresolute"]}, keldeoresolute:{num:647,species:"Keldeo-Resolute",baseSpecies:"Keldeo",forme:"Resolute",formeLetter:"R",types:["Water","Fighting"],gender:"N",baseStats:{hp:91,atk:72,def:90,spa:129,spd:90,spe:108},abilities:{0:"Justified"},heightm:1.4,weightkg:48.5,color:"Yellow",eggGroups:["Undiscovered"]}, meloetta:{num:648,species:"Meloetta",baseForme:"Aria",types:["Normal","Psychic"],gender:"N",baseStats:{hp:100,atk:77,def:77,spa:128,spd:128,spe:90},abilities:{0:"Serene Grace"},heightm:0.6,weightkg:6.5,color:"White",eggGroups:["Undiscovered"],otherFormes:["meloettapirouette"]}, meloettapirouette:{num:648,species:"Meloetta-Pirouette",baseSpecies:"Meloetta",forme:"Pirouette",formeLetter:"P",types:["Normal","Fighting"],gender:"N",baseStats:{hp:100,atk:128,def:90,spa:77,spd:77,spe:128},abilities:{0:"Serene Grace"},heightm:0.6,weightkg:6.5,color:"White",eggGroups:["Undiscovered"]}, genesect:{num:649,species:"Genesect",types:["Bug","Steel"],gender:"N",baseStats:{hp:71,atk:120,def:95,spa:120,spd:95,spe:99},abilities:{0:"Download"},heightm:1.5,weightkg:82.5,color:"Purple",eggGroups:["Undiscovered"],otherFormes:["genesectdouse","genesectshock","genesectburn","genesectchill"]}, genesectdouse:{num:649,species:"Genesect-Douse",baseSpecies:"Genesect",forme:"Douse",formeLetter:"D",types:["Bug","Steel"],gender:"N",baseStats:{hp:71,atk:120,def:95,spa:120,spd:95,spe:99},abilities:{0:"Download"},heightm:1.5,weightkg:82.5,color:"Purple",eggGroups:["Undiscovered"]}, genesectshock:{num:649,species:"Genesect-Shock",baseSpecies:"Genesect",forme:"Shock",formeLetter:"S",types:["Bug","Steel"],gender:"N",baseStats:{hp:71,atk:120,def:95,spa:120,spd:95,spe:99},abilities:{0:"Download"},heightm:1.5,weightkg:82.5,color:"Purple",eggGroups:["Undiscovered"]}, genesectburn:{num:649,species:"Genesect-Burn",baseSpecies:"Genesect",forme:"Burn",formeLetter:"B",types:["Bug","Steel"],gender:"N",baseStats:{hp:71,atk:120,def:95,spa:120,spd:95,spe:99},abilities:{0:"Download"},heightm:1.5,weightkg:82.5,color:"Purple",eggGroups:["Undiscovered"]}, genesectchill:{num:649,species:"Genesect-Chill",baseSpecies:"Genesect",forme:"Chill",formeLetter:"C",types:["Bug","Steel"],gender:"N",baseStats:{hp:71,atk:120,def:95,spa:120,spd:95,spe:99},abilities:{0:"Download"},heightm:1.5,weightkg:82.5,color:"Purple",eggGroups:["Undiscovered"]}, chespin:{num:650,species:"Chespin",types:["Grass"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:56,atk:61,def:65,spa:48,spd:45,spe:38},abilities:{0:"Overgrow",H:"Bulletproof"},heightm:0.4,weightkg:9,color:"Green",evos:["quilladin"],eggGroups:["Field"]}, quilladin:{num:651,species:"Quilladin",types:["Grass"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:61,atk:78,def:95,spa:56,spd:58,spe:57},abilities:{0:"Overgrow",H:"Bulletproof"},heightm:0.7,weightkg:29,color:"Green",prevo:"chespin",evos:["chesnaught"],evoLevel:16,eggGroups:["Field"]}, chesnaught:{num:652,species:"Chesnaught",types:["Grass","Fighting"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:88,atk:107,def:122,spa:74,spd:75,spe:64},abilities:{0:"Overgrow",H:"Bulletproof"},heightm:1.6,weightkg:90,color:"Green",prevo:"quilladin",evoLevel:36,eggGroups:["Field"]}, fennekin:{num:653,species:"Fennekin",types:["Fire"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:40,atk:45,def:40,spa:62,spd:60,spe:60},abilities:{0:"Blaze",H:"Magician"},heightm:0.4,weightkg:9.4,color:"Red",evos:["braixen"],eggGroups:["Field"]}, braixen:{num:654,species:"Braixen",types:["Fire"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:59,atk:59,def:58,spa:90,spd:70,spe:73},abilities:{0:"Blaze",H:"Magician"},heightm:1,weightkg:14.5,color:"Red",prevo:"fennekin",evos:["delphox"],evoLevel:16,eggGroups:["Field"]}, delphox:{num:655,species:"Delphox",types:["Fire","Psychic"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:75,atk:69,def:72,spa:114,spd:100,spe:104},abilities:{0:"Blaze",H:"Magician"},heightm:1.5,weightkg:39,color:"Red",prevo:"braixen",evoLevel:36,eggGroups:["Field"]}, froakie:{num:656,species:"Froakie",types:["Water"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:41,atk:56,def:40,spa:62,spd:44,spe:71},abilities:{0:"Torrent",H:"Protean"},heightm:0.3,weightkg:7,color:"Blue",evos:["frogadier"],eggGroups:["Water 1"]}, frogadier:{num:657,species:"Frogadier",types:["Water"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:54,atk:63,def:52,spa:83,spd:56,spe:97},abilities:{0:"Torrent",H:"Protean"},heightm:0.6,weightkg:10.9,color:"Blue",prevo:"froakie",evos:["greninja"],evoLevel:16,eggGroups:["Water 1"]}, greninja:{num:658,species:"Greninja",types:["Water","Dark"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:72,atk:95,def:67,spa:103,spd:71,spe:122},abilities:{0:"Torrent",H:"Protean"},heightm:1.5,weightkg:40,color:"Blue",prevo:"frogadier",evoLevel:36,eggGroups:["Water 1"]}, bunnelby:{num:659,species:"Bunnelby",types:["Normal"],baseStats:{hp:38,atk:36,def:38,spa:32,spd:36,spe:57},abilities:{0:"Pickup",1:"Cheek Pouch",H:"Huge Power"},heightm:0.4,weightkg:5,color:"Brown",evos:["diggersby"],eggGroups:["Field"]}, diggersby:{num:660,species:"Diggersby",types:["Normal","Ground"],baseStats:{hp:85,atk:56,def:77,spa:50,spd:77,spe:78},abilities:{0:"Pickup",1:"Cheek Pouch",H:"Huge Power"},heightm:1,weightkg:42.4,color:"Brown",prevo:"bunnelby",evoLevel:20,eggGroups:["Field"]}, fletchling:{num:661,species:"Fletchling",types:["Normal","Flying"],baseStats:{hp:45,atk:50,def:43,spa:40,spd:38,spe:62},abilities:{0:"Big Pecks",H:"Gale Wings"},heightm:0.3,weightkg:1.7,color:"Red",evos:["fletchinder"],eggGroups:["Flying"]}, fletchinder:{num:662,species:"Fletchinder",types:["Fire","Flying"],baseStats:{hp:62,atk:73,def:55,spa:56,spd:52,spe:84},abilities:{0:"Flame Body",H:"Gale Wings"},heightm:0.7,weightkg:16,color:"Red",prevo:"fletchling",evos:["talonflame"],evoLevel:17,eggGroups:["Flying"]}, talonflame:{num:663,species:"Talonflame",types:["Fire","Flying"],baseStats:{hp:78,atk:81,def:71,spa:74,spd:69,spe:126},abilities:{0:"Flame Body",H:"Gale Wings"},heightm:1.2,weightkg:24.5,color:"Red",prevo:"fletchinder",evoLevel:35,eggGroups:["Flying"]}, scatterbug:{num:664,species:"Scatterbug",types:["Bug"],baseStats:{hp:38,atk:35,def:40,spa:27,spd:25,spe:35},abilities:{0:"Shield Dust",1:"Compound Eyes",H:"Friend Guard"},heightm:0.3,weightkg:2.5,color:"Black",evos:["spewpa"],eggGroups:["Bug"]}, spewpa:{num:665,species:"Spewpa",types:["Bug"],baseStats:{hp:45,atk:22,def:60,spa:27,spd:30,spe:29},abilities:{0:"Shed Skin",H:"Friend Guard"},heightm:0.3,weightkg:8.4,color:"Black",prevo:"scatterbug",evos:["vivillon"],evoLevel:9,eggGroups:["Bug"]}, vivillon:{num:666,species:"Vivillon",types:["Bug","Flying"],baseStats:{hp:80,atk:52,def:50,spa:90,spd:50,spe:89},abilities:{0:"Shield Dust",1:"Compound Eyes",H:"Friend Guard"},heightm:1.2,weightkg:17,color:"Black",prevo:"spewpa",evoLevel:12,eggGroups:["Bug"]}, litleo:{num:667,species:"Litleo",types:["Fire","Normal"],baseStats:{hp:62,atk:50,def:58,spa:73,spd:54,spe:72},abilities:{0:"Rivalry",1:"Unnerve",H:"Moxie"},heightm:0.6,weightkg:13.5,color:"Brown",evos:["pyroar"],eggGroups:["Field"]}, pyroar:{num:668,species:"Pyroar",types:["Fire","Normal"],genderRatio:{M:0.25,F:0.75},baseStats:{hp:86,atk:68,def:72,spa:109,spd:66,spe:106},abilities:{0:"Rivalry",1:"Unnerve",H:"Moxie"},heightm:1.5,weightkg:81.5,color:"Brown",prevo:"litleo",evoLevel:35,eggGroups:["Field"]}, flabebe:{num:669,species:"Flabebe",types:["Fairy"],gender:"F",baseStats:{hp:44,atk:38,def:39,spa:61,spd:79,spe:42},abilities:{0:"Flower Veil",H:"Symbiosis"},heightm:0.1,weightkg:0.1,color:"White",evos:["floette"],eggGroups:["Fairy"]}, floette:{num:670,species:"Floette",baseForme:"Red-Flower",types:["Fairy"],gender:"F",baseStats:{hp:54,atk:45,def:47,spa:75,spd:98,spe:52},abilities:{0:"Flower Veil",H:"Symbiosis"},heightm:0.2,weightkg:0.9,color:"White",prevo:"flabebe",evos:["florges"],evoLevel:19,eggGroups:["Fairy"],otherForms:["floetteeternalflower"]}, floetteeternalflower:{num:670,species:"Floette-Eternal-Flower",baseSpecies:"Floette",forme:"Eternal-Flower",formeLetter:"E",types:["Fairy"],gender:"F",baseStats:{hp:74,atk:65,def:67,spa:125,spd:128,spe:92},abilities:{0:"Flower Veil"},heightm:0.2,weightkg:0.9,color:"White",prevo:"flabebe",evoLevel:19,eggGroups:["Fairy"]}, florges:{num:671,species:"Florges",types:["Fairy"],gender:"F",baseStats:{hp:78,atk:65,def:68,spa:112,spd:154,spe:75},abilities:{0:"Flower Veil",H:"Symbiosis"},heightm:1.1,weightkg:10,color:"White",prevo:"floette",evoLevel:19,eggGroups:["Fairy"]}, skiddo:{num:672,species:"Skiddo",types:["Grass"],baseStats:{hp:66,atk:65,def:48,spa:62,spd:57,spe:52},abilities:{0:"Sap Sipper",H:"Grass Pelt"},heightm:0.9,weightkg:31,color:"Brown",evos:["gogoat"],eggGroups:["Field"]}, gogoat:{num:673,species:"Gogoat",types:["Grass"],baseStats:{hp:123,atk:100,def:62,spa:97,spd:81,spe:68},abilities:{0:"Sap Sipper",H:"Grass Pelt"},heightm:1.7,weightkg:91,color:"Brown",prevo:"skiddo",evoLevel:32,eggGroups:["Field"]}, pancham:{num:674,species:"Pancham",types:["Fighting"],baseStats:{hp:67,atk:82,def:62,spa:46,spd:48,spe:43},abilities:{0:"Iron Fist",1:"Mold Breaker",H:"Scrappy"},heightm:0.6,weightkg:8,color:"White",evos:["pangoro"],eggGroups:["Field","Human-Like"]}, pangoro:{num:675,species:"Pangoro",types:["Fighting","Dark"],baseStats:{hp:95,atk:124,def:78,spa:69,spd:71,spe:58},abilities:{0:"Iron Fist",1:"Mold Breaker",H:"Scrappy"},heightm:2.1,weightkg:136,color:"White",prevo:"pancham",evoLevel:32,eggGroups:["Field","Human-Like"]}, furfrou:{num:676,species:"Furfrou",types:["Normal"],baseStats:{hp:75,atk:80,def:60,spa:65,spd:90,spe:102},abilities:{0:"Fur Coat"},heightm:1.2,weightkg:28,color:"White",eggGroups:["Field"]}, espurr:{num:677,species:"Espurr",types:["Psychic"],baseStats:{hp:62,atk:48,def:54,spa:63,spd:60,spe:68},abilities:{0:"Keen Eye",1:"Infiltrator",H:"Own Tempo"},heightm:0.3,weightkg:3.5,color:"Gray",evos:["meowstic"],eggGroups:["Field"]}, meowstic:{num:678,species:"Meowstic",baseForme:"M",types:["Psychic"],gender:"M",baseStats:{hp:74,atk:48,def:76,spa:83,spd:81,spe:104},abilities:{0:"Keen Eye",1:"Infiltrator",H:"Prankster"},heightm:0.6,weightkg:8.5,color:"White",prevo:"espurr",evoLevel:25,eggGroups:["Field"],otherFormes:["meowsticf"]}, meowsticf:{num:678,species:"Meowstic-F",baseSpecies:"Meowstic",forme:"F",formeLetter:"F",types:["Psychic"],gender:"F",baseStats:{hp:74,atk:48,def:76,spa:83,spd:81,spe:104},abilities:{0:"Keen Eye",1:"Infiltrator",H:"Competitive"},heightm:0.6,weightkg:8.5,color:"White",prevo:"espurr",evoLevel:25,eggGroups:["Field"]}, honedge:{num:679,species:"Honedge",types:["Steel","Ghost"],baseStats:{hp:45,atk:80,def:100,spa:35,spd:37,spe:28},abilities:{0:"No Guard"},heightm:0.8,weightkg:2,color:"Brown",evos:["doublade"],eggGroups:["Mineral"]}, doublade:{num:680,species:"Doublade",types:["Steel","Ghost"],baseStats:{hp:59,atk:110,def:150,spa:45,spd:49,spe:35},abilities:{0:"No Guard"},heightm:0.8,weightkg:4.5,color:"Brown",prevo:"honedge",evos:["aegislash"],evoLevel:35,eggGroups:["Mineral"]}, aegislash:{num:681,species:"Aegislash",types:["Steel","Ghost"],baseStats:{hp:60,atk:50,def:150,spa:50,spd:150,spe:60},abilities:{0:"Stance Change"},heightm:1.7,weightkg:53,color:"Brown",prevo:"doublade",evoLevel:35,eggGroups:["Mineral"],otherFormes:["aegislashblade"]}, aegislashblade:{num:681,species:"Aegislash-Blade",baseSpecies:"Aegislash",forme:"Blade",formeLetter:"B",types:["Steel","Ghost"],baseStats:{hp:60,atk:150,def:50,spa:150,spd:50,spe:60},abilities:{0:"Stance Change"},heightm:1.7,weightkg:53,color:"Brown",prevo:"doublade",evoLevel:35,eggGroups:["Mineral"]}, spritzee:{num:682,species:"Spritzee",types:["Fairy"],baseStats:{hp:78,atk:52,def:60,spa:63,spd:65,spe:23},abilities:{0:"Healer",H:"Aroma Veil"},heightm:0.2,weightkg:0.5,color:"Pink",evos:["aromatisse"],eggGroups:["Fairy"]}, aromatisse:{num:683,species:"Aromatisse",types:["Fairy"],baseStats:{hp:101,atk:72,def:72,spa:99,spd:89,spe:29},abilities:{0:"Healer",H:"Aroma Veil"},heightm:0.8,weightkg:15.5,color:"Pink",prevo:"spritzee",evoLevel:1,eggGroups:["Fairy"]}, swirlix:{num:684,species:"Swirlix",types:["Fairy"],baseStats:{hp:62,atk:48,def:66,spa:59,spd:57,spe:49},abilities:{0:"Sweet Veil",H:"Unburden"},heightm:0.4,weightkg:3.5,color:"White",evos:["slurpuff"],eggGroups:["Fairy"]}, slurpuff:{num:685,species:"Slurpuff",types:["Fairy"],baseStats:{hp:82,atk:80,def:86,spa:85,spd:75,spe:72},abilities:{0:"Sweet Veil",H:"Unburden"},heightm:0.8,weightkg:5,color:"White",prevo:"swirlix",evoLevel:1,eggGroups:["Fairy"]}, inkay:{num:686,species:"Inkay",types:["Dark","Psychic"],baseStats:{hp:53,atk:54,def:53,spa:37,spd:46,spe:45},abilities:{0:"Contrary",1:"Suction Cups",H:"Infiltrator"},heightm:0.4,weightkg:3.5,color:"Blue",evos:["malamar"],eggGroups:["Water 1","Water 2"]}, malamar:{num:687,species:"Malamar",types:["Dark","Psychic"],baseStats:{hp:86,atk:92,def:88,spa:68,spd:75,spe:73},abilities:{0:"Contrary",1:"Suction Cups",H:"Infiltrator"},heightm:1.5,weightkg:47,color:"Blue",prevo:"inkay",evoLevel:30,eggGroups:["Water 1","Water 2"]}, binacle:{num:688,species:"Binacle",types:["Rock","Water"],baseStats:{hp:42,atk:52,def:67,spa:39,spd:56,spe:50},abilities:{0:"Tough Claws",1:"Sniper",H:"Pickpocket"},heightm:0.5,weightkg:31,color:"Brown",evos:["barbaracle"],eggGroups:["Water 3"]}, barbaracle:{num:689,species:"Barbaracle",types:["Rock","Water"],baseStats:{hp:72,atk:105,def:115,spa:54,spd:86,spe:68},abilities:{0:"Tough Claws",1:"Sniper",H:"Pickpocket"},heightm:1.3,weightkg:96,color:"Brown",prevo:"binacle",evoLevel:39,eggGroups:["Water 3"]}, skrelp:{num:690,species:"Skrelp",types:["Poison","Water"],baseStats:{hp:50,atk:60,def:60,spa:60,spd:60,spe:30},abilities:{0:"Poison Point",1:"Poison Touch",H:"Adaptability"},heightm:0.5,weightkg:7.3,color:"Brown",evos:["dragalge"],eggGroups:["Water 1","Dragon"]}, dragalge:{num:691,species:"Dragalge",types:["Poison","Dragon"],baseStats:{hp:65,atk:75,def:90,spa:97,spd:123,spe:44},abilities:{0:"Poison Point",1:"Poison Touch",H:"Adaptability"},heightm:1.8,weightkg:81.5,color:"Brown",prevo:"skrelp",evoLevel:37,eggGroups:["Water 1","Dragon"]}, clauncher:{num:692,species:"Clauncher",types:["Water"],baseStats:{hp:50,atk:53,def:62,spa:58,spd:63,spe:44},abilities:{0:"Mega Launcher"},heightm:0.5,weightkg:8.3,color:"Blue",evos:["clawitzer"],eggGroups:["Water 1","Water 3"]}, clawitzer:{num:693,species:"Clawitzer",types:["Water"],baseStats:{hp:71,atk:73,def:88,spa:120,spd:89,spe:59},abilities:{0:"Mega Launcher"},heightm:1.3,weightkg:35.3,color:"Blue",prevo:"clauncher",evoLevel:37,eggGroups:["Water 1","Water 3"]}, helioptile:{num:694,species:"Helioptile",types:["Electric","Normal"],baseStats:{hp:44,atk:38,def:33,spa:61,spd:43,spe:70},abilities:{0:"Dry Skin",1:"Sand Veil",H:"Solar Power"},heightm:0.5,weightkg:6,color:"Yellow",evos:["heliolisk"],eggGroups:["Monster","Dragon"]}, heliolisk:{num:695,species:"Heliolisk",types:["Electric","Normal"],baseStats:{hp:62,atk:55,def:52,spa:109,spd:94,spe:109},abilities:{0:"Dry Skin",1:"Sand Veil",H:"Solar Power"},heightm:1,weightkg:21,color:"Yellow",prevo:"helioptile",evoLevel:1,eggGroups:["Monster","Dragon"]}, tyrunt:{num:696,species:"Tyrunt",types:["Rock","Dragon"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:58,atk:89,def:77,spa:45,spd:45,spe:48},abilities:{0:"Strong Jaw",H:"Sturdy"},heightm:0.8,weightkg:26,color:"Brown",evos:["tyrantrum"],eggGroups:["Monster","Dragon"]}, tyrantrum:{num:697,species:"Tyrantrum",types:["Rock","Dragon"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:82,atk:121,def:119,spa:69,spd:59,spe:71},abilities:{0:"Strong Jaw",H:"Rock Head"},heightm:2.5,weightkg:270,color:"Red",prevo:"tyrunt",evoLevel:39,eggGroups:["Monster","Dragon"]}, amaura:{num:698,species:"Amaura",types:["Rock","Ice"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:77,atk:59,def:50,spa:67,spd:63,spe:46},abilities:{0:"Refrigerate",H:"Snow Warning"},heightm:1.3,weightkg:25.2,color:"Blue",evos:["aurorus"],eggGroups:["Monster"]}, aurorus:{num:699,species:"Aurorus",types:["Rock","Ice"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:123,atk:77,def:72,spa:99,spd:92,spe:58},abilities:{0:"Refrigerate",H:"Snow Warning"},heightm:2.7,weightkg:225,color:"Blue",prevo:"amaura",evoLevel:39,eggGroups:["Monster"]}, sylveon:{num:700,species:"Sylveon",types:["Fairy"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:95,atk:65,def:65,spa:110,spd:130,spe:60},abilities:{0:"Cute Charm",H:"Pixilate"},heightm:1,weightkg:23.5,color:"Pink",prevo:"eevee",evoLevel:2,eggGroups:["Field"]}, hawlucha:{num:701,species:"Hawlucha",types:["Fighting","Flying"],baseStats:{hp:78,atk:92,def:75,spa:74,spd:63,spe:118},abilities:{0:"Limber",1:"Unburden",H:"Mold Breaker"},heightm:0.8,weightkg:21.5,color:"Green",eggGroups:["Human-Like"]}, dedenne:{num:702,species:"Dedenne",types:["Electric","Fairy"],baseStats:{hp:67,atk:58,def:57,spa:81,spd:67,spe:101},abilities:{0:"Cheek Pouch",1:"Pickup",H:"Plus"},heightm:0.2,weightkg:2.2,color:"Yellow",eggGroups:["Field","Fairy"]}, carbink:{num:703,species:"Carbink",types:["Rock","Fairy"],gender:"N",baseStats:{hp:50,atk:50,def:150,spa:50,spd:150,spe:50},abilities:{0:"Clear Body",H:"Sturdy"},heightm:0.3,weightkg:5.7,color:"Gray",eggGroups:["Fairy","Mineral"]}, goomy:{num:704,species:"Goomy",types:["Dragon"],baseStats:{hp:45,atk:50,def:35,spa:55,spd:75,spe:40},abilities:{0:"Sap Sipper",1:"Hydration",H:"Gooey"},heightm:0.3,weightkg:2.8,color:"Purple",evos:["sliggoo"],eggGroups:["Dragon"]}, sliggoo:{num:705,species:"Sliggoo",types:["Dragon"],baseStats:{hp:68,atk:75,def:53,spa:83,spd:113,spe:60},abilities:{0:"Sap Sipper",1:"Hydration",H:"Gooey"},heightm:0.8,weightkg:17.5,color:"Purple",prevo:"goomy",evos:["goodra"],evoLevel:40,eggGroups:["Dragon"]}, goodra:{num:706,species:"Goodra",types:["Dragon"],baseStats:{hp:90,atk:100,def:70,spa:110,spd:150,spe:80},abilities:{0:"Sap Sipper",1:"Hydration",H:"Gooey"},heightm:2,weightkg:150.5,color:"Purple",prevo:"sliggoo",evoLevel:50,eggGroups:["Dragon"]}, klefki:{num:707,species:"Klefki",types:["Steel","Fairy"],baseStats:{hp:57,atk:80,def:91,spa:80,spd:87,spe:75},abilities:{0:"Prankster",H:"Magician"},heightm:0.2,weightkg:3,color:"Gray",eggGroups:["Mineral"]}, phantump:{num:708,species:"Phantump",types:["Ghost","Grass"],baseStats:{hp:43,atk:70,def:48,spa:50,spd:60,spe:38},abilities:{0:"Natural Cure",1:"Frisk",H:"Harvest"},heightm:0.4,weightkg:7,color:"Brown",evos:["trevenant"],eggGroups:["Grass","Amorphous"]}, trevenant:{num:709,species:"Trevenant",types:["Ghost","Grass"],baseStats:{hp:85,atk:110,def:76,spa:65,spd:82,spe:56},abilities:{0:"Natural Cure",1:"Frisk",H:"Harvest"},heightm:1.5,weightkg:71,color:"Brown",prevo:"phantump",evoLevel:1,eggGroups:["Grass","Amorphous"]}, pumpkaboo:{num:710,species:"Pumpkaboo",baseForme:"Average",types:["Ghost","Grass"],baseStats:{hp:49,atk:66,def:70,spa:44,spd:55,spe:51},abilities:{0:"Pickup",1:"Frisk",H:"Insomnia"},heightm:0.4,weightkg:5,color:"Brown",evos:["gourgeist"],eggGroups:["Amorphous"],otherFormes:["pumpkaboosmall","pumpkaboolarge","pumpkaboosuper"]}, pumpkaboosmall:{num:710,species:"Pumpkaboo-Small",baseSpecies:"Pumpkaboo",forme:"Small",formeLetter:"S",types:["Ghost","Grass"],baseStats:{hp:44,atk:66,def:70,spa:44,spd:55,spe:56},abilities:{0:"Pickup",1:"Frisk",H:"Insomnia"},heightm:0.3,weightkg:3.5,color:"Brown",evos:["gourgeistsmall"],eggGroups:["Amorphous"]}, pumpkaboolarge:{num:710,species:"Pumpkaboo-Large",baseSpecies:"Pumpkaboo",forme:"Large",formeLetter:"L",types:["Ghost","Grass"],baseStats:{hp:54,atk:66,def:70,spa:44,spd:55,spe:46},abilities:{0:"Pickup",1:"Frisk",H:"Insomnia"},heightm:0.5,weightkg:7.5,color:"Brown",evos:["gourgeistlarge"],eggGroups:["Amorphous"]}, pumpkaboosuper:{num:710,species:"Pumpkaboo-Super",baseSpecies:"Pumpkaboo",forme:"Super",formeLetter:"S",types:["Ghost","Grass"],baseStats:{hp:59,atk:66,def:70,spa:44,spd:55,spe:41},abilities:{0:"Pickup",1:"Frisk",H:"Insomnia"},heightm:0.8,weightkg:15,color:"Brown",evos:["gourgeistsuper"],eggGroups:["Amorphous"]}, gourgeist:{num:711,species:"Gourgeist",baseForme:"Average",types:["Ghost","Grass"],baseStats:{hp:65,atk:90,def:122,spa:58,spd:75,spe:84},abilities:{0:"Pickup",1:"Frisk",H:"Insomnia"},heightm:0.9,weightkg:12.5,color:"Brown",prevo:"pumpkaboo",evoLevel:1,eggGroups:["Amorphous"],otherFormes:["gourgeistsmall","gourgeistlarge","gourgeistsuper"]}, gourgeistsmall:{num:711,species:"Gourgeist-Small",baseSpecies:"Gourgeist",forme:"Small",formeLetter:"S",types:["Ghost","Grass"],baseStats:{hp:55,atk:85,def:122,spa:58,spd:75,spe:99},abilities:{0:"Pickup",1:"Frisk",H:"Insomnia"},heightm:0.7,weightkg:9.5,color:"Brown",prevo:"pumpkaboosmall",evoLevel:1,eggGroups:["Amorphous"]}, gourgeistlarge:{num:711,species:"Gourgeist-Large",baseSpecies:"Gourgeist",forme:"Large",formeLetter:"L",types:["Ghost","Grass"],baseStats:{hp:75,atk:95,def:122,spa:58,spd:75,spe:69},abilities:{0:"Pickup",1:"Frisk",H:"Insomnia"},heightm:1.1,weightkg:14,color:"Brown",prevo:"pumpkaboolarge",evoLevel:1,eggGroups:["Amorphous"]}, gourgeistsuper:{num:711,species:"Gourgeist-Super",baseSpecies:"Gourgeist",forme:"Super",formeLetter:"S",types:["Ghost","Grass"],baseStats:{hp:85,atk:100,def:122,spa:58,spd:75,spe:54},abilities:{0:"Pickup",1:"Frisk",H:"Insomnia"},heightm:1.7,weightkg:39,color:"Brown",prevo:"pumpkaboosuper",evoLevel:1,eggGroups:["Amorphous"]}, bergmite:{num:712,species:"Bergmite",types:["Ice"],baseStats:{hp:55,atk:69,def:85,spa:32,spd:35,spe:28},abilities:{0:"Own Tempo",1:"Ice Body",H:"Sturdy"},heightm:1,weightkg:99.5,color:"Blue",evos:["avalugg"],eggGroups:["Monster"]}, avalugg:{num:713,species:"Avalugg",types:["Ice"],baseStats:{hp:95,atk:117,def:184,spa:44,spd:46,spe:28},abilities:{0:"Own Tempo",1:"Ice Body",H:"Sturdy"},heightm:2,weightkg:505,color:"Blue",prevo:"bergmite",evoLevel:40,eggGroups:["Monster"]}, noibat:{num:714,species:"Noibat",types:["Flying","Dragon"],baseStats:{hp:40,atk:30,def:35,spa:45,spd:40,spe:55},abilities:{0:"Frisk",1:"Infiltrator",H:"Telepathy"},heightm:0.5,weightkg:8,color:"Purple",evos:["noivern"],eggGroups:["Flying"]}, noivern:{num:715,species:"Noivern",types:["Flying","Dragon"],baseStats:{hp:85,atk:70,def:80,spa:97,spd:80,spe:123},abilities:{0:"Frisk",1:"Infiltrator",H:"Telepathy"},heightm:1.5,weightkg:85,color:"Purple",prevo:"noibat",evoLevel:48,eggGroups:["Flying"]}, xerneas:{num:716,species:"Xerneas",types:["Fairy"],gender:"N",baseStats:{hp:126,atk:131,def:95,spa:131,spd:98,spe:99},abilities:{0:"Fairy Aura"},heightm:3,weightkg:215,color:"Blue",eggGroups:["Undiscovered"]}, yveltal:{num:717,species:"Yveltal",types:["Dark","Flying"],gender:"N",baseStats:{hp:126,atk:131,def:95,spa:131,spd:98,spe:99},abilities:{0:"Dark Aura"},heightm:5.8,weightkg:203,color:"Red",eggGroups:["Undiscovered"]}, zygarde:{num:718,species:"Zygarde",types:["Dragon","Ground"],gender:"N",baseStats:{hp:108,atk:100,def:121,spa:81,spd:95,spe:95},abilities:{0:"Aura Break"},heightm:5,weightkg:305,color:"Green",eggGroups:["Undiscovered"]}, diancie:{num:719,species:"Diancie",types:["Rock","Fairy"],gender:"N",baseStats:{hp:50,atk:100,def:150,spa:100,spd:150,spe:50},abilities:{0:"Clear Body"},heightm:0.7,weightkg:8.8,color:"Gray",eggGroups:["Undiscovered"]}, hoopa:{num:720,species:"Hoopa",types:["Psychic","Ghost"],gender:"N",baseStats:{hp:80,atk:110,def:60,spa:150,spd:130,spe:70},abilities:{0:"Magician"},heightm:0.5,weightkg:9,color:"Pink",eggGroups:["Undiscovered"]}, volcanion:{num:721,species:"Volcanion",types:["Fire","Water"],gender:"N",baseStats:{hp:80,atk:110,def:120,spa:130,spd:90,spe:70},abilities:{0:"Water Absorb"},heightm:1.7,weightkg:195,color:"Red",eggGroups:["Undiscovered"]}, missingno:{num:0,species:"Missingno.",types:["Bird","Normal"],baseStats:{hp:33,atk:136,def:0,spa:6,spd:6,spe:29},abilities:{0:"",H:""},heightm:3,weightkg:1590.8,color:"Gray",eggGroups:["Undiscovered"]}, tomohawk:{num:-1,species:"Tomohawk",types:["Flying","Fighting"],baseStats:{hp:105,atk:60,def:90,spa:115,spd:80,spe:85},abilities:{0:"Intimidate",1:"Prankster",H:"Justified"},heightm:1.27,weightkg:37.2,color:"Red",eggGroups:["Field","Flying"]}, necturna:{num:-2,species:"Necturna",types:["Grass","Ghost"],gender:"F",baseStats:{hp:64,atk:120,def:100,spa:85,spd:120,spe:81},abilities:{0:"Forewarn",H:"Telepathy"},heightm:1.65,weightkg:49.6,color:"Black",eggGroups:["Grass","Field"]}, mollux:{num:-3,species:"Mollux",types:["Fire","Poison"],baseStats:{hp:95,atk:45,def:83,spa:131,spd:105,spe:76},abilities:{0:"Dry Skin",H:"Illuminate"},heightm:1.2,weightkg:41,color:"Pink",eggGroups:["Fairy","Field"]}, aurumoth:{num:-4,species:"Aurumoth",types:["Bug","Psychic"],baseStats:{hp:110,atk:120,def:99,spa:117,spd:60,spe:94},abilities:{0:"Weak Armor",1:"No Guard",H:"Illusion"},heightm:2.1,weightkg:193,color:"Purple",eggGroups:["Bug"]}, malaconda:{num:-5,species:"Malaconda",types:["Dark","Grass"],baseStats:{hp:115,atk:100,def:60,spa:40,spd:130,spe:55},abilities:{0:"Harvest",1:"Infiltrator"},heightm:5.5,weightkg:108.8,color:"Brown",eggGroups:["Grass","Dragon"]}, cawmodore:{num:-6,species:"Cawmodore",types:["Steel","Flying"],baseStats:{hp:50,atk:92,def:130,spa:65,spd:75,spe:118},abilities:{0:"Intimidate",1:"Volt Absorb",H:"Big Pecks"},heightm:1.7,weightkg:37.0,color:"Black",eggGroups:["Flying"]}, volkraken:{num:-7,species:"Volkraken",types:["Water","Fire"],baseStats:{hp:100,atk:45,def:80,spa:135,spd:100,spe:95},abilities:{0:"Analytic",1:"Infiltrator",H:"Pressure"},heightm:1.3,weightkg:44.5,color:"Red",eggGroups:["Water 1","Water 2"]}, syclant:{num:-51,species:"Syclant",types:["Ice","Bug"],baseStats:{hp:70,atk:116,def:70,spa:114,spd:64,spe:121},abilities:{0:"Compound Eyes",1:"Mountaineer"},heightm:1.7,weightkg:52,color:"Blue",eggGroups:["Bug"]}, revenankh:{num:-52,species:"Revenankh",types:["Ghost","Fighting"],baseStats:{hp:90,atk:105,def:90,spa:65,spd:110,spe:65},abilities:{0:"Shed Skin",1:"Air Lock"},heightm:1.8,weightkg:44,color:"White",eggGroups:["Amorphous","Human-Like"]}, pyroak:{num:-53,species:"Pyroak",types:["Fire","Grass"],baseStats:{hp:120,atk:70,def:105,spa:95,spd:90,spe:60},abilities:{0:"Rock Head",1:"Battle Armor"},heightm:2.1,weightkg:168,color:"Brown",eggGroups:["Monster","Dragon"]}, fidgit:{num:-54,species:"Fidgit",types:["Poison","Ground"],baseStats:{hp:95,atk:76,def:109,spa:90,spd:80,spe:105},abilities:{0:"Persistent",1:"Vital Spirit"},heightm:0.9,weightkg:53,color:"Purple",eggGroups:["Field"]}, stratagem:{num:-55,species:"Stratagem",types:["Rock"],gender:"N",baseStats:{hp:90,atk:60,def:65,spa:120,spd:70,spe:130},abilities:{0:"Levitate",1:"Technician"},heightm:0.9,weightkg:45,color:"Gray",eggGroups:["Undiscovered"]}, arghonaut:{num:-56,species:"Arghonaut",types:["Water","Fighting"],baseStats:{hp:105,atk:110,def:95,spa:70,spd:100,spe:75},abilities:{0:"Unaware"},heightm:1.7,weightkg:151,color:"Green",eggGroups:["Water 1","Water 3"]}, kitsunoh:{num:-57,species:"Kitsunoh",types:["Steel","Ghost"],baseStats:{hp:80,atk:103,def:85,spa:55,spd:80,spe:110},abilities:{0:"Frisk",1:"Limber"},heightm:1.1,weightkg:51,color:"Gray",eggGroups:["Field"]}, cyclohm:{num:-58,species:"Cyclohm",types:["Electric","Dragon"],baseStats:{hp:108,atk:60,def:118,spa:112,spd:70,spe:80},abilities:{0:"Shield Dust",1:"Static"},heightm:1.6,weightkg:59,color:"Yellow",eggGroups:["Dragon","Monster"]}, colossoil:{num:-59,species:"Colossoil",types:["Dark","Ground"],baseStats:{hp:133,atk:122,def:72,spa:71,spd:72,spe:95},abilities:{0:"Rebound",1:"Guts"},heightm:2.6,weightkg:683.6,color:"Brown",eggGroups:["Water 2","Field"]}, krilowatt:{num:-60,species:"Krilowatt",types:["Electric","Water"],baseStats:{hp:151,atk:84,def:73,spa:83,spd:74,spe:105},abilities:{0:"Trace",1:"Magic Guard"},heightm:0.7,weightkg:10.6,color:"Red",eggGroups:["Water 1","Fairy"]}, voodoom:{num:-61,species:"Voodoom",types:["Fighting","Dark"],baseStats:{hp:90,atk:85,def:80,spa:105,spd:80,spe:110},abilities:{0:"Volt Absorb",1:"Lightningrod"},heightm:2,weightkg:75.5,color:"Brown",eggGroups:["Human-Like","Ground"]} };
AmCharts.mapTranslations.tt = {"Russia":"Россия"};
/* */ (function(process) { var validator = require("./validator"); module.exports = (function() { var sameValue = function(val1, val2) { return val1 === val2; }; var compactOverrides = function(tokens, processable, Token, compatibility) { var result, can, token, t, i, ii, iiii, oldResult, matchingComponent; var nameMatchFilter1 = function(x) { return x.prop === token.prop; }; var nameMatchFilter2 = function(x) { return x.prop === t.prop; }; function willResultInShorterValue(shorthand, token) { var shorthandCopy = shorthand.clone(); shorthandCopy.isDirty = true; shorthandCopy.isShorthand = true; shorthandCopy.components = []; shorthand.components.forEach(function(component) { var componentCopy = component.clone(); if (component.prop == token.prop) componentCopy.value = token.value; shorthandCopy.components.push(componentCopy); }); return Token.getDetokenizedLength([shorthand, token]) >= Token.getDetokenizedLength([shorthandCopy]); } for (result = tokens, i = 0; (ii = result.length - 1 - i) >= 0; i++) { token = result[ii]; can = (processable[token.prop] && processable[token.prop].canOverride) || sameValue; oldResult = result; result = []; var removeSelf = false; var oldResultLength = oldResult.length; for (var iii = 0; iii < oldResultLength; iii++) { t = oldResult[iii]; if (t === token && !removeSelf) { result.push(t); continue; } if (iii > ii && !token.isImportant) { result.push(t); continue; } if (iii > ii && t.isImportant && token.isImportant && t.prop != token.prop && t.isComponentOf(token)) { result.push(t); continue; } if (t.isImportant && !token.isImportant) { result.push(t); continue; } if (token.isShorthand && !t.isShorthand && t.isComponentOf(token)) { matchingComponent = token.components.filter(nameMatchFilter2)[0]; can = (processable[t.prop] && processable[t.prop].canOverride) || sameValue; if (!can(t.value, matchingComponent.value)) { result.push(t); } } else if (t.isShorthand && !token.isShorthand && token.isComponentOf(t)) { matchingComponent = t.components.filter(nameMatchFilter1)[0]; if (can(matchingComponent.value, token.value)) { var disabledForToken = !compatibility.properties.backgroundSizeMerging && token.prop.indexOf('background-size') > -1 || processable[token.prop].nonMergeableValue && processable[token.prop].nonMergeableValue == token.value; if (disabledForToken) { result.push(t); continue; } if (!compatibility.properties.merging) { var wouldBreakCompatibility = false; for (iiii = 0; iiii < t.components.length; iiii++) { var o = processable[t.components[iiii].prop]; can = (o && o.canOverride) || sameValue; if (!can(o.defaultValue, t.components[iiii].value)) { wouldBreakCompatibility = true; break; } } if (wouldBreakCompatibility) { result.push(t); continue; } } if ((!token.isImportant || token.isImportant && matchingComponent.isImportant) && willResultInShorterValue(t, token)) { matchingComponent.value = token.value; removeSelf = true; } else { matchingComponent.isIrrelevant = true; } t.isDirty = true; } result.push(t); } else if (token.isShorthand && t.isShorthand && token.prop === t.prop) { for (iiii = 0; iiii < t.components.length; iiii++) { can = (processable[t.components[iiii].prop] && processable[t.components[iiii].prop].canOverride) || sameValue; if (!can(t.components[iiii].value, token.components[iiii].value)) { result.push(t); break; } if (t.components[iiii].isImportant && token.components[iiii].isImportant && (validator.isValidFunction(t.components[iiii].value) ^ validator.isValidFunction(token.components[iiii].value))) { result.push(t); break; } } } else if (t.prop !== token.prop || !can(t.value, token.value)) { result.push(t); } else if (t.isImportant && token.isImportant && (validator.isValidFunction(t.value) ^ validator.isValidFunction(token.value))) { result.push(t); } } if (removeSelf) { i--; } } return result; }; return {compactOverrides: compactOverrides}; })(); })(require("process"));
/*! * Knockout ES5 plugin - https://github.com/SteveSanderson/knockout-es5 * Copyright (c) Steve Sanderson * MIT license */ !function(a,b){"use strict"; // Model tracking // -------------- // // This is the central feature of Knockout-ES5. We augment model objects by converting properties // into ES5 getter/setter pairs that read/write an underlying Knockout observable. This means you can // use plain JavaScript syntax to read/write the property while still getting the full benefits of // Knockout's automatic dependency detection and notification triggering. // // For comparison, here's Knockout ES3-compatible syntax: // // var firstNameLength = myModel.user().firstName().length; // Read // myModel.user().firstName('Bert'); // Write // // ... versus Knockout-ES5 syntax: // // var firstNameLength = myModel.user.firstName.length; // Read // myModel.user.firstName = 'Bert'; // Write // `ko.track(model)` converts each property on the given model object into a getter/setter pair that // wraps a Knockout observable. Optionally specify an array of property names to wrap; otherwise we // wrap all properties. If any of the properties are already observables, we replace them with // ES5 getter/setter pairs that wrap your original observable instances. In the case of readonly // ko.computed properties, we simply do not define a setter (so attempted writes will be ignored, // which is how ES5 readonly properties normally behave). // // By design, this does *not* recursively walk child object properties, because making literally // everything everywhere independently observable is usually unhelpful. When you do want to track // child object properties independently, define your own class for those child objects and put // a separate ko.track call into its constructor --- this gives you far more control. /** * @param {object} obj * @param {object|array.<string>} propertyNamesOrSettings * @param {boolean} propertyNamesOrSettings.deep Use deep track. * @param {array.<string>} propertyNamesOrSettings.fields Array of property names to wrap. * todo: @param {array.<string>} propertyNamesOrSettings.exclude Array of exclude property names to wrap. * todo: @param {function(string, *):boolean} propertyNamesOrSettings.filter Function to filter property * names to wrap. A function that takes ... params * @return {object} */ function c(a,b){if(!a||"object"!=typeof a)throw new Error("When calling ko.track, you must pass an object as the first parameter.");var c; // defaults return i(b)?(b.deep=b.deep||!1,b.fields=b.fields||Object.getOwnPropertyNames(a),b.lazy=b.lazy||!1,h(a,b.fields,b)):(c=b||Object.getOwnPropertyNames(a),h(a,c,{})),a}function d(a){return a.name?a.name:(a.toString().trim().match(A)||[])[1]}function e(a){return a&&"object"==typeof a&&"Object"===d(a.constructor)}function f(a,c,d){var e=w.isObservable(a),f=!e&&Array.isArray(a),g=e?a:f?w.observableArray(a):w.observable(a); // add check in case the object is already an observable array return d[c]=function(){return g},(f||e&&"push"in g)&&m(w,g),{configurable:!0,enumerable:!0,get:g,set:w.isWriteableObservable(g)?g:b}}function g(a,b,c){function d(a,b){return e?b?e(a):e:Array.isArray(a)?(e=w.observableArray(a),m(w,e),e):e=w.observable(a)}if(w.isObservable(a)) // no need to be lazy if we already have an observable return f(a,b,c);var e;return c[b]=function(){return d(a)},{configurable:!0,enumerable:!0,get:function(){return d(a)()},set:function(a){d(a,!0)}}}function h(a,b,c){if(b.length){var d=j(a,!0),i={};b.forEach(function(b){ // Skip properties that are already tracked if(!(b in d)&&Object.getOwnPropertyDescriptor(a,b).configurable!==!1) // Skip properties where descriptor can't be redefined {var j=a[b];i[b]=(c.lazy?g:f)(j,b,d),c.deep&&e(j)&&h(j,Object.keys(j),c)}}),Object.defineProperties(a,i)}}function i(a){return!!a&&"object"==typeof a&&a.constructor===Object} // Gets or creates the hidden internal key-value collection of observables corresponding to // properties on the model object. function j(a,b){y||(y=x());var c=y.get(a);return!c&&b&&(c={},y.set(a,c)),c} // Removes the internal references to observables mapped to the specified properties // or the entire object reference if no properties are passed in. This allows the // observables to be replaced and tracked again. function k(a,b){if(y)if(1===arguments.length)y.delete(a);else{var c=j(a,!1);c&&b.forEach(function(a){delete c[a]})}} // Computed properties // ------------------- // // The preceding code is already sufficient to upgrade ko.computed model properties to ES5 // getter/setter pairs (or in the case of readonly ko.computed properties, just a getter). // These then behave like a regular property with a getter function, except they are smarter: // your evaluator is only invoked when one of its dependencies changes. The result is cached // and used for all evaluations until the next time a dependency changes). // // However, instead of forcing developers to declare a ko.computed property explicitly, it's // nice to offer a utility function that declares a computed getter directly. // Implements `ko.defineProperty` function l(a,b,d){var e=this,f={owner:a,deferEvaluation:!0};if("function"==typeof d)f.read=d;else{if("value"in d)throw new Error('For ko.defineProperty, you must not specify a "value" for the property. You must provide a "get" function.');if("function"!=typeof d.get)throw new Error('For ko.defineProperty, the third parameter must be either an evaluator function, or an options object containing a function called "get".');f.read=d.get,f.write=d.set}return a[b]=e.computed(f),c.call(e,a,[b]),a} // Array handling // -------------- // // Arrays are special, because unlike other property types, they have standard mutator functions // (`push`/`pop`/`splice`/etc.) and it's desirable to trigger a change notification whenever one of // those mutator functions is invoked. // // Traditionally, Knockout handles this by putting special versions of `push`/`pop`/etc. on observable // arrays that mutate the underlying array and then trigger a notification. That approach doesn't // work for Knockout-ES5 because properties now return the underlying arrays, so the mutator runs // in the context of the underlying array, not any particular observable: // // // Operates on the underlying array value // myModel.someCollection.push('New value'); // // To solve this, Knockout-ES5 detects array values, and modifies them as follows: // 1. Associates a hidden subscribable with each array instance that it encounters // 2. Intercepts standard mutators (`push`/`pop`/etc.) and makes them trigger the subscribable // Then, for model properties whose values are arrays, the property's underlying observable // subscribes to the array subscribable, so it can trigger a change notification after mutation. // Given an observable that underlies a model property, watch for any array value that might // be assigned as the property value, and hook into its change events function m(a,b){var c=null;a.computed(function(){ // Unsubscribe to any earlier array instance c&&(c.dispose(),c=null); // Subscribe to the new array instance var d=b();d instanceof Array&&(c=n(a,b,d))})} // Listens for array mutations, and when they happen, cause the observable to fire notifications. // This is used to make model properties of type array fire notifications when the array changes. // Returns a subscribable that can later be disposed. function n(a,b,c){var d=o(a,c);return d.subscribe(b)} // Gets or creates a subscribable that fires after each array mutation function o(a,b){z||(z=x());var c=z.get(b);if(!c){c=new a.subscribable,z.set(b,c);var d={};p(b,c,d),q(a,b,c,d)}return c} // After each array mutation, fires a notification on the given subscribable function p(a,b,c){["pop","push","reverse","shift","sort","splice","unshift"].forEach(function(d){var e=a[d];a[d]=function(){var a=e.apply(this,arguments);return c.pause!==!0&&b.notifySubscribers(this),a}})} // Adds Knockout's additional array mutation functions to the array function q(a,b,c,d){["remove","removeAll","destroy","destroyAll","replace"].forEach(function(e){ // Make it a non-enumerable property for consistency with standard Array functions Object.defineProperty(b,e,{enumerable:!1,value:function(){var f; // These additional array mutators are built using the underlying push/pop/etc. // mutators, which are wrapped to trigger notifications. But we don't want to // trigger multiple notifications, so pause the push/pop/etc. wrappers and // delivery only one notification at the end of the process. d.pause=!0;try{ // Creates a temporary observableArray that can perform the operation. f=a.observableArray.fn[e].apply(a.observableArray(b),arguments)}finally{d.pause=!1}return c.notifySubscribers(b),f}})})} // Static utility functions // ------------------------ // // Since Knockout-ES5 sets up properties that return values, not observables, you can't // trivially subscribe to the underlying observables (e.g., `someProperty.subscribe(...)`), // or tell them that object values have mutated, etc. To handle this, we set up some // extra utility functions that can return or work with the underlying observables. // Returns the underlying observable associated with a model property (or `null` if the // model or property doesn't exist, or isn't associated with an observable). This means // you can subscribe to the property, e.g.: // // ko.getObservable(model, 'propertyName') // .subscribe(function(newValue) { ... }); function r(a,b){if(!a||"object"!=typeof a)return null;var c=j(a,!1);return c&&b in c?c[b]():null} // Returns a boolean indicating whether the property on the object has an underlying // observables. This does the check in a way not to create an observable if the // object was created with lazily created observables function s(a,b){if(!a||"object"!=typeof a)return!1;var c=j(a,!1);return!!c&&b in c} // Causes a property's associated observable to fire a change notification. Useful when // the property value is a complex object and you've modified a child property. function t(a,b){var c=r(a,b);c&&c.valueHasMutated()} // Module initialisation // --------------------- // // When this script is first evaluated, it works out what kind of module loading scenario // it is in (Node.js or a browser `<script>` tag), stashes a reference to its dependencies // (currently that's just the WeakMap shim), and then finally attaches itself to whichever // instance of Knockout.js it can find. // Extends a Knockout instance with Knockout-ES5 functionality function u(a){a.track=c,a.untrack=k,a.getObservable=r,a.valueHasMutated=t,a.defineProperty=l, // todo: test it, maybe added it to ko. directly a.es5={getAllObservablesForObject:j,notifyWhenPresentOrFutureArrayValuesMutate:m,isTracked:s}} // Determines which module loading scenario we're in, grabs dependencies, and attaches to KO function v(){if("object"==typeof exports&&"object"==typeof module){ // Node.js case - load KO and WeakMap modules synchronously w=require("knockout");var b=a.WeakMap||require("../lib/weakmap");u(w),x=function(){return new b},module.exports=w}else"function"==typeof define&&define.amd?define(["knockout"],function(b){return w=b,u(b),x=function(){return new a.WeakMap},b}):"ko"in a&&( // Non-module case - attach to the global instance, and assume a global WeakMap constructor w=a.ko,u(a.ko),x=function(){return new a.WeakMap})}var w,x,y,z,A=/^function\s*([^\s(]+)/;v()}("undefined"!=typeof window?window:"undefined"!=typeof global?global:this);
/*! * jQuery Password Strength plugin for Twitter Bootstrap * Version: 2.1.1 * * Copyright (c) 2008-2013 Tane Piper * Copyright (c) 2013 Alejandro Blanco * Dual licensed under the MIT and GPL licenses. */ (function (jQuery) { // Source: src/i18n.js var i18n = {}; (function (i18n, i18next) { 'use strict'; i18n.fallback = { "wordMinLength": "Your password is too short", "wordMaxLength": "Your password is too long", "wordInvalidChar": "Your password contains an invalid character", "wordNotEmail": "Do not use your email as your password", "wordSimilarToUsername": "Your password cannot contain your username", "wordTwoCharacterClasses": "Use different character classes", "wordRepetitions": "Too many repetitions", "wordSequences": "Your password contains sequences", "errorList": "Errors:", "veryWeak": "Very Weak", "weak": "Weak", "normal": "Normal", "medium": "Medium", "strong": "Strong", "veryStrong": "Very Strong" }; i18n.t = function (key) { var result = ''; // Try to use i18next.com if (i18next) { result = i18next.t(key); } else { // Fallback to english result = i18n.fallback[key]; } return result === key ? '' : result; }; }(i18n, window.i18next)); // Source: src/rules.js var rulesEngine = {}; try { if (!jQuery && module && module.exports) { var jQuery = require("jquery"), jsdom = require("jsdom").jsdom; jQuery = jQuery(jsdom().defaultView); } } catch (ignore) {} (function ($, rulesEngine) { "use strict"; var validation = {}; rulesEngine.forbiddenSequences = [ "0123456789", "abcdefghijklmnopqrstuvwxyz", "qwertyuiop", "asdfghjkl", "zxcvbnm", "!@#$%^&*()_+" ]; validation.wordNotEmail = function (options, word, score) { if (word.match(/^([\w\!\#$\%\&\'\*\+\-\/\=\?\^\`{\|\}\~]+\.)*[\w\!\#$\%\&\'\*\+\-\/\=\?\^\`{\|\}\~]+@((((([a-z0-9]{1}[a-z0-9\-]{0,62}[a-z0-9]{1})|[a-z])\.)+[a-z]{2,6})|(\d{1,3}\.){3}\d{1,3}(\:\d{1,5})?)$/i)) { return score; } return 0; }; validation.wordMinLength = function (options, word, score) { var wordlen = word.length, lenScore = Math.pow(wordlen, options.rules.raisePower); if (wordlen < options.common.minChar) { lenScore = (lenScore + score); } return lenScore; }; validation.wordMaxLength = function (options, word, score) { var wordlen = word.length, lenScore = Math.pow(wordlen, options.rules.raisePower); if (wordlen > options.common.maxChar) { return score; } return lenScore; }; validation.wordInvalidChar = function (options, word, score) { if (word.match(/[\s,',"]/)) { return score; } return 0; }; validation.wordLengthStaticScore = function (options, word, score) { return word.length < options.common.minChar ? 0 : score; }; validation.wordSimilarToUsername = function (options, word, score) { var username = $(options.common.usernameField).val(); if (username && word.toLowerCase().match(username.replace(/[\-\[\]\/\{\}\(\)\*\+\=\?\:\.\\\^\$\|\!\,]/g, "\\$&").toLowerCase())) { return score; } return 0; }; validation.wordTwoCharacterClasses = function (options, word, score) { if (word.match(/([a-z].*[A-Z])|([A-Z].*[a-z])/) || (word.match(/([a-zA-Z])/) && word.match(/([0-9])/)) || (word.match(/(.[!,@,#,$,%,\^,&,*,?,_,~])/) && word.match(/[a-zA-Z0-9_]/))) { return score; } return 0; }; validation.wordRepetitions = function (options, word, score) { if (word.match(/(.)\1\1/)) { return score; } return 0; }; validation.wordSequences = function (options, word, score) { var found = false, j; if (word.length > 2) { $.each(rulesEngine.forbiddenSequences, function (idx, seq) { if (found) { return; } var sequences = [seq, seq.split('').reverse().join('')]; $.each(sequences, function (idx, sequence) { for (j = 0; j < (word.length - 2); j += 1) { // iterate the word trough a sliding window of size 3: if (sequence.indexOf(word.toLowerCase().substring(j, j + 3)) > -1) { found = true; } } }); }); if (found) { return score; } } return 0; }; validation.wordLowercase = function (options, word, score) { return word.match(/[a-z]/) && score; }; validation.wordUppercase = function (options, word, score) { return word.match(/[A-Z]/) && score; }; validation.wordOneNumber = function (options, word, score) { return word.match(/\d+/) && score; }; validation.wordThreeNumbers = function (options, word, score) { return word.match(/(.*[0-9].*[0-9].*[0-9])/) && score; }; validation.wordOneSpecialChar = function (options, word, score) { return word.match(/[!,@,#,$,%,\^,&,*,?,_,~]/) && score; }; validation.wordTwoSpecialChar = function (options, word, score) { return word.match(/(.*[!,@,#,$,%,\^,&,*,?,_,~].*[!,@,#,$,%,\^,&,*,?,_,~])/) && score; }; validation.wordUpperLowerCombo = function (options, word, score) { return word.match(/([a-z].*[A-Z])|([A-Z].*[a-z])/) && score; }; validation.wordLetterNumberCombo = function (options, word, score) { return word.match(/([a-zA-Z])/) && word.match(/([0-9])/) && score; }; validation.wordLetterNumberCharCombo = function (options, word, score) { return word.match(/([a-zA-Z0-9].*[!,@,#,$,%,\^,&,*,?,_,~])|([!,@,#,$,%,\^,&,*,?,_,~].*[a-zA-Z0-9])/) && score; }; rulesEngine.validation = validation; rulesEngine.executeRules = function (options, word) { var totalScore = 0; $.each(options.rules.activated, function (rule, active) { if (active) { var score = options.rules.scores[rule], funct = rulesEngine.validation[rule], result, errorMessage; if (!$.isFunction(funct)) { funct = options.rules.extra[rule]; } if ($.isFunction(funct)) { result = funct(options, word, score); if (result) { totalScore += result; } if (result < 0 || (!$.isNumeric(result) && !result)) { errorMessage = options.ui.spanError(options, rule); if (errorMessage.length > 0) { options.instances.errors.push(errorMessage); } } } } }); if ($.isFunction(options.common.onScore)) { totalScore = options.common.onScore(options, word, totalScore); } return totalScore; }; }(jQuery, rulesEngine)); try { if (module && module.exports) { module.exports = rulesEngine; } } catch (ignore) {} // Source: src/options.js var defaultOptions = {}; defaultOptions.common = {}; defaultOptions.common.minChar = 6; defaultOptions.common.maxChar = 20; defaultOptions.common.usernameField = "#username"; defaultOptions.common.userInputs = [ // Selectors for input fields with user input ]; defaultOptions.common.onLoad = undefined; defaultOptions.common.onKeyUp = undefined; defaultOptions.common.onScore = undefined; defaultOptions.common.zxcvbn = false; defaultOptions.common.zxcvbnTerms = [ // List of disrecommended words ]; defaultOptions.common.events = ["keyup", "change", "paste"]; defaultOptions.common.debug = false; defaultOptions.rules = {}; defaultOptions.rules.extra = {}; defaultOptions.rules.scores = { wordNotEmail: -100, wordMinLength: -50, wordMaxLength: -50, wordInvalidChar: -100, wordSimilarToUsername: -100, wordSequences: -20, wordTwoCharacterClasses: 2, wordRepetitions: -25, wordLowercase: 1, wordUppercase: 3, wordOneNumber: 3, wordThreeNumbers: 5, wordOneSpecialChar: 3, wordTwoSpecialChar: 5, wordUpperLowerCombo: 2, wordLetterNumberCombo: 2, wordLetterNumberCharCombo: 2 }; defaultOptions.rules.activated = { wordNotEmail: true, wordMinLength: true, wordMaxLength: false, wordInvalidChar: false, wordSimilarToUsername: true, wordSequences: true, wordTwoCharacterClasses: false, wordRepetitions: false, wordLowercase: true, wordUppercase: true, wordOneNumber: true, wordThreeNumbers: true, wordOneSpecialChar: true, wordTwoSpecialChar: true, wordUpperLowerCombo: true, wordLetterNumberCombo: true, wordLetterNumberCharCombo: true }; defaultOptions.rules.raisePower = 1.4; defaultOptions.ui = {}; defaultOptions.ui.bootstrap2 = false; defaultOptions.ui.bootstrap4 = false; defaultOptions.ui.colorClasses = [ "danger", "danger", "danger", "warning", "warning", "success" ]; defaultOptions.ui.showProgressBar = true; defaultOptions.ui.progressBarEmptyPercentage = 1; defaultOptions.ui.progressBarMinPercentage = 1; defaultOptions.ui.progressExtraCssClasses = ''; defaultOptions.ui.progressBarExtraCssClasses = ''; defaultOptions.ui.showPopover = false; defaultOptions.ui.popoverPlacement = "bottom"; defaultOptions.ui.showStatus = false; defaultOptions.ui.spanError = function (options, key) { "use strict"; var text = options.i18n.t(key); if (!text) { return ''; } return '<span style="color: #d52929">' + text + '</span>'; }; defaultOptions.ui.popoverError = function (options) { "use strict"; var errors = options.instances.errors, errorsTitle = options.i18n.t("errorList"), message = "<div>" + errorsTitle + "<ul class='error-list' style='margin-bottom: 0;'>"; jQuery.each(errors, function (idx, err) { message += "<li>" + err + "</li>"; }); message += "</ul></div>"; return message; }; defaultOptions.ui.showVerdicts = true; defaultOptions.ui.showVerdictsInsideProgressBar = false; defaultOptions.ui.useVerdictCssClass = false; defaultOptions.ui.showErrors = false; defaultOptions.ui.showScore = false; defaultOptions.ui.container = undefined; defaultOptions.ui.viewports = { progress: undefined, verdict: undefined, errors: undefined, score: undefined }; defaultOptions.ui.scores = [0, 14, 26, 38, 50]; defaultOptions.i18n = {}; defaultOptions.i18n.t = i18n.t; // Source: src/ui.js var ui = {}; (function ($, ui) { "use strict"; var statusClasses = ["error", "warning", "success"], verdictKeys = [ "veryWeak", "weak", "normal", "medium", "strong", "veryStrong" ]; ui.getContainer = function (options, $el) { var $container; $container = $(options.ui.container); if (!($container && $container.length === 1)) { $container = $el.parent(); } return $container; }; ui.findElement = function ($container, viewport, cssSelector) { if (viewport) { return $container.find(viewport).find(cssSelector); } return $container.find(cssSelector); }; ui.getUIElements = function (options, $el) { var $container, result; if (options.instances.viewports) { return options.instances.viewports; } $container = ui.getContainer(options, $el); result = {}; result.$progressbar = ui.findElement($container, options.ui.viewports.progress, "div.progress"); if (options.ui.showVerdictsInsideProgressBar) { result.$verdict = result.$progressbar.find("span.password-verdict"); } if (!options.ui.showPopover) { if (!options.ui.showVerdictsInsideProgressBar) { result.$verdict = ui.findElement($container, options.ui.viewports.verdict, "span.password-verdict"); } result.$errors = ui.findElement($container, options.ui.viewports.errors, "ul.error-list"); } result.$score = ui.findElement($container, options.ui.viewports.score, "span.password-score"); options.instances.viewports = result; return result; }; ui.initProgressBar = function (options, $el) { var $container = ui.getContainer(options, $el), progressbar = "<div class='progress "; if (options.ui.bootstrap2) { // Boostrap 2 progressbar += options.ui.progressBarExtraCssClasses + "'><div class='"; } else { // Bootstrap 3 & 4 progressbar += options.ui.progressExtraCssClasses + "'><div class='" + options.ui.progressBarExtraCssClasses + " progress-"; } progressbar += "bar'>"; if (options.ui.showVerdictsInsideProgressBar) { progressbar += "<span class='password-verdict'></span>"; } progressbar += "</div></div>"; if (options.ui.viewports.progress) { $container.find(options.ui.viewports.progress).append(progressbar); } else { $(progressbar).insertAfter($el); } }; ui.initHelper = function (options, $el, html, viewport) { var $container = ui.getContainer(options, $el); if (viewport) { $container.find(viewport).append(html); } else { $(html).insertAfter($el); } }; ui.initVerdict = function (options, $el) { ui.initHelper(options, $el, "<span class='password-verdict'></span>", options.ui.viewports.verdict); }; ui.initErrorList = function (options, $el) { ui.initHelper(options, $el, "<ul class='error-list'></ul>", options.ui.viewports.errors); }; ui.initScore = function (options, $el) { ui.initHelper(options, $el, "<span class='password-score'></span>", options.ui.viewports.score); }; ui.initPopover = function (options, $el) { $el.popover("destroy"); $el.popover({ html: true, placement: options.ui.popoverPlacement, trigger: "manual", content: " " }); }; ui.initUI = function (options, $el) { if (options.ui.showPopover) { ui.initPopover(options, $el); } else { if (options.ui.showErrors) { ui.initErrorList(options, $el); } if (options.ui.showVerdicts && !options.ui.showVerdictsInsideProgressBar) { ui.initVerdict(options, $el); } } if (options.ui.showProgressBar) { ui.initProgressBar(options, $el); } if (options.ui.showScore) { ui.initScore(options, $el); } }; ui.updateProgressBar = function (options, $el, cssClass, percentage) { var $progressbar = ui.getUIElements(options, $el).$progressbar, $bar = $progressbar.find(".progress-bar"), cssPrefix = "progress-"; if (options.ui.bootstrap2) { $bar = $progressbar.find(".bar"); cssPrefix = ""; } $.each(options.ui.colorClasses, function (idx, value) { if (options.ui.bootstrap4) { $bar.removeClass("bg-" + value); } else { $bar.removeClass(cssPrefix + "bar-" + value); } }); if (options.ui.bootstrap4) { $bar.addClass("bg-" + options.ui.colorClasses[cssClass]); } else { $bar.addClass(cssPrefix + "bar-" + options.ui.colorClasses[cssClass]); } $bar.css("width", percentage + '%'); }; ui.updateVerdict = function (options, $el, cssClass, text) { var $verdict = ui.getUIElements(options, $el).$verdict; $verdict.removeClass(options.ui.colorClasses.join(' ')); if (cssClass > -1) { $verdict.addClass(options.ui.colorClasses[cssClass]); } $verdict.html(text); }; ui.updateErrors = function (options, $el, remove) { var $errors = ui.getUIElements(options, $el).$errors, html = ""; if (!remove) { $.each(options.instances.errors, function (idx, err) { html += "<li>" + err + "</li>"; }); } $errors.html(html); }; ui.updateScore = function (options, $el, score, remove) { var $score = ui.getUIElements(options, $el).$score, html = ""; if (!remove) { html = score.toFixed(2); } $score.html(html); }; ui.updatePopover = function (options, $el, verdictText, remove) { var popover = $el.data("bs.popover"), html = "", hide = true; if (options.ui.showVerdicts && !options.ui.showVerdictsInsideProgressBar && verdictText.length > 0) { html = "<h5><span class='password-verdict'>" + verdictText + "</span></h5>"; hide = false; } if (options.ui.showErrors) { if (options.instances.errors.length > 0) { hide = false; } html += options.ui.popoverError(options); } if (hide || remove) { $el.popover("hide"); return; } if (options.ui.bootstrap2) { popover = $el.data("popover"); } if (popover.$arrow && popover.$arrow.parents("body").length > 0) { $el.find("+ .popover .popover-content").html(html); } else { // It's hidden popover.options.content = html; $el.popover("show"); } }; ui.updateFieldStatus = function (options, $el, cssClass, remove) { var targetClass = options.ui.bootstrap2 ? ".control-group" : ".form-group", $container = $el.parents(targetClass).first(); $.each(statusClasses, function (idx, css) { if (!options.ui.bootstrap2) { css = "has-" + css; } $container.removeClass(css); }); if (remove) { return; } cssClass = statusClasses[Math.floor(cssClass / 2)]; if (!options.ui.bootstrap2) { cssClass = "has-" + cssClass; } $container.addClass(cssClass); }; ui.percentage = function (options, score, maximun) { var result = Math.floor(100 * score / maximun), min = options.ui.progressBarMinPercentage; result = result <= min ? min : result; result = result > 100 ? 100 : result; return result; }; ui.getVerdictAndCssClass = function (options, score) { var level, verdict; if (score === undefined) { return ['', 0]; } if (score <= options.ui.scores[0]) { level = 0; } else if (score < options.ui.scores[1]) { level = 1; } else if (score < options.ui.scores[2]) { level = 2; } else if (score < options.ui.scores[3]) { level = 3; } else if (score < options.ui.scores[4]) { level = 4; } else { level = 5; } verdict = verdictKeys[level]; return [options.i18n.t(verdict), level]; }; ui.updateUI = function (options, $el, score) { var cssClass, barPercentage, verdictText, verdictCssClass; cssClass = ui.getVerdictAndCssClass(options, score); verdictText = score === 0 ? '' : cssClass[0]; cssClass = cssClass[1]; verdictCssClass = options.ui.useVerdictCssClass ? cssClass : -1; if (options.ui.showProgressBar) { if (score === undefined) { barPercentage = options.ui.progressBarEmptyPercentage; } else { barPercentage = ui.percentage(options, score, options.ui.scores[4]); } ui.updateProgressBar(options, $el, cssClass, barPercentage); if (options.ui.showVerdictsInsideProgressBar) { ui.updateVerdict(options, $el, verdictCssClass, verdictText); } } if (options.ui.showStatus) { ui.updateFieldStatus(options, $el, cssClass, score === undefined); } if (options.ui.showPopover) { ui.updatePopover(options, $el, verdictText, score === undefined); } else { if (options.ui.showVerdicts && !options.ui.showVerdictsInsideProgressBar) { ui.updateVerdict(options, $el, verdictCssClass, verdictText); } if (options.ui.showErrors) { ui.updateErrors(options, $el, score === undefined); } } if (options.ui.showScore) { ui.updateScore(options, $el, score, score === undefined); } }; }(jQuery, ui)); // Source: src/methods.js var methods = {}; (function ($, methods) { "use strict"; var onKeyUp, onPaste, applyToAll; onKeyUp = function (event) { var $el = $(event.target), options = $el.data("pwstrength-bootstrap"), word = $el.val(), userInputs, verdictText, verdictLevel, score; if (options === undefined) { return; } options.instances.errors = []; if (word.length === 0) { score = undefined; } else { if (options.common.zxcvbn) { userInputs = []; $.each(options.common.userInputs.concat([options.common.usernameField]), function (idx, selector) { var value = $(selector).val(); if (value) { userInputs.push(value); } }); userInputs = userInputs.concat(options.common.zxcvbnTerms); score = zxcvbn(word, userInputs).guesses; score = Math.log(score) * Math.LOG2E; } else { score = rulesEngine.executeRules(options, word); } } ui.updateUI(options, $el, score); verdictText = ui.getVerdictAndCssClass(options, score); verdictLevel = verdictText[1]; verdictText = verdictText[0]; if (options.common.debug) { console.log(score + ' - ' + verdictText); } if ($.isFunction(options.common.onKeyUp)) { options.common.onKeyUp(event, { score: score, verdictText: verdictText, verdictLevel: verdictLevel }); } }; onPaste = function (event) { // This handler is necessary because the paste event fires before the // content is actually in the input, so we cannot read its value right // away. Therefore, the timeouts. var $el = $(event.target), word = $el.val(), tries = 0, callback; callback = function () { var newWord = $el.val(); if (newWord !== word) { onKeyUp(event); } else if (tries < 3) { tries += 1; setTimeout(callback, 100); } }; setTimeout(callback, 100); }; methods.init = function (settings) { this.each(function (idx, el) { // Make it deep extend (first param) so it extends also the // rules and other inside objects var clonedDefaults = $.extend(true, {}, defaultOptions), localOptions = $.extend(true, clonedDefaults, settings), $el = $(el); localOptions.instances = {}; $el.data("pwstrength-bootstrap", localOptions); $.each(localOptions.common.events, function (idx, eventName) { var handler = eventName === "paste" ? onPaste : onKeyUp; $el.on(eventName, handler); }); ui.initUI(localOptions, $el); $el.trigger("keyup"); if ($.isFunction(localOptions.common.onLoad)) { localOptions.common.onLoad(); } }); return this; }; methods.destroy = function () { this.each(function (idx, el) { var $el = $(el), options = $el.data("pwstrength-bootstrap"), elements = ui.getUIElements(options, $el); elements.$progressbar.remove(); elements.$verdict.remove(); elements.$errors.remove(); $el.removeData("pwstrength-bootstrap"); }); }; methods.forceUpdate = function () { this.each(function (idx, el) { var event = { target: el }; onKeyUp(event); }); }; methods.addRule = function (name, method, score, active) { this.each(function (idx, el) { var options = $(el).data("pwstrength-bootstrap"); options.rules.activated[name] = active; options.rules.scores[name] = score; options.rules.extra[name] = method; }); }; applyToAll = function (rule, prop, value) { this.each(function (idx, el) { $(el).data("pwstrength-bootstrap").rules[prop][rule] = value; }); }; methods.changeScore = function (rule, score) { applyToAll.call(this, rule, "scores", score); }; methods.ruleActive = function (rule, active) { applyToAll.call(this, rule, "activated", active); }; methods.ruleIsMet = function (rule) { if ($.isFunction(rulesEngine.validation[rule])) { if (rule === "wordLength") { rule = "wordLengthStaticScore"; } var rulesMetCnt = 0; this.each(function (idx, el) { var options = $(el).data("pwstrength-bootstrap"); rulesMetCnt += rulesEngine.validation[rule](options, $(el).val(), 1); }); return (rulesMetCnt === this.length); } $.error("Rule " + rule + " does not exist on jQuery.pwstrength-bootstrap.validation"); }; $.fn.pwstrength = function (method) { var result; if (methods[method]) { result = methods[method].apply(this, Array.prototype.slice.call(arguments, 1)); } else if (typeof method === "object" || !method) { result = methods.init.apply(this, arguments); } else { $.error("Method " + method + " does not exist on jQuery.pwstrength-bootstrap"); } return result; }; }(jQuery, methods)); }(jQuery));
// Copyright (c) 2016, Frappe Technologies and contributors // For license information, please see license.txt frappe.ui.form.on('Address Template', { refresh: function(frm) { if(frm.is_new() && !frm.doc.template) { // set default template via js so that it is translated frappe.call({ method: 'frappe.contacts.doctype.address_template.address_template.get_default_address_template', callback: function(r) { frm.set_value('template', r.message); } }); } } });
(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('react')) : typeof define === 'function' && define.amd ? define(['exports', 'react'], factory) : (factory((global.styled = global.styled || {}),global.React)); }(this, (function (exports,React) { 'use strict'; var React__default = 'default' in React ? React['default'] : React; // var chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'.split(''); /* Some high number, usually 9-digit base-10. Map it to base-😎 */ var generateAlphabeticName = function generateAlphabeticName(code) { var lastDigit = chars[code % chars.length]; return code > chars.length ? '' + generateAlphabeticName(Math.floor(code / chars.length)) + lastDigit : lastDigit; }; // var interleave = (function (strings, interpolations) { return interpolations.reduce(function (array, interp, i) { return array.concat(interp, strings[i + 1]); }, [strings[0]]); }); /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @typechecks */ var _uppercasePattern = /([A-Z])/g; /** * Hyphenates a camelcased string, for example: * * > hyphenate('backgroundColor') * < "background-color" * * For CSS style names, use `hyphenateStyleName` instead which works properly * with all vendor prefixes, including `ms`. * * @param {string} string * @return {string} */ function hyphenate$1(string) { return string.replace(_uppercasePattern, '-$1').toLowerCase(); } var hyphenate_1 = hyphenate$1; var hyphenate = hyphenate_1; var msPattern = /^ms-/; /** * Hyphenates a camelcased CSS property name, for example: * * > hyphenateStyleName('backgroundColor') * < "background-color" * > hyphenateStyleName('MozTransition') * < "-moz-transition" * > hyphenateStyleName('msTransition') * < "-ms-transition" * * As Modernizr suggests (http://modernizr.com/docs/#prefixed), an `ms` prefix * is converted to `-ms-`. * * @param {string} string * @return {string} */ function hyphenateStyleName(string) { return hyphenate(string).replace(msPattern, '-ms-'); } var hyphenateStyleName_1 = hyphenateStyleName; /** * Creates a unary function that invokes `func` with its argument transformed. * * @private * @param {Function} func The function to wrap. * @param {Function} transform The argument transform. * @returns {Function} Returns the new function. */ function overArg$1(func, transform) { return function (arg) { return func(transform(arg)); }; } var _overArg = overArg$1; var overArg = _overArg; /** Built-in value references. */ var getPrototype$1 = overArg(Object.getPrototypeOf, Object); var _getPrototype = getPrototype$1; var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; var asyncGenerator = function () { function AwaitValue(value) { this.value = value; } function AsyncGenerator(gen) { var front, back; function send(key, arg) { return new Promise(function (resolve, reject) { var request = { key: key, arg: arg, resolve: resolve, reject: reject, next: null }; if (back) { back = back.next = request; } else { front = back = request; resume(key, arg); } }); } function resume(key, arg) { try { var result = gen[key](arg); var value = result.value; if (value instanceof AwaitValue) { Promise.resolve(value.value).then(function (arg) { resume("next", arg); }, function (arg) { resume("throw", arg); }); } else { settle(result.done ? "return" : "normal", result.value); } } catch (err) { settle("throw", err); } } function settle(type, value) { switch (type) { case "return": front.resolve({ value: value, done: true }); break; case "throw": front.reject(value); break; default: front.resolve({ value: value, done: false }); break; } front = front.next; if (front) { resume(front.key, front.arg); } else { back = null; } } this._invoke = send; if (typeof gen.return !== "function") { this.return = undefined; } } if (typeof Symbol === "function" && Symbol.asyncIterator) { AsyncGenerator.prototype[Symbol.asyncIterator] = function () { return this; }; } AsyncGenerator.prototype.next = function (arg) { return this._invoke("next", arg); }; AsyncGenerator.prototype.throw = function (arg) { return this._invoke("throw", arg); }; AsyncGenerator.prototype.return = function (arg) { return this._invoke("return", arg); }; return { wrap: function (fn) { return function () { return new AsyncGenerator(fn.apply(this, arguments)); }; }, await: function (value) { return new AwaitValue(value); } }; }(); var classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }; var createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var defineProperty = function (obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }; var get$1 = function get$1(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get$1(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } }; var inherits = function (subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }; var possibleConstructorReturn = function (self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }; var set$1 = function set$1(object, property, value, receiver) { var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent !== null) { set$1(parent, property, value, receiver); } } else if ("value" in desc && desc.writable) { desc.value = value; } else { var setter = desc.set; if (setter !== undefined) { setter.call(receiver, value); } } return value; }; var toConsumableArray = function (arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) arr2[i] = arr[i]; return arr2; } else { return Array.from(arr); } }; /** * Checks if `value` is object-like. A value is object-like if it's not `null` * and has a `typeof` result of "object". * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is object-like, else `false`. * @example * * _.isObjectLike({}); * // => true * * _.isObjectLike([1, 2, 3]); * // => true * * _.isObjectLike(_.noop); * // => false * * _.isObjectLike(null); * // => false */ function isObjectLike$1(value) { return value != null && (typeof value === 'undefined' ? 'undefined' : _typeof(value)) == 'object'; } var isObjectLike_1 = isObjectLike$1; var getPrototype = _getPrototype; var isObjectLike = isObjectLike_1; /** `Object#toString` result references. */ var objectTag = '[object Object]'; /** Used for built-in method references. */ var funcProto = Function.prototype; var objectProto = Object.prototype; /** Used to resolve the decompiled source of functions. */ var funcToString = funcProto.toString; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** Used to infer the `Object` constructor. */ var objectCtorString = funcToString.call(Object); /** * Used to resolve the * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) * of values. */ var objectToString = objectProto.toString; /** * Checks if `value` is a plain object, that is, an object created by the * `Object` constructor or one with a `[[Prototype]]` of `null`. * * @static * @memberOf _ * @since 0.8.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a plain object, else `false`. * @example * * function Foo() { * this.a = 1; * } * * _.isPlainObject(new Foo); * // => false * * _.isPlainObject([1, 2, 3]); * // => false * * _.isPlainObject({ 'x': 0, 'y': 0 }); * // => true * * _.isPlainObject(Object.create(null)); * // => true */ function isPlainObject(value) { if (!isObjectLike(value) || objectToString.call(value) != objectTag) { return false; } var proto = getPrototype(value); if (proto === null) { return true; } var Ctor = hasOwnProperty.call(proto, 'constructor') && proto.constructor; return typeof Ctor == 'function' && Ctor instanceof Ctor && funcToString.call(Ctor) == objectCtorString; } var isPlainObject_1 = isPlainObject; // var objToCss = function objToCss(obj) { return Object.keys(obj).map(function (k) { return hyphenateStyleName_1(k) + ': ' + obj[k] + ';'; }).join(' '); }; var flatten = function flatten(chunks, executionContext) { return chunks.reduce(function (array, chunk) { /* Remove falsey values */ if (chunk === undefined || chunk === null || chunk === false || chunk === '') return array; /* Flatten arrays */ if (Array.isArray(chunk)) return array.concat.apply(array, toConsumableArray(flatten(chunk, executionContext))); /* Either execute or defer the function */ if (typeof chunk === 'function') { return executionContext ? array.concat.apply(array, toConsumableArray(flatten([chunk(executionContext)], executionContext))) : array.concat(chunk); } /* Handle objects */ return array.concat(isPlainObject_1(chunk) ? objToCss(chunk) : chunk.toString()); }, []); }; // var css = (function (strings) { for (var _len = arguments.length, interpolations = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { interpolations[_key - 1] = arguments[_key]; } return flatten(interleave(strings, interpolations)); }); var printed = {}; function warnOnce(message) { if (printed[message]) return; printed[message] = true; if (typeof console !== 'undefined' && console.warn) console.warn(message); } var process$1 = { argv: [], env: {} }; var index$2 = function index$2(flag, argv) { argv = argv || process$1.argv; var terminatorPos = argv.indexOf('--'); var prefix = /^--/.test(flag) ? '' : '--'; var pos = argv.indexOf(prefix + flag); return pos !== -1 && (terminatorPos !== -1 ? pos < terminatorPos : true); }; var hasFlag = index$2; var support = function support(level) { if (level === 0) { return false; } return { level: level, hasBasic: true, has256: level >= 2, has16m: level >= 3 }; }; var supportLevel = function () { if (hasFlag('no-color') || hasFlag('no-colors') || hasFlag('color=false')) { return 0; } if (hasFlag('color=16m') || hasFlag('color=full') || hasFlag('color=truecolor')) { return 3; } if (hasFlag('color=256')) { return 2; } if (hasFlag('color') || hasFlag('colors') || hasFlag('color=true') || hasFlag('color=always')) { return 1; } if (process$1.stdout && !process$1.stdout.isTTY) { return 0; } if (process$1.platform === 'win32') { return 1; } if ('COLORTERM' in process$1.env) { return 1; } if (process$1.env.TERM === 'dumb') { return 0; } if (/^xterm-256(?:color)?/.test(process$1.env.TERM)) { return 2; } if (/^screen|^xterm|^vt100|color|ansi|cygwin|linux/i.test(process$1.env.TERM)) { return 1; } return 0; }(); if (supportLevel === 0 && 'FORCE_COLOR' in process$1.env) { supportLevel = 1; } var index$1 = process$1 && support(supportLevel); var SINGLE_QUOTE = '\''.charCodeAt(0); var DOUBLE_QUOTE = '"'.charCodeAt(0); var BACKSLASH = '\\'.charCodeAt(0); var SLASH = '/'.charCodeAt(0); var NEWLINE = '\n'.charCodeAt(0); var SPACE = ' '.charCodeAt(0); var FEED = '\f'.charCodeAt(0); var TAB = '\t'.charCodeAt(0); var CR = '\r'.charCodeAt(0); var OPEN_SQUARE = '['.charCodeAt(0); var CLOSE_SQUARE = ']'.charCodeAt(0); var OPEN_PARENTHESES = '('.charCodeAt(0); var CLOSE_PARENTHESES = ')'.charCodeAt(0); var OPEN_CURLY = '{'.charCodeAt(0); var CLOSE_CURLY = '}'.charCodeAt(0); var SEMICOLON = ';'.charCodeAt(0); var ASTERISK = '*'.charCodeAt(0); var COLON = ':'.charCodeAt(0); var AT = '@'.charCodeAt(0); var RE_AT_END = /[ \n\t\r\f\{\(\)'"\\;/\[\]#]/g; var RE_WORD_END = /[ \n\t\r\f\(\)\{\}:;@!'"\\\]\[#]|\/(?=\*)/g; var RE_BAD_BRACKET = /.[\\\/\("'\n]/; function tokenize$1(input) { var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; var tokens = []; var css = input.css.valueOf(); var ignore = options.ignoreErrors; var code = void 0, next = void 0, quote = void 0, lines = void 0, last = void 0, content = void 0, escape = void 0, nextLine = void 0, nextOffset = void 0, escaped = void 0, escapePos = void 0, prev = void 0, n = void 0; var length = css.length; var offset = -1; var line = 1; var pos = 0; function unclosed(what) { throw input.error('Unclosed ' + what, line, pos - offset); } while (pos < length) { code = css.charCodeAt(pos); if (code === NEWLINE || code === FEED || code === CR && css.charCodeAt(pos + 1) !== NEWLINE) { offset = pos; line += 1; } switch (code) { case NEWLINE: case SPACE: case TAB: case CR: case FEED: next = pos; do { next += 1; code = css.charCodeAt(next); if (code === NEWLINE) { offset = next; line += 1; } } while (code === SPACE || code === NEWLINE || code === TAB || code === CR || code === FEED); tokens.push(['space', css.slice(pos, next)]); pos = next - 1; break; case OPEN_SQUARE: tokens.push(['[', '[', line, pos - offset]); break; case CLOSE_SQUARE: tokens.push([']', ']', line, pos - offset]); break; case OPEN_CURLY: tokens.push(['{', '{', line, pos - offset]); break; case CLOSE_CURLY: tokens.push(['}', '}', line, pos - offset]); break; case COLON: tokens.push([':', ':', line, pos - offset]); break; case SEMICOLON: tokens.push([';', ';', line, pos - offset]); break; case OPEN_PARENTHESES: prev = tokens.length ? tokens[tokens.length - 1][1] : ''; n = css.charCodeAt(pos + 1); if (prev === 'url' && n !== SINGLE_QUOTE && n !== DOUBLE_QUOTE && n !== SPACE && n !== NEWLINE && n !== TAB && n !== FEED && n !== CR) { next = pos; do { escaped = false; next = css.indexOf(')', next + 1); if (next === -1) { if (ignore) { next = pos; break; } else { unclosed('bracket'); } } escapePos = next; while (css.charCodeAt(escapePos - 1) === BACKSLASH) { escapePos -= 1; escaped = !escaped; } } while (escaped); tokens.push(['brackets', css.slice(pos, next + 1), line, pos - offset, line, next - offset]); pos = next; } else { next = css.indexOf(')', pos + 1); content = css.slice(pos, next + 1); if (next === -1 || RE_BAD_BRACKET.test(content)) { tokens.push(['(', '(', line, pos - offset]); } else { tokens.push(['brackets', content, line, pos - offset, line, next - offset]); pos = next; } } break; case CLOSE_PARENTHESES: tokens.push([')', ')', line, pos - offset]); break; case SINGLE_QUOTE: case DOUBLE_QUOTE: quote = code === SINGLE_QUOTE ? '\'' : '"'; next = pos; do { escaped = false; next = css.indexOf(quote, next + 1); if (next === -1) { if (ignore) { next = pos + 1; break; } else { unclosed('quote'); } } escapePos = next; while (css.charCodeAt(escapePos - 1) === BACKSLASH) { escapePos -= 1; escaped = !escaped; } } while (escaped); content = css.slice(pos, next + 1); lines = content.split('\n'); last = lines.length - 1; if (last > 0) { nextLine = line + last; nextOffset = next - lines[last].length; } else { nextLine = line; nextOffset = offset; } tokens.push(['string', css.slice(pos, next + 1), line, pos - offset, nextLine, next - nextOffset]); offset = nextOffset; line = nextLine; pos = next; break; case AT: RE_AT_END.lastIndex = pos + 1; RE_AT_END.test(css); if (RE_AT_END.lastIndex === 0) { next = css.length - 1; } else { next = RE_AT_END.lastIndex - 2; } tokens.push(['at-word', css.slice(pos, next + 1), line, pos - offset, line, next - offset]); pos = next; break; case BACKSLASH: next = pos; escape = true; while (css.charCodeAt(next + 1) === BACKSLASH) { next += 1; escape = !escape; } code = css.charCodeAt(next + 1); if (escape && code !== SLASH && code !== SPACE && code !== NEWLINE && code !== TAB && code !== CR && code !== FEED) { next += 1; } tokens.push(['word', css.slice(pos, next + 1), line, pos - offset, line, next - offset]); pos = next; break; default: if (code === SLASH && css.charCodeAt(pos + 1) === ASTERISK) { next = css.indexOf('*/', pos + 2) + 1; if (next === 0) { if (ignore) { next = css.length; } else { unclosed('comment'); } } content = css.slice(pos, next + 1); lines = content.split('\n'); last = lines.length - 1; if (last > 0) { nextLine = line + last; nextOffset = next - lines[last].length; } else { nextLine = line; nextOffset = offset; } tokens.push(['comment', content, line, pos - offset, nextLine, next - nextOffset]); offset = nextOffset; line = nextLine; pos = next; } else { RE_WORD_END.lastIndex = pos + 1; RE_WORD_END.test(css); if (RE_WORD_END.lastIndex === 0) { next = css.length - 1; } else { next = RE_WORD_END.lastIndex - 2; } tokens.push(['word', css.slice(pos, next + 1), line, pos - offset, line, next - offset]); pos = next; } break; } pos++; } return tokens; } var HIGHLIGHT_THEME = { 'brackets': [36, 39], // cyan 'string': [31, 39], // red 'at-word': [31, 39], // red 'comment': [90, 39], // gray '{': [32, 39], // green '}': [32, 39], // green ':': [1, 22], // bold ';': [1, 22], // bold '(': [1, 22], // bold ')': [1, 22] // bold }; function code(color) { return '\x1B[' + color + 'm'; } function terminalHighlight(css) { var tokens = tokenize$1(new Input(css), { ignoreErrors: true }); var result = []; tokens.forEach(function (token) { var color = HIGHLIGHT_THEME[token[0]]; if (color) { result.push(token[1].split(/\r?\n/).map(function (i) { return code(color[0]) + i + code(color[1]); }).join('\n')); } else { result.push(token[1]); } }); return result.join(''); } /** * The CSS parser throws this error for broken CSS. * * Custom parsers can throw this error for broken custom syntax using * the {@link Node#error} method. * * PostCSS will use the input source map to detect the original error location. * If you wrote a Sass file, compiled it to CSS and then parsed it with PostCSS, * PostCSS will show the original position in the Sass file. * * If you need the position in the PostCSS input * (e.g., to debug the previous compiler), use `error.input.file`. * * @example * // Catching and checking syntax error * try { * postcss.parse('a{') * } catch (error) { * if ( error.name === 'CssSyntaxError' ) { * error //=> CssSyntaxError * } * } * * @example * // Raising error from plugin * throw node.error('Unknown variable', { plugin: 'postcss-vars' }); */ var CssSyntaxError = function () { /** * @param {string} message - error message * @param {number} [line] - source line of the error * @param {number} [column] - source column of the error * @param {string} [source] - source code of the broken file * @param {string} [file] - absolute path to the broken file * @param {string} [plugin] - PostCSS plugin name, if error came from plugin */ function CssSyntaxError(message, line, column, source, file, plugin) { classCallCheck(this, CssSyntaxError); /** * @member {string} - Always equal to `'CssSyntaxError'`. You should * always check error type * by `error.name === 'CssSyntaxError'` instead of * `error instanceof CssSyntaxError`, because * npm could have several PostCSS versions. * * @example * if ( error.name === 'CssSyntaxError' ) { * error //=> CssSyntaxError * } */ this.name = 'CssSyntaxError'; /** * @member {string} - Error message. * * @example * error.message //=> 'Unclosed block' */ this.reason = message; if (file) { /** * @member {string} - Absolute path to the broken file. * * @example * error.file //=> 'a.sass' * error.input.file //=> 'a.css' */ this.file = file; } if (source) { /** * @member {string} - Source code of the broken file. * * @example * error.source //=> 'a { b {} }' * error.input.column //=> 'a b { }' */ this.source = source; } if (plugin) { /** * @member {string} - Plugin name, if error came from plugin. * * @example * error.plugin //=> 'postcss-vars' */ this.plugin = plugin; } if (typeof line !== 'undefined' && typeof column !== 'undefined') { /** * @member {number} - Source line of the error. * * @example * error.line //=> 2 * error.input.line //=> 4 */ this.line = line; /** * @member {number} - Source column of the error. * * @example * error.column //=> 1 * error.input.column //=> 4 */ this.column = column; } this.setMessage(); if (Error.captureStackTrace) { Error.captureStackTrace(this, CssSyntaxError); } } createClass(CssSyntaxError, [{ key: 'setMessage', value: function setMessage() { /** * @member {string} - Full error text in the GNU error format * with plugin, file, line and column. * * @example * error.message //=> 'a.css:1:1: Unclosed block' */ this.message = this.plugin ? this.plugin + ': ' : ''; this.message += this.file ? this.file : '<css input>'; if (typeof this.line !== 'undefined') { this.message += ':' + this.line + ':' + this.column; } this.message += ': ' + this.reason; } /** * Returns a few lines of CSS source that caused the error. * * If the CSS has an input source map without `sourceContent`, * this method will return an empty string. * * @param {boolean} [color] whether arrow will be colored red by terminal * color codes. By default, PostCSS will detect * color support by `process.stdout.isTTY` * and `process.env.NODE_DISABLE_COLORS`. * * @example * error.showSourceCode() //=> " 4 | } * // 5 | a { * // > 6 | bad * // | ^ * // 7 | } * // 8 | b {" * * @return {string} few lines of CSS source that caused the error */ }, { key: 'showSourceCode', value: function showSourceCode(color) { var _this = this; if (!this.source) return ''; var css = this.source; if (typeof color === 'undefined') color = index$1; if (color) css = terminalHighlight(css); var lines = css.split(/\r?\n/); var start = Math.max(this.line - 3, 0); var end = Math.min(this.line + 2, lines.length); var maxWidth = String(end).length; return lines.slice(start, end).map(function (line, index) { var number = start + 1 + index; var padded = (' ' + number).slice(-maxWidth); var gutter = ' ' + padded + ' | '; if (number === _this.line) { var spacing = gutter.replace(/\d/g, ' ') + line.slice(0, _this.column - 1).replace(/[^\t]/g, ' '); return '>' + gutter + line + '\n ' + spacing + '^'; } else { return ' ' + gutter + line; } }).join('\n'); } /** * Returns error position, message and source code of the broken part. * * @example * error.toString() //=> "CssSyntaxError: app.css:1:1: Unclosed block * // > 1 | a { * // | ^" * * @return {string} error position, message and source code */ }, { key: 'toString', value: function toString() { var code = this.showSourceCode(); if (code) { code = '\n\n' + code + '\n'; } return this.name + ': ' + this.message + code; } }, { key: 'generated', get: function get() { warnOnce('CssSyntaxError#generated is depreacted. Use input instead.'); return this.input; } /** * @memberof CssSyntaxError# * @member {Input} input - Input object with PostCSS internal information * about input file. If input has source map * from previous tool, PostCSS will use origin * (for example, Sass) source. You can use this * object to get PostCSS input source. * * @example * error.input.file //=> 'a.css' * error.file //=> 'a.sass' */ }]); return CssSyntaxError; }(); /* eslint-disable valid-jsdoc */ var defaultRaw = { colon: ': ', indent: ' ', beforeDecl: '\n', beforeRule: '\n', beforeOpen: ' ', beforeClose: '\n', beforeComment: '\n', after: '\n', emptyBody: '', commentLeft: ' ', commentRight: ' ' }; function capitalize(str) { return str[0].toUpperCase() + str.slice(1); } var Stringifier = function () { function Stringifier(builder) { classCallCheck(this, Stringifier); this.builder = builder; } createClass(Stringifier, [{ key: 'stringify', value: function stringify(node, semicolon) { this[node.type](node, semicolon); } }, { key: 'root', value: function root(node) { this.body(node); if (node.raws.after) this.builder(node.raws.after); } }, { key: 'comment', value: function comment(node) { var left = this.raw(node, 'left', 'commentLeft'); var right = this.raw(node, 'right', 'commentRight'); this.builder('/*' + left + node.text + right + '*/', node); } }, { key: 'decl', value: function decl(node, semicolon) { var between = this.raw(node, 'between', 'colon'); var string = node.prop + between + this.rawValue(node, 'value'); if (node.important) { string += node.raws.important || ' !important'; } if (semicolon) string += ';'; this.builder(string, node); } }, { key: 'rule', value: function rule(node) { this.block(node, this.rawValue(node, 'selector')); } }, { key: 'atrule', value: function atrule(node, semicolon) { var name = '@' + node.name; var params = node.params ? this.rawValue(node, 'params') : ''; if (typeof node.raws.afterName !== 'undefined') { name += node.raws.afterName; } else if (params) { name += ' '; } if (node.nodes) { this.block(node, name + params); } else { var end = (node.raws.between || '') + (semicolon ? ';' : ''); this.builder(name + params + end, node); } } }, { key: 'body', value: function body(node) { var last = node.nodes.length - 1; while (last > 0) { if (node.nodes[last].type !== 'comment') break; last -= 1; } var semicolon = this.raw(node, 'semicolon'); for (var i = 0; i < node.nodes.length; i++) { var child = node.nodes[i]; var before = this.raw(child, 'before'); if (before) this.builder(before); this.stringify(child, last !== i || semicolon); } } }, { key: 'block', value: function block(node, start) { var between = this.raw(node, 'between', 'beforeOpen'); this.builder(start + between + '{', node, 'start'); var after = void 0; if (node.nodes && node.nodes.length) { this.body(node); after = this.raw(node, 'after'); } else { after = this.raw(node, 'after', 'emptyBody'); } if (after) this.builder(after); this.builder('}', node, 'end'); } }, { key: 'raw', value: function raw(node, own, detect) { var value = void 0; if (!detect) detect = own; // Already had if (own) { value = node.raws[own]; if (typeof value !== 'undefined') return value; } var parent = node.parent; // Hack for first rule in CSS if (detect === 'before') { if (!parent || parent.type === 'root' && parent.first === node) { return ''; } } // Floating child without parent if (!parent) return defaultRaw[detect]; // Detect style by other nodes var root = node.root(); if (!root.rawCache) root.rawCache = {}; if (typeof root.rawCache[detect] !== 'undefined') { return root.rawCache[detect]; } if (detect === 'before' || detect === 'after') { return this.beforeAfter(node, detect); } else { var method = 'raw' + capitalize(detect); if (this[method]) { value = this[method](root, node); } else { root.walk(function (i) { value = i.raws[own]; if (typeof value !== 'undefined') return false; }); } } if (typeof value === 'undefined') value = defaultRaw[detect]; root.rawCache[detect] = value; return value; } }, { key: 'rawSemicolon', value: function rawSemicolon(root) { var value = void 0; root.walk(function (i) { if (i.nodes && i.nodes.length && i.last.type === 'decl') { value = i.raws.semicolon; if (typeof value !== 'undefined') return false; } }); return value; } }, { key: 'rawEmptyBody', value: function rawEmptyBody(root) { var value = void 0; root.walk(function (i) { if (i.nodes && i.nodes.length === 0) { value = i.raws.after; if (typeof value !== 'undefined') return false; } }); return value; } }, { key: 'rawIndent', value: function rawIndent(root) { if (root.raws.indent) return root.raws.indent; var value = void 0; root.walk(function (i) { var p = i.parent; if (p && p !== root && p.parent && p.parent === root) { if (typeof i.raws.before !== 'undefined') { var parts = i.raws.before.split('\n'); value = parts[parts.length - 1]; value = value.replace(/[^\s]/g, ''); return false; } } }); return value; } }, { key: 'rawBeforeComment', value: function rawBeforeComment(root, node) { var value = void 0; root.walkComments(function (i) { if (typeof i.raws.before !== 'undefined') { value = i.raws.before; if (value.indexOf('\n') !== -1) { value = value.replace(/[^\n]+$/, ''); } return false; } }); if (typeof value === 'undefined') { value = this.raw(node, null, 'beforeDecl'); } return value; } }, { key: 'rawBeforeDecl', value: function rawBeforeDecl(root, node) { var value = void 0; root.walkDecls(function (i) { if (typeof i.raws.before !== 'undefined') { value = i.raws.before; if (value.indexOf('\n') !== -1) { value = value.replace(/[^\n]+$/, ''); } return false; } }); if (typeof value === 'undefined') { value = this.raw(node, null, 'beforeRule'); } return value; } }, { key: 'rawBeforeRule', value: function rawBeforeRule(root) { var value = void 0; root.walk(function (i) { if (i.nodes && (i.parent !== root || root.first !== i)) { if (typeof i.raws.before !== 'undefined') { value = i.raws.before; if (value.indexOf('\n') !== -1) { value = value.replace(/[^\n]+$/, ''); } return false; } } }); return value; } }, { key: 'rawBeforeClose', value: function rawBeforeClose(root) { var value = void 0; root.walk(function (i) { if (i.nodes && i.nodes.length > 0) { if (typeof i.raws.after !== 'undefined') { value = i.raws.after; if (value.indexOf('\n') !== -1) { value = value.replace(/[^\n]+$/, ''); } return false; } } }); return value; } }, { key: 'rawBeforeOpen', value: function rawBeforeOpen(root) { var value = void 0; root.walk(function (i) { if (i.type !== 'decl') { value = i.raws.between; if (typeof value !== 'undefined') return false; } }); return value; } }, { key: 'rawColon', value: function rawColon(root) { var value = void 0; root.walkDecls(function (i) { if (typeof i.raws.between !== 'undefined') { value = i.raws.between.replace(/[^\s:]/g, ''); return false; } }); return value; } }, { key: 'beforeAfter', value: function beforeAfter(node, detect) { var value = void 0; if (node.type === 'decl') { value = this.raw(node, null, 'beforeDecl'); } else if (node.type === 'comment') { value = this.raw(node, null, 'beforeComment'); } else if (detect === 'before') { value = this.raw(node, null, 'beforeRule'); } else { value = this.raw(node, null, 'beforeClose'); } var buf = node.parent; var depth = 0; while (buf && buf.type !== 'root') { depth += 1; buf = buf.parent; } if (value.indexOf('\n') !== -1) { var indent = this.raw(node, null, 'indent'); if (indent.length) { for (var step = 0; step < depth; step++) { value += indent; } } } return value; } }, { key: 'rawValue', value: function rawValue(node, prop) { var value = node[prop]; var raw = node.raws[prop]; if (raw && raw.value === value) { return raw.raw; } else { return value; } } }]); return Stringifier; }(); function stringify$1(node, builder) { var str = new Stringifier(builder); str.stringify(node); } /** * @typedef {object} position * @property {number} line - source line in file * @property {number} column - source column in file */ /** * @typedef {object} source * @property {Input} input - {@link Input} with input file * @property {position} start - The starting position of the node’s source * @property {position} end - The ending position of the node’s source */ var cloneNode = function cloneNode(obj, parent) { var cloned = new obj.constructor(); for (var i in obj) { if (!obj.hasOwnProperty(i)) continue; var value = obj[i]; var type = typeof value === 'undefined' ? 'undefined' : _typeof(value); if (i === 'parent' && type === 'object') { if (parent) cloned[i] = parent; } else if (i === 'source') { cloned[i] = value; } else if (value instanceof Array) { cloned[i] = value.map(function (j) { return cloneNode(j, cloned); }); } else if (i !== 'before' && i !== 'after' && i !== 'between' && i !== 'semicolon') { if (type === 'object' && value !== null) value = cloneNode(value); cloned[i] = value; } } return cloned; }; /** * All node classes inherit the following common methods. * * @abstract */ var Node = function () { /** * @param {object} [defaults] - value for node properties */ function Node() { var defaults$$1 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; classCallCheck(this, Node); this.raws = {}; for (var name in defaults$$1) { this[name] = defaults$$1[name]; } } /** * Returns a CssSyntaxError instance containing the original position * of the node in the source, showing line and column numbers and also * a small excerpt to facilitate debugging. * * If present, an input source map will be used to get the original position * of the source, even from a previous compilation step * (e.g., from Sass compilation). * * This method produces very useful error messages. * * @param {string} message - error description * @param {object} [opts] - options * @param {string} opts.plugin - plugin name that created this error. * PostCSS will set it automatically. * @param {string} opts.word - a word inside a node’s string that should * be highlighted as the source of the error * @param {number} opts.index - an index inside a node’s string that should * be highlighted as the source of the error * * @return {CssSyntaxError} error object to throw it * * @example * if ( !variables[name] ) { * throw decl.error('Unknown variable ' + name, { word: name }); * // CssSyntaxError: postcss-vars:a.sass:4:3: Unknown variable $black * // color: $black * // a * // ^ * // background: white * } */ createClass(Node, [{ key: 'error', value: function error(message) { var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; if (this.source) { var pos = this.positionBy(opts); return this.source.input.error(message, pos.line, pos.column, opts); } else { return new CssSyntaxError(message); } } /** * This method is provided as a convenience wrapper for {@link Result#warn}. * * @param {Result} result - the {@link Result} instance * that will receive the warning * @param {string} text - warning message * @param {object} [opts] - options * @param {string} opts.plugin - plugin name that created this warning. * PostCSS will set it automatically. * @param {string} opts.word - a word inside a node’s string that should * be highlighted as the source of the warning * @param {number} opts.index - an index inside a node’s string that should * be highlighted as the source of the warning * * @return {Warning} created warning object * * @example * const plugin = postcss.plugin('postcss-deprecated', () => { * return (root, result) => { * root.walkDecls('bad', decl => { * decl.warn(result, 'Deprecated property bad'); * }); * }; * }); */ }, { key: 'warn', value: function warn(result, text, opts) { var data = { node: this }; for (var i in opts) { data[i] = opts[i]; }return result.warn(text, data); } /** * Removes the node from its parent and cleans the parent properties * from the node and its children. * * @example * if ( decl.prop.match(/^-webkit-/) ) { * decl.remove(); * } * * @return {Node} node to make calls chain */ }, { key: 'remove', value: function remove() { if (this.parent) { this.parent.removeChild(this); } this.parent = undefined; return this; } /** * Returns a CSS string representing the node. * * @param {stringifier|syntax} [stringifier] - a syntax to use * in string generation * * @return {string} CSS string of this node * * @example * postcss.rule({ selector: 'a' }).toString() //=> "a {}" */ }, { key: 'toString', value: function toString() { var stringifier = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : stringify$1; if (stringifier.stringify) stringifier = stringifier.stringify; var result = ''; stringifier(this, function (i) { result += i; }); return result; } /** * Returns a clone of the node. * * The resulting cloned node and its (cloned) children will have * a clean parent and code style properties. * * @param {object} [overrides] - new properties to override in the clone. * * @example * const cloned = decl.clone({ prop: '-moz-' + decl.prop }); * cloned.raws.before //=> undefined * cloned.parent //=> undefined * cloned.toString() //=> -moz-transform: scale(0) * * @return {Node} clone of the node */ }, { key: 'clone', value: function clone() { var overrides = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; var cloned = cloneNode(this); for (var name in overrides) { cloned[name] = overrides[name]; } return cloned; } /** * Shortcut to clone the node and insert the resulting cloned node * before the current node. * * @param {object} [overrides] - new properties to override in the clone. * * @example * decl.cloneBefore({ prop: '-moz-' + decl.prop }); * * @return {Node} - new node */ }, { key: 'cloneBefore', value: function cloneBefore() { var overrides = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; var cloned = this.clone(overrides); this.parent.insertBefore(this, cloned); return cloned; } /** * Shortcut to clone the node and insert the resulting cloned node * after the current node. * * @param {object} [overrides] - new properties to override in the clone. * * @return {Node} - new node */ }, { key: 'cloneAfter', value: function cloneAfter() { var overrides = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; var cloned = this.clone(overrides); this.parent.insertAfter(this, cloned); return cloned; } /** * Inserts node(s) before the current node and removes the current node. * * @param {...Node} nodes - node(s) to replace current one * * @example * if ( atrule.name == 'mixin' ) { * atrule.replaceWith(mixinRules[atrule.params]); * } * * @return {Node} current node to methods chain */ }, { key: 'replaceWith', value: function replaceWith() { var _this = this; if (this.parent) { for (var _len = arguments.length, nodes = Array(_len), _key = 0; _key < _len; _key++) { nodes[_key] = arguments[_key]; } nodes.forEach(function (node) { _this.parent.insertBefore(_this, node); }); this.remove(); } return this; } /** * Removes the node from its current parent and inserts it * at the end of `newParent`. * * This will clean the `before` and `after` code {@link Node#raws} data * from the node and replace them with the indentation style of `newParent`. * It will also clean the `between` property * if `newParent` is in another {@link Root}. * * @param {Container} newParent - container node where the current node * will be moved * * @example * atrule.moveTo(atrule.root()); * * @return {Node} current node to methods chain */ }, { key: 'moveTo', value: function moveTo(newParent) { this.cleanRaws(this.root() === newParent.root()); this.remove(); newParent.append(this); return this; } /** * Removes the node from its current parent and inserts it into * a new parent before `otherNode`. * * This will also clean the node’s code style properties just as it would * in {@link Node#moveTo}. * * @param {Node} otherNode - node that will be before current node * * @return {Node} current node to methods chain */ }, { key: 'moveBefore', value: function moveBefore(otherNode) { this.cleanRaws(this.root() === otherNode.root()); this.remove(); otherNode.parent.insertBefore(otherNode, this); return this; } /** * Removes the node from its current parent and inserts it into * a new parent after `otherNode`. * * This will also clean the node’s code style properties just as it would * in {@link Node#moveTo}. * * @param {Node} otherNode - node that will be after current node * * @return {Node} current node to methods chain */ }, { key: 'moveAfter', value: function moveAfter(otherNode) { this.cleanRaws(this.root() === otherNode.root()); this.remove(); otherNode.parent.insertAfter(otherNode, this); return this; } /** * Returns the next child of the node’s parent. * Returns `undefined` if the current node is the last child. * * @return {Node|undefined} next node * * @example * if ( comment.text === 'delete next' ) { * const next = comment.next(); * if ( next ) { * next.remove(); * } * } */ }, { key: 'next', value: function next() { var index = this.parent.index(this); return this.parent.nodes[index + 1]; } /** * Returns the previous child of the node’s parent. * Returns `undefined` if the current node is the first child. * * @return {Node|undefined} previous node * * @example * const annotation = decl.prev(); * if ( annotation.type == 'comment' ) { * readAnnotation(annotation.text); * } */ }, { key: 'prev', value: function prev() { var index = this.parent.index(this); return this.parent.nodes[index - 1]; } }, { key: 'toJSON', value: function toJSON() { var fixed = {}; for (var name in this) { if (!this.hasOwnProperty(name)) continue; if (name === 'parent') continue; var value = this[name]; if (value instanceof Array) { fixed[name] = value.map(function (i) { if ((typeof i === 'undefined' ? 'undefined' : _typeof(i)) === 'object' && i.toJSON) { return i.toJSON(); } else { return i; } }); } else if ((typeof value === 'undefined' ? 'undefined' : _typeof(value)) === 'object' && value.toJSON) { fixed[name] = value.toJSON(); } else { fixed[name] = value; } } return fixed; } /** * Returns a {@link Node#raws} value. If the node is missing * the code style property (because the node was manually built or cloned), * PostCSS will try to autodetect the code style property by looking * at other nodes in the tree. * * @param {string} prop - name of code style property * @param {string} [defaultType] - name of default value, it can be missed * if the value is the same as prop * * @example * const root = postcss.parse('a { background: white }'); * root.nodes[0].append({ prop: 'color', value: 'black' }); * root.nodes[0].nodes[1].raws.before //=> undefined * root.nodes[0].nodes[1].raw('before') //=> ' ' * * @return {string} code style value */ }, { key: 'raw', value: function raw(prop, defaultType) { var str = new Stringifier(); return str.raw(this, prop, defaultType); } /** * Finds the Root instance of the node’s tree. * * @example * root.nodes[0].nodes[0].root() === root * * @return {Root} root parent */ }, { key: 'root', value: function root() { var result = this; while (result.parent) { result = result.parent; }return result; } }, { key: 'cleanRaws', value: function cleanRaws(keepBetween) { delete this.raws.before; delete this.raws.after; if (!keepBetween) delete this.raws.between; } }, { key: 'positionInside', value: function positionInside(index) { var string = this.toString(); var column = this.source.start.column; var line = this.source.start.line; for (var i = 0; i < index; i++) { if (string[i] === '\n') { column = 1; line += 1; } else { column += 1; } } return { line: line, column: column }; } }, { key: 'positionBy', value: function positionBy(opts) { var pos = this.source.start; if (opts.index) { pos = this.positionInside(opts.index); } else if (opts.word) { var index = this.toString().indexOf(opts.word); if (index !== -1) pos = this.positionInside(index); } return pos; } }, { key: 'removeSelf', value: function removeSelf() { warnOnce('Node#removeSelf is deprecated. Use Node#remove.'); return this.remove(); } }, { key: 'replace', value: function replace(nodes) { warnOnce('Node#replace is deprecated. Use Node#replaceWith'); return this.replaceWith(nodes); } }, { key: 'style', value: function style(own, detect) { warnOnce('Node#style() is deprecated. Use Node#raw()'); return this.raw(own, detect); } }, { key: 'cleanStyles', value: function cleanStyles(keepBetween) { warnOnce('Node#cleanStyles() is deprecated. Use Node#cleanRaws()'); return this.cleanRaws(keepBetween); } }, { key: 'before', get: function get() { warnOnce('Node#before is deprecated. Use Node#raws.before'); return this.raws.before; }, set: function set(val) { warnOnce('Node#before is deprecated. Use Node#raws.before'); this.raws.before = val; } }, { key: 'between', get: function get() { warnOnce('Node#between is deprecated. Use Node#raws.between'); return this.raws.between; }, set: function set(val) { warnOnce('Node#between is deprecated. Use Node#raws.between'); this.raws.between = val; } /** * @memberof Node# * @member {string} type - String representing the node’s type. * Possible values are `root`, `atrule`, `rule`, * `decl`, or `comment`. * * @example * postcss.decl({ prop: 'color', value: 'black' }).type //=> 'decl' */ /** * @memberof Node# * @member {Container} parent - the node’s parent node. * * @example * root.nodes[0].parent == root; */ /** * @memberof Node# * @member {source} source - the input source of the node * * The property is used in source map generation. * * If you create a node manually (e.g., with `postcss.decl()`), * that node will not have a `source` property and will be absent * from the source map. For this reason, the plugin developer should * consider cloning nodes to create new ones (in which case the new node’s * source will reference the original, cloned node) or setting * the `source` property manually. * * ```js * // Bad * const prefixed = postcss.decl({ * prop: '-moz-' + decl.prop, * value: decl.value * }); * * // Good * const prefixed = decl.clone({ prop: '-moz-' + decl.prop }); * ``` * * ```js * if ( atrule.name == 'add-link' ) { * const rule = postcss.rule({ selector: 'a', source: atrule.source }); * atrule.parent.insertBefore(atrule, rule); * } * ``` * * @example * decl.source.input.from //=> '/home/ai/a.sass' * decl.source.start //=> { line: 10, column: 2 } * decl.source.end //=> { line: 10, column: 12 } */ /** * @memberof Node# * @member {object} raws - Information to generate byte-to-byte equal * node string as it was in the origin input. * * Every parser saves its own properties, * but the default CSS parser uses: * * * `before`: the space symbols before the node. It also stores `*` * and `_` symbols before the declaration (IE hack). * * `after`: the space symbols after the last child of the node * to the end of the node. * * `between`: the symbols between the property and value * for declarations, selector and `{` for rules, or last parameter * and `{` for at-rules. * * `semicolon`: contains true if the last child has * an (optional) semicolon. * * `afterName`: the space between the at-rule name and its parameters. * * `left`: the space symbols between `/*` and the comment’s text. * * `right`: the space symbols between the comment’s text * and <code>*&#47;</code>. * * `important`: the content of the important statement, * if it is not just `!important`. * * PostCSS cleans selectors, declaration values and at-rule parameters * from comments and extra spaces, but it stores origin content in raws * properties. As such, if you don’t change a declaration’s value, * PostCSS will use the raw value with comments. * * @example * const root = postcss.parse('a {\n color:black\n}') * root.first.first.raws //=> { before: '\n ', between: ':' } */ }]); return Node; }(); /** * Represents a CSS declaration. * * @extends Node * * @example * const root = postcss.parse('a { color: black }'); * const decl = root.first.first; * decl.type //=> 'decl' * decl.toString() //=> ' color: black' */ var Declaration = function (_Node) { inherits(Declaration, _Node); function Declaration(defaults$$1) { classCallCheck(this, Declaration); var _this = possibleConstructorReturn(this, (Declaration.__proto__ || Object.getPrototypeOf(Declaration)).call(this, defaults$$1)); _this.type = 'decl'; return _this; } createClass(Declaration, [{ key: '_value', get: function get() { warnOnce('Node#_value was deprecated. Use Node#raws.value'); return this.raws.value; }, set: function set(val) { warnOnce('Node#_value was deprecated. Use Node#raws.value'); this.raws.value = val; } }, { key: '_important', get: function get() { warnOnce('Node#_important was deprecated. Use Node#raws.important'); return this.raws.important; }, set: function set(val) { warnOnce('Node#_important was deprecated. Use Node#raws.important'); this.raws.important = val; } /** * @memberof Declaration# * @member {string} prop - the declaration’s property name * * @example * const root = postcss.parse('a { color: black }'); * const decl = root.first.first; * decl.prop //=> 'color' */ /** * @memberof Declaration# * @member {string} value - the declaration’s value * * @example * const root = postcss.parse('a { color: black }'); * const decl = root.first.first; * decl.value //=> 'black' */ /** * @memberof Declaration# * @member {boolean} important - `true` if the declaration * has an !important annotation. * * @example * const root = postcss.parse('a { color: black !important; color: red }'); * root.first.first.important //=> true * root.first.last.important //=> undefined */ /** * @memberof Declaration# * @member {object} raws - Information to generate byte-to-byte equal * node string as it was in the origin input. * * Every parser saves its own properties, * but the default CSS parser uses: * * * `before`: the space symbols before the node. It also stores `*` * and `_` symbols before the declaration (IE hack). * * `between`: the symbols between the property and value * for declarations, selector and `{` for rules, or last parameter * and `{` for at-rules. * * `important`: the content of the important statement, * if it is not just `!important`. * * PostCSS cleans declaration from comments and extra spaces, * but it stores origin content in raws properties. * As such, if you don’t change a declaration’s value, * PostCSS will use the raw value with comments. * * @example * const root = postcss.parse('a {\n color:black\n}') * root.first.first.raws //=> { before: '\n ', between: ':' } */ }]); return Declaration; }(Node); /** * Represents a comment between declarations or statements (rule and at-rules). * * Comments inside selectors, at-rule parameters, or declaration values * will be stored in the `raws` properties explained above. * * @extends Node */ var Comment = function (_Node) { inherits(Comment, _Node); function Comment(defaults$$1) { classCallCheck(this, Comment); var _this = possibleConstructorReturn(this, (Comment.__proto__ || Object.getPrototypeOf(Comment)).call(this, defaults$$1)); _this.type = 'comment'; return _this; } createClass(Comment, [{ key: 'left', get: function get() { warnOnce('Comment#left was deprecated. Use Comment#raws.left'); return this.raws.left; }, set: function set(val) { warnOnce('Comment#left was deprecated. Use Comment#raws.left'); this.raws.left = val; } }, { key: 'right', get: function get() { warnOnce('Comment#right was deprecated. Use Comment#raws.right'); return this.raws.right; }, set: function set(val) { warnOnce('Comment#right was deprecated. Use Comment#raws.right'); this.raws.right = val; } /** * @memberof Comment# * @member {string} text - the comment’s text */ /** * @memberof Comment# * @member {object} raws - Information to generate byte-to-byte equal * node string as it was in the origin input. * * Every parser saves its own properties, * but the default CSS parser uses: * * * `before`: the space symbols before the node. * * `left`: the space symbols between `/*` and the comment’s text. * * `right`: the space symbols between the comment’s text. */ }]); return Comment; }(Node); var Parser = function () { function Parser(input) { classCallCheck(this, Parser); this.input = input; this.pos = 0; this.root = new Root(); this.current = this.root; this.spaces = ''; this.semicolon = false; this.root.source = { input: input, start: { line: 1, column: 1 } }; } createClass(Parser, [{ key: 'tokenize', value: function tokenize() { this.tokens = tokenize$1(this.input); } }, { key: 'loop', value: function loop() { var token = void 0; while (this.pos < this.tokens.length) { token = this.tokens[this.pos]; switch (token[0]) { case 'space': case ';': this.spaces += token[1]; break; case '}': this.end(token); break; case 'comment': this.comment(token); break; case 'at-word': this.atrule(token); break; case '{': this.emptyRule(token); break; default: this.other(); break; } this.pos += 1; } this.endFile(); } }, { key: 'comment', value: function comment(token) { var node = new Comment(); this.init(node, token[2], token[3]); node.source.end = { line: token[4], column: token[5] }; var text = token[1].slice(2, -2); if (/^\s*$/.test(text)) { node.text = ''; node.raws.left = text; node.raws.right = ''; } else { var match = text.match(/^(\s*)([^]*[^\s])(\s*)$/); node.text = match[2]; node.raws.left = match[1]; node.raws.right = match[3]; } } }, { key: 'emptyRule', value: function emptyRule(token) { var node = new Rule(); this.init(node, token[2], token[3]); node.selector = ''; node.raws.between = ''; this.current = node; } }, { key: 'other', value: function other() { var token = void 0; var end = false; var type = null; var colon = false; var bracket = null; var brackets = []; var start = this.pos; while (this.pos < this.tokens.length) { token = this.tokens[this.pos]; type = token[0]; if (type === '(' || type === '[') { if (!bracket) bracket = token; brackets.push(type === '(' ? ')' : ']'); } else if (brackets.length === 0) { if (type === ';') { if (colon) { this.decl(this.tokens.slice(start, this.pos + 1)); return; } else { break; } } else if (type === '{') { this.rule(this.tokens.slice(start, this.pos + 1)); return; } else if (type === '}') { this.pos -= 1; end = true; break; } else if (type === ':') { colon = true; } } else if (type === brackets[brackets.length - 1]) { brackets.pop(); if (brackets.length === 0) bracket = null; } this.pos += 1; } if (this.pos === this.tokens.length) { this.pos -= 1; end = true; } if (brackets.length > 0) this.unclosedBracket(bracket); if (end && colon) { while (this.pos > start) { token = this.tokens[this.pos][0]; if (token !== 'space' && token !== 'comment') break; this.pos -= 1; } this.decl(this.tokens.slice(start, this.pos + 1)); return; } this.unknownWord(start); } }, { key: 'rule', value: function rule(tokens) { tokens.pop(); var node = new Rule(); this.init(node, tokens[0][2], tokens[0][3]); node.raws.between = this.spacesFromEnd(tokens); this.raw(node, 'selector', tokens); this.current = node; } }, { key: 'decl', value: function decl(tokens) { var node = new Declaration(); this.init(node); var last = tokens[tokens.length - 1]; if (last[0] === ';') { this.semicolon = true; tokens.pop(); } if (last[4]) { node.source.end = { line: last[4], column: last[5] }; } else { node.source.end = { line: last[2], column: last[3] }; } while (tokens[0][0] !== 'word') { node.raws.before += tokens.shift()[1]; } node.source.start = { line: tokens[0][2], column: tokens[0][3] }; node.prop = ''; while (tokens.length) { var type = tokens[0][0]; if (type === ':' || type === 'space' || type === 'comment') { break; } node.prop += tokens.shift()[1]; } node.raws.between = ''; var token = void 0; while (tokens.length) { token = tokens.shift(); if (token[0] === ':') { node.raws.between += token[1]; break; } else { node.raws.between += token[1]; } } if (node.prop[0] === '_' || node.prop[0] === '*') { node.raws.before += node.prop[0]; node.prop = node.prop.slice(1); } node.raws.between += this.spacesFromStart(tokens); this.precheckMissedSemicolon(tokens); for (var i = tokens.length - 1; i > 0; i--) { token = tokens[i]; if (token[1] === '!important') { node.important = true; var string = this.stringFrom(tokens, i); string = this.spacesFromEnd(tokens) + string; if (string !== ' !important') node.raws.important = string; break; } else if (token[1] === 'important') { var cache = tokens.slice(0); var str = ''; for (var j = i; j > 0; j--) { var _type = cache[j][0]; if (str.trim().indexOf('!') === 0 && _type !== 'space') { break; } str = cache.pop()[1] + str; } if (str.trim().indexOf('!') === 0) { node.important = true; node.raws.important = str; tokens = cache; } } if (token[0] !== 'space' && token[0] !== 'comment') { break; } } this.raw(node, 'value', tokens); if (node.value.indexOf(':') !== -1) this.checkMissedSemicolon(tokens); } }, { key: 'atrule', value: function atrule(token) { var node = new AtRule(); node.name = token[1].slice(1); if (node.name === '') { this.unnamedAtrule(node, token); } this.init(node, token[2], token[3]); var last = false; var open = false; var params = []; this.pos += 1; while (this.pos < this.tokens.length) { token = this.tokens[this.pos]; if (token[0] === ';') { node.source.end = { line: token[2], column: token[3] }; this.semicolon = true; break; } else if (token[0] === '{') { open = true; break; } else if (token[0] === '}') { this.end(token); break; } else { params.push(token); } this.pos += 1; } if (this.pos === this.tokens.length) { last = true; } node.raws.between = this.spacesFromEnd(params); if (params.length) { node.raws.afterName = this.spacesFromStart(params); this.raw(node, 'params', params); if (last) { token = params[params.length - 1]; node.source.end = { line: token[4], column: token[5] }; this.spaces = node.raws.between; node.raws.between = ''; } } else { node.raws.afterName = ''; node.params = ''; } if (open) { node.nodes = []; this.current = node; } } }, { key: 'end', value: function end(token) { if (this.current.nodes && this.current.nodes.length) { this.current.raws.semicolon = this.semicolon; } this.semicolon = false; this.current.raws.after = (this.current.raws.after || '') + this.spaces; this.spaces = ''; if (this.current.parent) { this.current.source.end = { line: token[2], column: token[3] }; this.current = this.current.parent; } else { this.unexpectedClose(token); } } }, { key: 'endFile', value: function endFile() { if (this.current.parent) this.unclosedBlock(); if (this.current.nodes && this.current.nodes.length) { this.current.raws.semicolon = this.semicolon; } this.current.raws.after = (this.current.raws.after || '') + this.spaces; } // Helpers }, { key: 'init', value: function init(node, line, column) { this.current.push(node); node.source = { start: { line: line, column: column }, input: this.input }; node.raws.before = this.spaces; this.spaces = ''; if (node.type !== 'comment') this.semicolon = false; } }, { key: 'raw', value: function raw(node, prop, tokens) { var token = void 0, type = void 0; var length = tokens.length; var value = ''; var clean = true; for (var i = 0; i < length; i += 1) { token = tokens[i]; type = token[0]; if (type === 'comment' || type === 'space' && i === length - 1) { clean = false; } else { value += token[1]; } } if (!clean) { var raw = tokens.reduce(function (all, i) { return all + i[1]; }, ''); node.raws[prop] = { value: value, raw: raw }; } node[prop] = value; } }, { key: 'spacesFromEnd', value: function spacesFromEnd(tokens) { var lastTokenType = void 0; var spaces = ''; while (tokens.length) { lastTokenType = tokens[tokens.length - 1][0]; if (lastTokenType !== 'space' && lastTokenType !== 'comment') break; spaces = tokens.pop()[1] + spaces; } return spaces; } }, { key: 'spacesFromStart', value: function spacesFromStart(tokens) { var next = void 0; var spaces = ''; while (tokens.length) { next = tokens[0][0]; if (next !== 'space' && next !== 'comment') break; spaces += tokens.shift()[1]; } return spaces; } }, { key: 'stringFrom', value: function stringFrom(tokens, from) { var result = ''; for (var i = from; i < tokens.length; i++) { result += tokens[i][1]; } tokens.splice(from, tokens.length - from); return result; } }, { key: 'colon', value: function colon(tokens) { var brackets = 0; var token = void 0, type = void 0, prev = void 0; for (var i = 0; i < tokens.length; i++) { token = tokens[i]; type = token[0]; if (type === '(') { brackets += 1; } else if (type === ')') { brackets -= 1; } else if (brackets === 0 && type === ':') { if (!prev) { this.doubleColon(token); } else if (prev[0] === 'word' && prev[1] === 'progid') { continue; } else { return i; } } prev = token; } return false; } // Errors }, { key: 'unclosedBracket', value: function unclosedBracket(bracket) { throw this.input.error('Unclosed bracket', bracket[2], bracket[3]); } }, { key: 'unknownWord', value: function unknownWord(start) { var token = this.tokens[start]; throw this.input.error('Unknown word', token[2], token[3]); } }, { key: 'unexpectedClose', value: function unexpectedClose(token) { throw this.input.error('Unexpected }', token[2], token[3]); } }, { key: 'unclosedBlock', value: function unclosedBlock() { var pos = this.current.source.start; throw this.input.error('Unclosed block', pos.line, pos.column); } }, { key: 'doubleColon', value: function doubleColon(token) { throw this.input.error('Double colon', token[2], token[3]); } }, { key: 'unnamedAtrule', value: function unnamedAtrule(node, token) { throw this.input.error('At-rule without name', token[2], token[3]); } }, { key: 'precheckMissedSemicolon', value: function precheckMissedSemicolon(tokens) { // Hook for Safe Parser tokens; } }, { key: 'checkMissedSemicolon', value: function checkMissedSemicolon(tokens) { var colon = this.colon(tokens); if (colon === false) return; var founded = 0; var token = void 0; for (var j = colon - 1; j >= 0; j--) { token = tokens[j]; if (token[0] !== 'space') { founded += 1; if (founded === 2) break; } } throw this.input.error('Missed semicolon', token[2], token[3]); } }]); return Parser; }(); function parse(css, opts) { if (opts && opts.safe) { throw new Error('Option safe was removed. ' + 'Use parser: require("postcss-safe-parser")'); } var input = new Input(css, opts); var parser = new Parser(input); try { parser.tokenize(); parser.loop(); } catch (e) { if (e.name === 'CssSyntaxError' && opts && opts.from) { if (/\.scss$/i.test(opts.from)) { e.message += '\nYou tried to parse SCSS with ' + 'the standard CSS parser; ' + 'try again with the postcss-scss parser'; } else if (/\.less$/i.test(opts.from)) { e.message += '\nYou tried to parse Less with ' + 'the standard CSS parser; ' + 'try again with the postcss-less parser'; } } throw e; } return parser.root; } function cleanSource(nodes) { return nodes.map(function (i) { if (i.nodes) i.nodes = cleanSource(i.nodes); delete i.source; return i; }); } /** * @callback childCondition * @param {Node} node - container child * @param {number} index - child index * @param {Node[]} nodes - all container children * @return {boolean} */ /** * @callback childIterator * @param {Node} node - container child * @param {number} index - child index * @return {false|undefined} returning `false` will break iteration */ /** * The {@link Root}, {@link AtRule}, and {@link Rule} container nodes * inherit some common methods to help work with their children. * * Note that all containers can store any content. If you write a rule inside * a rule, PostCSS will parse it. * * @extends Node * @abstract */ var Container = function (_Node) { inherits(Container, _Node); function Container() { classCallCheck(this, Container); return possibleConstructorReturn(this, (Container.__proto__ || Object.getPrototypeOf(Container)).apply(this, arguments)); } createClass(Container, [{ key: 'push', value: function push(child) { child.parent = this; this.nodes.push(child); return this; } /** * Iterates through the container’s immediate children, * calling `callback` for each child. * * Returning `false` in the callback will break iteration. * * This method only iterates through the container’s immediate children. * If you need to recursively iterate through all the container’s descendant * nodes, use {@link Container#walk}. * * Unlike the for `{}`-cycle or `Array#forEach` this iterator is safe * if you are mutating the array of child nodes during iteration. * PostCSS will adjust the current index to match the mutations. * * @param {childIterator} callback - iterator receives each node and index * * @return {false|undefined} returns `false` if iteration was broke * * @example * const root = postcss.parse('a { color: black; z-index: 1 }'); * const rule = root.first; * * for ( let decl of rule.nodes ) { * decl.cloneBefore({ prop: '-webkit-' + decl.prop }); * // Cycle will be infinite, because cloneBefore moves the current node * // to the next index * } * * rule.each(decl => { * decl.cloneBefore({ prop: '-webkit-' + decl.prop }); * // Will be executed only for color and z-index * }); */ }, { key: 'each', value: function each(callback) { if (!this.lastEach) this.lastEach = 0; if (!this.indexes) this.indexes = {}; this.lastEach += 1; var id = this.lastEach; this.indexes[id] = 0; if (!this.nodes) return undefined; var index = void 0, result = void 0; while (this.indexes[id] < this.nodes.length) { index = this.indexes[id]; result = callback(this.nodes[index], index); if (result === false) break; this.indexes[id] += 1; } delete this.indexes[id]; return result; } /** * Traverses the container’s descendant nodes, calling callback * for each node. * * Like container.each(), this method is safe to use * if you are mutating arrays during iteration. * * If you only need to iterate through the container’s immediate children, * use {@link Container#each}. * * @param {childIterator} callback - iterator receives each node and index * * @return {false|undefined} returns `false` if iteration was broke * * @example * root.walk(node => { * // Traverses all descendant nodes. * }); */ }, { key: 'walk', value: function walk(callback) { return this.each(function (child, i) { var result = callback(child, i); if (result !== false && child.walk) { result = child.walk(callback); } return result; }); } /** * Traverses the container’s descendant nodes, calling callback * for each declaration node. * * If you pass a filter, iteration will only happen over declarations * with matching properties. * * Like {@link Container#each}, this method is safe * to use if you are mutating arrays during iteration. * * @param {string|RegExp} [prop] - string or regular expression * to filter declarations by property name * @param {childIterator} callback - iterator receives each node and index * * @return {false|undefined} returns `false` if iteration was broke * * @example * root.walkDecls(decl => { * checkPropertySupport(decl.prop); * }); * * root.walkDecls('border-radius', decl => { * decl.remove(); * }); * * root.walkDecls(/^background/, decl => { * decl.value = takeFirstColorFromGradient(decl.value); * }); */ }, { key: 'walkDecls', value: function walkDecls(prop, callback) { if (!callback) { callback = prop; return this.walk(function (child, i) { if (child.type === 'decl') { return callback(child, i); } }); } else if (prop instanceof RegExp) { return this.walk(function (child, i) { if (child.type === 'decl' && prop.test(child.prop)) { return callback(child, i); } }); } else { return this.walk(function (child, i) { if (child.type === 'decl' && child.prop === prop) { return callback(child, i); } }); } } /** * Traverses the container’s descendant nodes, calling callback * for each rule node. * * If you pass a filter, iteration will only happen over rules * with matching selectors. * * Like {@link Container#each}, this method is safe * to use if you are mutating arrays during iteration. * * @param {string|RegExp} [selector] - string or regular expression * to filter rules by selector * @param {childIterator} callback - iterator receives each node and index * * @return {false|undefined} returns `false` if iteration was broke * * @example * const selectors = []; * root.walkRules(rule => { * selectors.push(rule.selector); * }); * console.log(`Your CSS uses ${selectors.length} selectors`); */ }, { key: 'walkRules', value: function walkRules(selector, callback) { if (!callback) { callback = selector; return this.walk(function (child, i) { if (child.type === 'rule') { return callback(child, i); } }); } else if (selector instanceof RegExp) { return this.walk(function (child, i) { if (child.type === 'rule' && selector.test(child.selector)) { return callback(child, i); } }); } else { return this.walk(function (child, i) { if (child.type === 'rule' && child.selector === selector) { return callback(child, i); } }); } } /** * Traverses the container’s descendant nodes, calling callback * for each at-rule node. * * If you pass a filter, iteration will only happen over at-rules * that have matching names. * * Like {@link Container#each}, this method is safe * to use if you are mutating arrays during iteration. * * @param {string|RegExp} [name] - string or regular expression * to filter at-rules by name * @param {childIterator} callback - iterator receives each node and index * * @return {false|undefined} returns `false` if iteration was broke * * @example * root.walkAtRules(rule => { * if ( isOld(rule.name) ) rule.remove(); * }); * * let first = false; * root.walkAtRules('charset', rule => { * if ( !first ) { * first = true; * } else { * rule.remove(); * } * }); */ }, { key: 'walkAtRules', value: function walkAtRules(name, callback) { if (!callback) { callback = name; return this.walk(function (child, i) { if (child.type === 'atrule') { return callback(child, i); } }); } else if (name instanceof RegExp) { return this.walk(function (child, i) { if (child.type === 'atrule' && name.test(child.name)) { return callback(child, i); } }); } else { return this.walk(function (child, i) { if (child.type === 'atrule' && child.name === name) { return callback(child, i); } }); } } /** * Traverses the container’s descendant nodes, calling callback * for each comment node. * * Like {@link Container#each}, this method is safe * to use if you are mutating arrays during iteration. * * @param {childIterator} callback - iterator receives each node and index * * @return {false|undefined} returns `false` if iteration was broke * * @example * root.walkComments(comment => { * comment.remove(); * }); */ }, { key: 'walkComments', value: function walkComments(callback) { return this.walk(function (child, i) { if (child.type === 'comment') { return callback(child, i); } }); } /** * Inserts new nodes to the start of the container. * * @param {...(Node|object|string|Node[])} children - new nodes * * @return {Node} this node for methods chain * * @example * const decl1 = postcss.decl({ prop: 'color', value: 'black' }); * const decl2 = postcss.decl({ prop: 'background-color', value: 'white' }); * rule.append(decl1, decl2); * * root.append({ name: 'charset', params: '"UTF-8"' }); // at-rule * root.append({ selector: 'a' }); // rule * rule.append({ prop: 'color', value: 'black' }); // declaration * rule.append({ text: 'Comment' }) // comment * * root.append('a {}'); * root.first.append('color: black; z-index: 1'); */ }, { key: 'append', value: function append() { var _this2 = this; for (var _len = arguments.length, children = Array(_len), _key = 0; _key < _len; _key++) { children[_key] = arguments[_key]; } children.forEach(function (child) { var nodes = _this2.normalize(child, _this2.last); nodes.forEach(function (node) { return _this2.nodes.push(node); }); }); return this; } /** * Inserts new nodes to the end of the container. * * @param {...(Node|object|string|Node[])} children - new nodes * * @return {Node} this node for methods chain * * @example * const decl1 = postcss.decl({ prop: 'color', value: 'black' }); * const decl2 = postcss.decl({ prop: 'background-color', value: 'white' }); * rule.prepend(decl1, decl2); * * root.append({ name: 'charset', params: '"UTF-8"' }); // at-rule * root.append({ selector: 'a' }); // rule * rule.append({ prop: 'color', value: 'black' }); // declaration * rule.append({ text: 'Comment' }) // comment * * root.append('a {}'); * root.first.append('color: black; z-index: 1'); */ }, { key: 'prepend', value: function prepend() { var _this3 = this; for (var _len2 = arguments.length, children = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { children[_key2] = arguments[_key2]; } children = children.reverse(); children.forEach(function (child) { var nodes = _this3.normalize(child, _this3.first, 'prepend').reverse(); nodes.forEach(function (node) { return _this3.nodes.unshift(node); }); for (var id in _this3.indexes) { _this3.indexes[id] = _this3.indexes[id] + nodes.length; } }); return this; } }, { key: 'cleanRaws', value: function cleanRaws(keepBetween) { get$1(Container.prototype.__proto__ || Object.getPrototypeOf(Container.prototype), 'cleanRaws', this).call(this, keepBetween); if (this.nodes) { this.nodes.forEach(function (node) { return node.cleanRaws(keepBetween); }); } } /** * Insert new node before old node within the container. * * @param {Node|number} exist - child or child’s index. * @param {Node|object|string|Node[]} add - new node * * @return {Node} this node for methods chain * * @example * rule.insertBefore(decl, decl.clone({ prop: '-webkit-' + decl.prop })); */ }, { key: 'insertBefore', value: function insertBefore(exist, add) { var _this4 = this; exist = this.index(exist); var type = exist === 0 ? 'prepend' : false; var nodes = this.normalize(add, this.nodes[exist], type).reverse(); nodes.forEach(function (node) { return _this4.nodes.splice(exist, 0, node); }); var index = void 0; for (var id in this.indexes) { index = this.indexes[id]; if (exist <= index) { this.indexes[id] = index + nodes.length; } } return this; } /** * Insert new node after old node within the container. * * @param {Node|number} exist - child or child’s index * @param {Node|object|string|Node[]} add - new node * * @return {Node} this node for methods chain */ }, { key: 'insertAfter', value: function insertAfter(exist, add) { var _this5 = this; exist = this.index(exist); var nodes = this.normalize(add, this.nodes[exist]).reverse(); nodes.forEach(function (node) { return _this5.nodes.splice(exist + 1, 0, node); }); var index = void 0; for (var id in this.indexes) { index = this.indexes[id]; if (exist < index) { this.indexes[id] = index + nodes.length; } } return this; } }, { key: 'remove', value: function remove(child) { if (typeof child !== 'undefined') { warnOnce('Container#remove is deprecated. ' + 'Use Container#removeChild'); this.removeChild(child); } else { get$1(Container.prototype.__proto__ || Object.getPrototypeOf(Container.prototype), 'remove', this).call(this); } return this; } /** * Removes node from the container and cleans the parent properties * from the node and its children. * * @param {Node|number} child - child or child’s index * * @return {Node} this node for methods chain * * @example * rule.nodes.length //=> 5 * rule.removeChild(decl); * rule.nodes.length //=> 4 * decl.parent //=> undefined */ }, { key: 'removeChild', value: function removeChild(child) { child = this.index(child); this.nodes[child].parent = undefined; this.nodes.splice(child, 1); var index = void 0; for (var id in this.indexes) { index = this.indexes[id]; if (index >= child) { this.indexes[id] = index - 1; } } return this; } /** * Removes all children from the container * and cleans their parent properties. * * @return {Node} this node for methods chain * * @example * rule.removeAll(); * rule.nodes.length //=> 0 */ }, { key: 'removeAll', value: function removeAll() { this.nodes.forEach(function (node) { return node.parent = undefined; }); this.nodes = []; return this; } /** * Passes all declaration values within the container that match pattern * through callback, replacing those values with the returned result * of callback. * * This method is useful if you are using a custom unit or function * and need to iterate through all values. * * @param {string|RegExp} pattern - replace pattern * @param {object} opts - options to speed up the search * @param {string|string[]} opts.props - an array of property names * @param {string} opts.fast - string that’s used * to narrow down values and speed up the regexp search * @param {function|string} callback - string to replace pattern * or callback that returns a new * value. * The callback will receive * the same arguments as those * passed to a function parameter * of `String#replace`. * * @return {Node} this node for methods chain * * @example * root.replaceValues(/\d+rem/, { fast: 'rem' }, string => { * return 15 * parseInt(string) + 'px'; * }); */ }, { key: 'replaceValues', value: function replaceValues(pattern, opts, callback) { if (!callback) { callback = opts; opts = {}; } this.walkDecls(function (decl) { if (opts.props && opts.props.indexOf(decl.prop) === -1) return; if (opts.fast && decl.value.indexOf(opts.fast) === -1) return; decl.value = decl.value.replace(pattern, callback); }); return this; } /** * Returns `true` if callback returns `true` * for all of the container’s children. * * @param {childCondition} condition - iterator returns true or false. * * @return {boolean} is every child pass condition * * @example * const noPrefixes = rule.every(i => i.prop[0] !== '-'); */ }, { key: 'every', value: function every(condition) { return this.nodes.every(condition); } /** * Returns `true` if callback returns `true` for (at least) one * of the container’s children. * * @param {childCondition} condition - iterator returns true or false. * * @return {boolean} is some child pass condition * * @example * const hasPrefix = rule.some(i => i.prop[0] === '-'); */ }, { key: 'some', value: function some(condition) { return this.nodes.some(condition); } /** * Returns a `child`’s index within the {@link Container#nodes} array. * * @param {Node} child - child of the current container. * * @return {number} child index * * @example * rule.index( rule.nodes[2] ) //=> 2 */ }, { key: 'index', value: function index(child) { if (typeof child === 'number') { return child; } else { return this.nodes.indexOf(child); } } /** * The container’s first child. * * @type {Node} * * @example * rule.first == rules.nodes[0]; */ }, { key: 'normalize', value: function normalize(nodes, sample) { var _this6 = this; if (typeof nodes === 'string') { nodes = cleanSource(parse(nodes).nodes); } else if (!Array.isArray(nodes)) { if (nodes.type === 'root') { nodes = nodes.nodes; } else if (nodes.type) { nodes = [nodes]; } else if (nodes.prop) { if (typeof nodes.value === 'undefined') { throw new Error('Value field is missed in node creation'); } else if (typeof nodes.value !== 'string') { nodes.value = String(nodes.value); } nodes = [new Declaration(nodes)]; } else if (nodes.selector) { nodes = [new Rule(nodes)]; } else if (nodes.name) { nodes = [new AtRule(nodes)]; } else if (nodes.text) { nodes = [new Comment(nodes)]; } else { throw new Error('Unknown node type in node creation'); } } var processed = nodes.map(function (i) { if (typeof i.raws === 'undefined') i = _this6.rebuild(i); if (i.parent) i = i.clone(); if (typeof i.raws.before === 'undefined') { if (sample && typeof sample.raws.before !== 'undefined') { i.raws.before = sample.raws.before.replace(/[^\s]/g, ''); } } i.parent = _this6; return i; }); return processed; } }, { key: 'rebuild', value: function rebuild(node, parent) { var _this7 = this; var fix = void 0; if (node.type === 'root') { fix = new Root(); } else if (node.type === 'atrule') { fix = new AtRule(); } else if (node.type === 'rule') { fix = new Rule(); } else if (node.type === 'decl') { fix = new Declaration(); } else if (node.type === 'comment') { fix = new Comment(); } for (var i in node) { if (i === 'nodes') { fix.nodes = node.nodes.map(function (j) { return _this7.rebuild(j, fix); }); } else if (i === 'parent' && parent) { fix.parent = parent; } else if (node.hasOwnProperty(i)) { fix[i] = node[i]; } } return fix; } }, { key: 'eachInside', value: function eachInside(callback) { warnOnce('Container#eachInside is deprecated. ' + 'Use Container#walk instead.'); return this.walk(callback); } }, { key: 'eachDecl', value: function eachDecl(prop, callback) { warnOnce('Container#eachDecl is deprecated. ' + 'Use Container#walkDecls instead.'); return this.walkDecls(prop, callback); } }, { key: 'eachRule', value: function eachRule(selector, callback) { warnOnce('Container#eachRule is deprecated. ' + 'Use Container#walkRules instead.'); return this.walkRules(selector, callback); } }, { key: 'eachAtRule', value: function eachAtRule(name, callback) { warnOnce('Container#eachAtRule is deprecated. ' + 'Use Container#walkAtRules instead.'); return this.walkAtRules(name, callback); } }, { key: 'eachComment', value: function eachComment(callback) { warnOnce('Container#eachComment is deprecated. ' + 'Use Container#walkComments instead.'); return this.walkComments(callback); } }, { key: 'first', get: function get() { if (!this.nodes) return undefined; return this.nodes[0]; } /** * The container’s last child. * * @type {Node} * * @example * rule.last == rule.nodes[rule.nodes.length - 1]; */ }, { key: 'last', get: function get() { if (!this.nodes) return undefined; return this.nodes[this.nodes.length - 1]; } }, { key: 'semicolon', get: function get() { warnOnce('Node#semicolon is deprecated. Use Node#raws.semicolon'); return this.raws.semicolon; }, set: function set(val) { warnOnce('Node#semicolon is deprecated. Use Node#raws.semicolon'); this.raws.semicolon = val; } }, { key: 'after', get: function get() { warnOnce('Node#after is deprecated. Use Node#raws.after'); return this.raws.after; }, set: function set(val) { warnOnce('Node#after is deprecated. Use Node#raws.after'); this.raws.after = val; } /** * @memberof Container# * @member {Node[]} nodes - an array containing the container’s children * * @example * const root = postcss.parse('a { color: black }'); * root.nodes.length //=> 1 * root.nodes[0].selector //=> 'a' * root.nodes[0].nodes[0].prop //=> 'color' */ }]); return Container; }(Node); /** * Represents an at-rule. * * If it’s followed in the CSS by a {} block, this node will have * a nodes property representing its children. * * @extends Container * * @example * const root = postcss.parse('@charset "UTF-8"; @media print {}'); * * const charset = root.first; * charset.type //=> 'atrule' * charset.nodes //=> undefined * * const media = root.last; * media.nodes //=> [] */ var AtRule = function (_Container) { inherits(AtRule, _Container); function AtRule(defaults$$1) { classCallCheck(this, AtRule); var _this = possibleConstructorReturn(this, (AtRule.__proto__ || Object.getPrototypeOf(AtRule)).call(this, defaults$$1)); _this.type = 'atrule'; return _this; } createClass(AtRule, [{ key: 'append', value: function append() { var _babelHelpers$get; if (!this.nodes) this.nodes = []; for (var _len = arguments.length, children = Array(_len), _key = 0; _key < _len; _key++) { children[_key] = arguments[_key]; } return (_babelHelpers$get = get$1(AtRule.prototype.__proto__ || Object.getPrototypeOf(AtRule.prototype), 'append', this)).call.apply(_babelHelpers$get, [this].concat(children)); } }, { key: 'prepend', value: function prepend() { var _babelHelpers$get2; if (!this.nodes) this.nodes = []; for (var _len2 = arguments.length, children = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { children[_key2] = arguments[_key2]; } return (_babelHelpers$get2 = get$1(AtRule.prototype.__proto__ || Object.getPrototypeOf(AtRule.prototype), 'prepend', this)).call.apply(_babelHelpers$get2, [this].concat(children)); } }, { key: 'afterName', get: function get() { warnOnce('AtRule#afterName was deprecated. Use AtRule#raws.afterName'); return this.raws.afterName; }, set: function set(val) { warnOnce('AtRule#afterName was deprecated. Use AtRule#raws.afterName'); this.raws.afterName = val; } }, { key: '_params', get: function get() { warnOnce('AtRule#_params was deprecated. Use AtRule#raws.params'); return this.raws.params; }, set: function set(val) { warnOnce('AtRule#_params was deprecated. Use AtRule#raws.params'); this.raws.params = val; } /** * @memberof AtRule# * @member {string} name - the at-rule’s name immediately follows the `@` * * @example * const root = postcss.parse('@media print {}'); * media.name //=> 'media' * const media = root.first; */ /** * @memberof AtRule# * @member {string} params - the at-rule’s parameters, the values * that follow the at-rule’s name but precede * any {} block * * @example * const root = postcss.parse('@media print, screen {}'); * const media = root.first; * media.params //=> 'print, screen' */ /** * @memberof AtRule# * @member {object} raws - Information to generate byte-to-byte equal * node string as it was in the origin input. * * Every parser saves its own properties, * but the default CSS parser uses: * * * `before`: the space symbols before the node. It also stores `*` * and `_` symbols before the declaration (IE hack). * * `after`: the space symbols after the last child of the node * to the end of the node. * * `between`: the symbols between the property and value * for declarations, selector and `{` for rules, or last parameter * and `{` for at-rules. * * `semicolon`: contains true if the last child has * an (optional) semicolon. * * `afterName`: the space between the at-rule name and its parameters. * * PostCSS cleans at-rule parameters from comments and extra spaces, * but it stores origin content in raws properties. * As such, if you don’t change a declaration’s value, * PostCSS will use the raw value with comments. * * @example * const root = postcss.parse(' @media\nprint {\n}') * root.first.first.raws //=> { before: ' ', * // between: ' ', * // afterName: '\n', * // after: '\n' } */ }]); return AtRule; }(Container); /** * Contains helpers for safely splitting lists of CSS values, * preserving parentheses and quotes. * * @example * const list = postcss.list; * * @namespace list */ var list = { split: function split(string, separators, last) { var array = []; var current = ''; var split = false; var func = 0; var quote = false; var escape = false; for (var i = 0; i < string.length; i++) { var letter = string[i]; if (quote) { if (escape) { escape = false; } else if (letter === '\\') { escape = true; } else if (letter === quote) { quote = false; } } else if (letter === '"' || letter === '\'') { quote = letter; } else if (letter === '(') { func += 1; } else if (letter === ')') { if (func > 0) func -= 1; } else if (func === 0) { if (separators.indexOf(letter) !== -1) split = true; } if (split) { if (current !== '') array.push(current.trim()); current = ''; split = false; } else { current += letter; } } if (last || current !== '') array.push(current.trim()); return array; }, /** * Safely splits space-separated values (such as those for `background`, * `border-radius`, and other shorthand properties). * * @param {string} string - space-separated values * * @return {string[]} splitted values * * @example * postcss.list.space('1px calc(10% + 1px)') //=> ['1px', 'calc(10% + 1px)'] */ space: function space(string) { var spaces = [' ', '\n', '\t']; return list.split(string, spaces); }, /** * Safely splits comma-separated values (such as those for `transition-*` * and `background` properties). * * @param {string} string - comma-separated values * * @return {string[]} splitted values * * @example * postcss.list.comma('black, linear-gradient(white, black)') * //=> ['black', 'linear-gradient(white, black)'] */ comma: function comma(string) { var comma = ','; return list.split(string, [comma], true); } }; /** * Represents a CSS rule: a selector followed by a declaration block. * * @extends Container * * @example * const root = postcss.parse('a{}'); * const rule = root.first; * rule.type //=> 'rule' * rule.toString() //=> 'a{}' */ var Rule = function (_Container) { inherits(Rule, _Container); function Rule(defaults$$1) { classCallCheck(this, Rule); var _this = possibleConstructorReturn(this, (Rule.__proto__ || Object.getPrototypeOf(Rule)).call(this, defaults$$1)); _this.type = 'rule'; if (!_this.nodes) _this.nodes = []; return _this; } /** * An array containing the rule’s individual selectors. * Groups of selectors are split at commas. * * @type {string[]} * * @example * const root = postcss.parse('a, b { }'); * const rule = root.first; * * rule.selector //=> 'a, b' * rule.selectors //=> ['a', 'b'] * * rule.selectors = ['a', 'strong']; * rule.selector //=> 'a, strong' */ createClass(Rule, [{ key: 'selectors', get: function get() { return list.comma(this.selector); }, set: function set(values) { var match = this.selector ? this.selector.match(/,\s*/) : null; var sep = match ? match[0] : ',' + this.raw('between', 'beforeOpen'); this.selector = values.join(sep); } }, { key: '_selector', get: function get() { warnOnce('Rule#_selector is deprecated. Use Rule#raws.selector'); return this.raws.selector; }, set: function set(val) { warnOnce('Rule#_selector is deprecated. Use Rule#raws.selector'); this.raws.selector = val; } /** * @memberof Rule# * @member {string} selector - the rule’s full selector represented * as a string * * @example * const root = postcss.parse('a, b { }'); * const rule = root.first; * rule.selector //=> 'a, b' */ /** * @memberof Rule# * @member {object} raws - Information to generate byte-to-byte equal * node string as it was in the origin input. * * Every parser saves its own properties, * but the default CSS parser uses: * * * `before`: the space symbols before the node. It also stores `*` * and `_` symbols before the declaration (IE hack). * * `after`: the space symbols after the last child of the node * to the end of the node. * * `between`: the symbols between the property and value * for declarations, selector and `{` for rules, or last parameter * and `{` for at-rules. * * `semicolon`: contains true if the last child has * an (optional) semicolon. * * PostCSS cleans selectors from comments and extra spaces, * but it stores origin content in raws properties. * As such, if you don’t change a declaration’s value, * PostCSS will use the raw value with comments. * * @example * const root = postcss.parse('a {\n color:black\n}') * root.first.first.raws //=> { before: '', between: ' ', after: '\n' } */ }]); return Rule; }(Container); /** * Represents a plugin’s warning. It can be created using {@link Node#warn}. * * @example * if ( decl.important ) { * decl.warn(result, 'Avoid !important', { word: '!important' }); * } */ var Warning = function () { /** * @param {string} text - warning message * @param {Object} [opts] - warning options * @param {Node} opts.node - CSS node that caused the warning * @param {string} opts.word - word in CSS source that caused the warning * @param {number} opts.index - index in CSS node string that caused * the warning * @param {string} opts.plugin - name of the plugin that created * this warning. {@link Result#warn} fills * this property automatically. */ function Warning(text) { var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; classCallCheck(this, Warning); /** * @member {string} - Type to filter warnings from * {@link Result#messages}. Always equal * to `"warning"`. * * @example * const nonWarning = result.messages.filter(i => i.type !== 'warning') */ this.type = 'warning'; /** * @member {string} - The warning message. * * @example * warning.text //=> 'Try to avoid !important' */ this.text = text; if (opts.node && opts.node.source) { var pos = opts.node.positionBy(opts); /** * @member {number} - Line in the input file * with this warning’s source * * @example * warning.line //=> 5 */ this.line = pos.line; /** * @member {number} - Column in the input file * with this warning’s source. * * @example * warning.column //=> 6 */ this.column = pos.column; } for (var opt in opts) { this[opt] = opts[opt]; } } /** * Returns a warning position and message. * * @example * warning.toString() //=> 'postcss-lint:a.css:10:14: Avoid !important' * * @return {string} warning position and message */ createClass(Warning, [{ key: 'toString', value: function toString() { if (this.node) { return this.node.error(this.text, { plugin: this.plugin, index: this.index, word: this.word }).message; } else if (this.plugin) { return this.plugin + ': ' + this.text; } else { return this.text; } } /** * @memberof Warning# * @member {string} plugin - The name of the plugin that created * it will fill this property automatically. * this warning. When you call {@link Node#warn} * * @example * warning.plugin //=> 'postcss-important' */ /** * @memberof Warning# * @member {Node} node - Contains the CSS node that caused the warning. * * @example * warning.node.toString() //=> 'color: white !important' */ }]); return Warning; }(); /** * @typedef {object} Message * @property {string} type - message type * @property {string} plugin - source PostCSS plugin name */ /** * Provides the result of the PostCSS transformations. * * A Result instance is returned by {@link LazyResult#then} * or {@link Root#toResult} methods. * * @example * postcss([cssnext]).process(css).then(function (result) { * console.log(result.css); * }); * * @example * var result2 = postcss.parse(css).toResult(); */ var Result = function () { /** * @param {Processor} processor - processor used for this transformation. * @param {Root} root - Root node after all transformations. * @param {processOptions} opts - options from the {@link Processor#process} * or {@link Root#toResult} */ function Result(processor, root, opts) { classCallCheck(this, Result); /** * @member {Processor} - The Processor instance used * for this transformation. * * @example * for ( let plugin of result.processor.plugins) { * if ( plugin.postcssPlugin === 'postcss-bad' ) { * throw 'postcss-good is incompatible with postcss-bad'; * } * }); */ this.processor = processor; /** * @member {Message[]} - Contains messages from plugins * (e.g., warnings or custom messages). * Each message should have type * and plugin properties. * * @example * postcss.plugin('postcss-min-browser', () => { * return (root, result) => { * var browsers = detectMinBrowsersByCanIUse(root); * result.messages.push({ * type: 'min-browser', * plugin: 'postcss-min-browser', * browsers: browsers * }); * }; * }); */ this.messages = []; /** * @member {Root} - Root node after all transformations. * * @example * root.toResult().root == root; */ this.root = root; /** * @member {processOptions} - Options from the {@link Processor#process} * or {@link Root#toResult} call * that produced this Result instance. * * @example * root.toResult(opts).opts == opts; */ this.opts = opts; /** * @member {string} - A CSS string representing of {@link Result#root}. * * @example * postcss.parse('a{}').toResult().css //=> "a{}" */ this.css = undefined; /** * @member {SourceMapGenerator} - An instance of `SourceMapGenerator` * class from the `source-map` library, * representing changes * to the {@link Result#root} instance. * * @example * result.map.toJSON() //=> { version: 3, file: 'a.css', … } * * @example * if ( result.map ) { * fs.writeFileSync(result.opts.to + '.map', result.map.toString()); * } */ this.map = undefined; } /** * Returns for @{link Result#css} content. * * @example * result + '' === result.css * * @return {string} string representing of {@link Result#root} */ createClass(Result, [{ key: 'toString', value: function toString() { return this.css; } /** * Creates an instance of {@link Warning} and adds it * to {@link Result#messages}. * * @param {string} text - warning message * @param {Object} [opts] - warning options * @param {Node} opts.node - CSS node that caused the warning * @param {string} opts.word - word in CSS source that caused the warning * @param {number} opts.index - index in CSS node string that caused * the warning * @param {string} opts.plugin - name of the plugin that created * this warning. {@link Result#warn} fills * this property automatically. * * @return {Warning} created warning */ }, { key: 'warn', value: function warn(text) { var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; if (!opts.plugin) { if (this.lastPlugin && this.lastPlugin.postcssPlugin) { opts.plugin = this.lastPlugin.postcssPlugin; } } var warning = new Warning(text, opts); this.messages.push(warning); return warning; } /** * Returns warnings from plugins. Filters {@link Warning} instances * from {@link Result#messages}. * * @example * result.warnings().forEach(warn => { * console.warn(warn.toString()); * }); * * @return {Warning[]} warnings from plugins */ }, { key: 'warnings', value: function warnings() { return this.messages.filter(function (i) { return i.type === 'warning'; }); } /** * An alias for the {@link Result#css} property. * Use it with syntaxes that generate non-CSS output. * @type {string} * * @example * result.css === result.content; */ }, { key: 'content', get: function get() { return this.css; } }]); return Result; }(); function isPromise(obj) { return (typeof obj === 'undefined' ? 'undefined' : _typeof(obj)) === 'object' && typeof obj.then === 'function'; } /** * @callback onFulfilled * @param {Result} result */ /** * @callback onRejected * @param {Error} error */ /** * A Promise proxy for the result of PostCSS transformations. * * A `LazyResult` instance is returned by {@link Processor#process}. * * @example * const lazy = postcss([cssnext]).process(css); */ var LazyResult = function () { function LazyResult(processor, css, opts) { classCallCheck(this, LazyResult); this.stringified = false; this.processed = false; var root = void 0; if ((typeof css === 'undefined' ? 'undefined' : _typeof(css)) === 'object' && css.type === 'root') { root = css; } else if (css instanceof LazyResult || css instanceof Result) { root = css.root; if (css.map) { if (typeof opts.map === 'undefined') opts.map = {}; if (!opts.map.inline) opts.map.inline = false; opts.map.prev = css.map; } } else { var parser = parse; if (opts.syntax) parser = opts.syntax.parse; if (opts.parser) parser = opts.parser; if (parser.parse) parser = parser.parse; try { root = parser(css, opts); } catch (error) { this.error = error; } } this.result = new Result(processor, root, opts); } /** * Returns a {@link Processor} instance, which will be used * for CSS transformations. * @type {Processor} */ createClass(LazyResult, [{ key: 'warnings', /** * Processes input CSS through synchronous plugins * and calls {@link Result#warnings()}. * * @return {Warning[]} warnings from plugins */ value: function warnings() { return this.sync().warnings(); } /** * Alias for the {@link LazyResult#css} property. * * @example * lazy + '' === lazy.css; * * @return {string} output CSS */ }, { key: 'toString', value: function toString() { return this.css; } /** * Processes input CSS through synchronous and asynchronous plugins * and calls `onFulfilled` with a Result instance. If a plugin throws * an error, the `onRejected` callback will be executed. * * It implements standard Promise API. * * @param {onFulfilled} onFulfilled - callback will be executed * when all plugins will finish work * @param {onRejected} onRejected - callback will be execited on any error * * @return {Promise} Promise API to make queue * * @example * postcss([cssnext]).process(css).then(result => { * console.log(result.css); * }); */ }, { key: 'then', value: function then(onFulfilled, onRejected) { return this.async().then(onFulfilled, onRejected); } /** * Processes input CSS through synchronous and asynchronous plugins * and calls onRejected for each error thrown in any plugin. * * It implements standard Promise API. * * @param {onRejected} onRejected - callback will be execited on any error * * @return {Promise} Promise API to make queue * * @example * postcss([cssnext]).process(css).then(result => { * console.log(result.css); * }).catch(error => { * console.error(error); * }); */ }, { key: 'catch', value: function _catch(onRejected) { return this.async().catch(onRejected); } }, { key: 'handleError', value: function handleError(error, plugin) { try { this.error = error; if (error.name === 'CssSyntaxError' && !error.plugin) { error.plugin = plugin.postcssPlugin; error.setMessage(); } else if (plugin.postcssVersion) { var pluginName = plugin.postcssPlugin; var pluginVer = plugin.postcssVersion; var runtimeVer = this.result.processor.version; var a = pluginVer.split('.'); var b = runtimeVer.split('.'); if (a[0] !== b[0] || parseInt(a[1]) > parseInt(b[1])) { warnOnce('Your current PostCSS version ' + 'is ' + runtimeVer + ', but ' + pluginName + ' ' + 'uses ' + pluginVer + '. Perhaps this is ' + 'the source of the error below.'); } } } catch (err) { if (console && console.error) console.error(err); } } }, { key: 'asyncTick', value: function asyncTick(resolve, reject) { var _this = this; if (this.plugin >= this.processor.plugins.length) { this.processed = true; return resolve(); } try { (function () { var plugin = _this.processor.plugins[_this.plugin]; var promise = _this.run(plugin); _this.plugin += 1; if (isPromise(promise)) { promise.then(function () { _this.asyncTick(resolve, reject); }).catch(function (error) { _this.handleError(error, plugin); _this.processed = true; reject(error); }); } else { _this.asyncTick(resolve, reject); } })(); } catch (error) { this.processed = true; reject(error); } } }, { key: 'async', value: function async() { var _this2 = this; if (this.processed) { return new Promise(function (resolve, reject) { if (_this2.error) { reject(_this2.error); } else { resolve(_this2.stringify()); } }); } if (this.processing) { return this.processing; } this.processing = new Promise(function (resolve, reject) { if (_this2.error) return reject(_this2.error); _this2.plugin = 0; _this2.asyncTick(resolve, reject); }).then(function () { _this2.processed = true; return _this2.stringify(); }); return this.processing; } }, { key: 'sync', value: function sync() { var _this3 = this; if (this.processed) return this.result; this.processed = true; if (this.processing) { throw new Error('Use process(css).then(cb) to work with async plugins'); } if (this.error) throw this.error; this.result.processor.plugins.forEach(function (plugin) { var promise = _this3.run(plugin); if (isPromise(promise)) { throw new Error('Use process(css).then(cb) to work with async plugins'); } }); return this.result; } }, { key: 'run', value: function run(plugin) { this.result.lastPlugin = plugin; try { return plugin(this.result.root, this.result); } catch (error) { this.handleError(error, plugin); throw error; } } }, { key: 'stringify', value: function stringify() { if (this.stringified) return this.result; this.stringified = true; this.sync(); var opts = this.result.opts; var str = stringify$1; if (opts.syntax) str = opts.syntax.stringify; if (opts.stringifier) str = opts.stringifier; if (str.stringify) str = str.stringify; var result = ''; str(this.root, function (i) { result += i; }); this.result.css = result; return this.result; } }, { key: 'processor', get: function get() { return this.result.processor; } /** * Options from the {@link Processor#process} call. * @type {processOptions} */ }, { key: 'opts', get: function get() { return this.result.opts; } /** * Processes input CSS through synchronous plugins, converts `Root` * to a CSS string and returns {@link Result#css}. * * This property will only work with synchronous plugins. * If the processor contains any asynchronous plugins * it will throw an error. This is why this method is only * for debug purpose, you should always use {@link LazyResult#then}. * * @type {string} * @see Result#css */ }, { key: 'css', get: function get() { return this.stringify().css; } /** * An alias for the `css` property. Use it with syntaxes * that generate non-CSS output. * * This property will only work with synchronous plugins. * If the processor contains any asynchronous plugins * it will throw an error. This is why this method is only * for debug purpose, you should always use {@link LazyResult#then}. * * @type {string} * @see Result#content */ }, { key: 'content', get: function get() { return this.stringify().content; } /** * Processes input CSS through synchronous plugins * and returns {@link Result#map}. * * This property will only work with synchronous plugins. * If the processor contains any asynchronous plugins * it will throw an error. This is why this method is only * for debug purpose, you should always use {@link LazyResult#then}. * * @type {SourceMapGenerator} * @see Result#map */ }, { key: 'map', get: function get() { return this.stringify().map; } /** * Processes input CSS through synchronous plugins * and returns {@link Result#root}. * * This property will only work with synchronous plugins. If the processor * contains any asynchronous plugins it will throw an error. * * This is why this method is only for debug purpose, * you should always use {@link LazyResult#then}. * * @type {Root} * @see Result#root */ }, { key: 'root', get: function get() { return this.sync().root; } /** * Processes input CSS through synchronous plugins * and returns {@link Result#messages}. * * This property will only work with synchronous plugins. If the processor * contains any asynchronous plugins it will throw an error. * * This is why this method is only for debug purpose, * you should always use {@link LazyResult#then}. * * @type {Message[]} * @see Result#messages */ }, { key: 'messages', get: function get() { return this.sync().messages; } }]); return LazyResult; }(); /** * @callback builder * @param {string} part - part of generated CSS connected to this node * @param {Node} node - AST node * @param {"start"|"end"} [type] - node’s part type */ /** * @callback parser * * @param {string|toString} css - string with input CSS or any object * with toString() method, like a Buffer * @param {processOptions} [opts] - options with only `from` and `map` keys * * @return {Root} PostCSS AST */ /** * @callback stringifier * * @param {Node} node - start node for stringifing. Usually {@link Root}. * @param {builder} builder - function to concatenate CSS from node’s parts * or generate string and source map * * @return {void} */ /** * @typedef {object} syntax * @property {parser} parse - function to generate AST by string * @property {stringifier} stringify - function to generate string by AST */ /** * @typedef {object} toString * @property {function} toString */ /** * @callback pluginFunction * @param {Root} root - parsed input CSS * @param {Result} result - result to set warnings or check other plugins */ /** * @typedef {object} Plugin * @property {function} postcss - PostCSS plugin function */ /** * @typedef {object} processOptions * @property {string} from - the path of the CSS source file. * You should always set `from`, * because it is used in source map * generation and syntax error messages. * @property {string} to - the path where you’ll put the output * CSS file. You should always set `to` * to generate correct source maps. * @property {parser} parser - function to generate AST by string * @property {stringifier} stringifier - class to generate string by AST * @property {syntax} syntax - object with `parse` and `stringify` * @property {object} map - source map options * @property {boolean} map.inline - does source map should * be embedded in the output * CSS as a base64-encoded * comment * @property {string|object|false|function} map.prev - source map content * from a previous * processing step * (for example, Sass). * PostCSS will try to find * previous map * automatically, so you * could disable it by * `false` value. * @property {boolean} map.sourcesContent - does PostCSS should set * the origin content to map * @property {string|false} map.annotation - does PostCSS should set * annotation comment to map * @property {string} map.from - override `from` in map’s * `sources` */ /** * Contains plugins to process CSS. Create one `Processor` instance, * initialize its plugins, and then use that instance on numerous CSS files. * * @example * const processor = postcss([autoprefixer, precss]); * processor.process(css1).then(result => console.log(result.css)); * processor.process(css2).then(result => console.log(result.css)); */ var Processor = function () { /** * @param {Array.<Plugin|pluginFunction>|Processor} plugins - PostCSS * plugins. See {@link Processor#use} for plugin format. */ function Processor() { var plugins = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : []; classCallCheck(this, Processor); /** * @member {string} - Current PostCSS version. * * @example * if ( result.processor.version.split('.')[0] !== '5' ) { * throw new Error('This plugin works only with PostCSS 5'); * } */ this.version = '5.2.0'; /** * @member {pluginFunction[]} - Plugins added to this processor. * * @example * const processor = postcss([autoprefixer, precss]); * processor.plugins.length //=> 2 */ this.plugins = this.normalize(plugins); } /** * Adds a plugin to be used as a CSS processor. * * PostCSS plugin can be in 4 formats: * * A plugin created by {@link postcss.plugin} method. * * A function. PostCSS will pass the function a @{link Root} * as the first argument and current {@link Result} instance * as the second. * * An object with a `postcss` method. PostCSS will use that method * as described in #2. * * Another {@link Processor} instance. PostCSS will copy plugins * from that instance into this one. * * Plugins can also be added by passing them as arguments when creating * a `postcss` instance (see [`postcss(plugins)`]). * * Asynchronous plugins should return a `Promise` instance. * * @param {Plugin|pluginFunction|Processor} plugin - PostCSS plugin * or {@link Processor} * with plugins * * @example * const processor = postcss() * .use(autoprefixer) * .use(precss); * * @return {Processes} current processor to make methods chain */ createClass(Processor, [{ key: 'use', value: function use(plugin) { this.plugins = this.plugins.concat(this.normalize([plugin])); return this; } /** * Parses source CSS and returns a {@link LazyResult} Promise proxy. * Because some plugins can be asynchronous it doesn’t make * any transformations. Transformations will be applied * in the {@link LazyResult} methods. * * @param {string|toString|Result} css - String with input CSS or * any object with a `toString()` * method, like a Buffer. * Optionally, send a {@link Result} * instance and the processor will * take the {@link Root} from it. * @param {processOptions} [opts] - options * * @return {LazyResult} Promise proxy * * @example * processor.process(css, { from: 'a.css', to: 'a.out.css' }) * .then(result => { * console.log(result.css); * }); */ }, { key: 'process', value: function process(css) { var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; return new LazyResult(this, css, opts); } }, { key: 'normalize', value: function normalize(plugins) { var normalized = []; plugins.forEach(function (i) { if (i.postcss) i = i.postcss; if ((typeof i === 'undefined' ? 'undefined' : _typeof(i)) === 'object' && Array.isArray(i.plugins)) { normalized = normalized.concat(i.plugins); } else if (typeof i === 'function') { normalized.push(i); } else { throw new Error(i + ' is not a PostCSS plugin'); } }); return normalized; } }]); return Processor; }(); /** * Represents a CSS file and contains all its parsed nodes. * * @extends Container * * @example * const root = postcss.parse('a{color:black} b{z-index:2}'); * root.type //=> 'root' * root.nodes.length //=> 2 */ var Root = function (_Container) { inherits(Root, _Container); function Root(defaults$$1) { classCallCheck(this, Root); var _this = possibleConstructorReturn(this, (Root.__proto__ || Object.getPrototypeOf(Root)).call(this, defaults$$1)); _this.type = 'root'; if (!_this.nodes) _this.nodes = []; return _this; } createClass(Root, [{ key: 'removeChild', value: function removeChild(child) { child = this.index(child); if (child === 0 && this.nodes.length > 1) { this.nodes[1].raws.before = this.nodes[child].raws.before; } return get$1(Root.prototype.__proto__ || Object.getPrototypeOf(Root.prototype), 'removeChild', this).call(this, child); } }, { key: 'normalize', value: function normalize(child, sample, type) { var nodes = get$1(Root.prototype.__proto__ || Object.getPrototypeOf(Root.prototype), 'normalize', this).call(this, child); if (sample) { if (type === 'prepend') { if (this.nodes.length > 1) { sample.raws.before = this.nodes[1].raws.before; } else { delete sample.raws.before; } } else if (this.first !== sample) { nodes.forEach(function (node) { node.raws.before = sample.raws.before; }); } } return nodes; } /** * Returns a {@link Result} instance representing the root’s CSS. * * @param {processOptions} [opts] - options with only `to` and `map` keys * * @return {Result} result with current root’s CSS * * @example * const root1 = postcss.parse(css1, { from: 'a.css' }); * const root2 = postcss.parse(css2, { from: 'b.css' }); * root1.append(root2); * const result = root1.toResult({ to: 'all.css', map: true }); */ }, { key: 'toResult', value: function toResult() { var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; var lazy = new LazyResult(new Processor(), this, opts); return lazy.stringify(); } }, { key: 'remove', value: function remove(child) { warnOnce('Root#remove is deprecated. Use Root#removeChild'); this.removeChild(child); } }, { key: 'prevMap', value: function prevMap() { warnOnce('Root#prevMap is deprecated. Use Root#source.input.map'); return this.source.input.map; } /** * @memberof Root# * @member {object} raws - Information to generate byte-to-byte equal * node string as it was in the origin input. * * Every parser saves its own properties, * but the default CSS parser uses: * * * `after`: the space symbols after the last child to the end of file. * * `semicolon`: is the last child has an (optional) semicolon. * * @example * postcss.parse('a {}\n').raws //=> { after: '\n' } * postcss.parse('a {}').raws //=> { after: '' } */ }]); return Root; }(Container); // import PreviousMap from './previous-map'; var sequence = 0; /** * @typedef {object} filePosition * @property {string} file - path to file * @property {number} line - source line in file * @property {number} column - source column in file */ /** * Represents the source CSS. * * @example * const root = postcss.parse(css, { from: file }); * const input = root.source.input; */ var Input = function () { /** * @param {string} css - input CSS source * @param {object} [opts] - {@link Processor#process} options */ function Input(css) { var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; classCallCheck(this, Input); /** * @member {string} - input CSS source * * @example * const input = postcss.parse('a{}', { from: file }).input; * input.css //=> "a{}"; */ this.css = css.toString(); if (this.css[0] === '\uFEFF' || this.css[0] === '\uFFFE') { this.css = this.css.slice(1); } if (opts.from) { if (/^\w+:\/\//.test(opts.from)) { /** * @member {string} - The absolute path to the CSS source file * defined with the `from` option. * * @example * const root = postcss.parse(css, { from: 'a.css' }); * root.source.input.file //=> '/home/ai/a.css' */ this.file = opts.from; } else { this.file = path.resolve(opts.from); } } /* let map = new PreviousMap(this.css, opts); if ( map.text ) { /!** * @member {PreviousMap} - The input source map passed from * a compilation step before PostCSS * (for example, from Sass compiler). * * @example * root.source.input.map.consumer().sources //=> ['a.sass'] *!/ this.map = map; let file = map.consumer().file; if ( !this.file && file ) this.file = this.mapResolve(file); } */ if (!this.file) { sequence += 1; /** * @member {string} - The unique ID of the CSS source. It will be * created if `from` option is not provided * (because PostCSS does not know the file path). * * @example * const root = postcss.parse(css); * root.source.input.file //=> undefined * root.source.input.id //=> "<input css 1>" */ this.id = '<input css ' + sequence + '>'; } if (this.map) this.map.file = this.from; } createClass(Input, [{ key: 'error', value: function error(message, line, column) { var opts = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {}; var result = void 0; var origin = this.origin(line, column); if (origin) { result = new CssSyntaxError(message, origin.line, origin.column, origin.source, origin.file, opts.plugin); } else { result = new CssSyntaxError(message, line, column, this.css, this.file, opts.plugin); } result.input = { line: line, column: column, source: this.css }; if (this.file) result.input.file = this.file; return result; } /** * Reads the input source map and returns a symbol position * in the input source (e.g., in a Sass file that was compiled * to CSS before being passed to PostCSS). * * @param {number} line - line in input CSS * @param {number} column - column in input CSS * * @return {filePosition} position in input source * * @example * root.source.input.origin(1, 1) //=> { file: 'a.css', line: 3, column: 1 } */ }, { key: 'origin', value: function origin(line, column) { if (!this.map) return false; var consumer = this.map.consumer(); var from = consumer.originalPositionFor({ line: line, column: column }); if (!from.source) return false; var result = { file: this.mapResolve(from.source), line: from.line, column: from.column }; var source = consumer.sourceContentFor(from.source); if (source) result.source = source; return result; } }, { key: 'mapResolve', value: function mapResolve(file) { if (/^\w+:\/\//.test(file)) { return file; } else { return path.resolve(this.map.consumer().sourceRoot || '.', file); } } /** * The CSS source identifier. Contains {@link Input#file} if the user * set the `from` option, or {@link Input#id} if they did not. * @type {string} * * @example * const root = postcss.parse(css, { from: 'a.css' }); * root.source.input.from //=> "/home/ai/a.css" * * const root = postcss.parse(css); * root.source.input.from //=> "<input css 1>" */ }, { key: 'from', get: function get() { return this.file || this.id; } }]); return Input; }(); var SafeParser = function (_Parser) { inherits(SafeParser, _Parser); function SafeParser() { classCallCheck(this, SafeParser); return possibleConstructorReturn(this, (SafeParser.__proto__ || Object.getPrototypeOf(SafeParser)).apply(this, arguments)); } createClass(SafeParser, [{ key: 'tokenize', value: function tokenize() { this.tokens = tokenize$1(this.input, { ignoreErrors: true }); } }, { key: 'comment', value: function comment(token) { var node = new Comment(); this.init(node, token[2], token[3]); node.source.end = { line: token[4], column: token[5] }; var text = token[1].slice(2); if (text.slice(-2) === '*/') text = text.slice(0, -2); if (/^\s*$/.test(text)) { node.text = ''; node.raws.left = text; node.raws.right = ''; } else { var match = text.match(/^(\s*)([^]*[^\s])(\s*)$/); node.text = match[2]; node.raws.left = match[1]; node.raws.right = match[3]; } } }, { key: 'unclosedBracket', value: function unclosedBracket() {} }, { key: 'unknownWord', value: function unknownWord(start) { var buffer = this.tokens.slice(start, this.pos + 1); this.spaces += buffer.map(function (i) { return i[1]; }).join(''); } }, { key: 'unexpectedClose', value: function unexpectedClose() { this.current.raws.after += '}'; } }, { key: 'doubleColon', value: function doubleColon() {} }, { key: 'unnamedAtrule', value: function unnamedAtrule(node) { node.name = ''; } }, { key: 'precheckMissedSemicolon', value: function precheckMissedSemicolon(tokens) { var colon = this.colon(tokens); if (colon === false) return; var split = void 0; for (split = colon - 1; split >= 0; split--) { if (tokens[split][0] === 'word') break; } for (split -= 1; split >= 0; split--) { if (tokens[split][0] !== 'space') { split += 1; break; } } var other = tokens.splice(split, tokens.length - split); this.decl(other); } }, { key: 'checkMissedSemicolon', value: function checkMissedSemicolon() {} }, { key: 'endFile', value: function endFile() { if (this.current.nodes && this.current.nodes.length) { this.current.raws.semicolon = this.semicolon; } this.current.raws.after = (this.current.raws.after || '') + this.spaces; while (this.current.parent) { this.current = this.current.parent; this.current.raws.after = ''; } } }]); return SafeParser; }(Parser); function safeParse(css, opts) { var input = new Input(css, opts); var parser = new SafeParser(input); parser.tokenize(); parser.loop(); return parser.root; } function selectors(parent, node) { var result = []; parent.selectors.forEach(function (i) { node.selectors.forEach(function (j) { if (j.indexOf('&') === -1) { result.push(i + ' ' + j); } else { result.push(j.replace(/&/g, i)); } }); }); return result; } function pickComment(comment, after) { if (comment && comment.type === 'comment') { return comment.moveAfter(after); } else { return after; } } function atruleChilds(rule, atrule) { var children = []; atrule.each(function (child) { if (child.type === 'comment') { children.push(child); } if (child.type === 'decl') { children.push(child); } else if (child.type === 'rule') { child.selectors = selectors(rule, child); } else if (child.type === 'atrule') { atruleChilds(rule, child); } }); if (children.length) { var clone = rule.clone({ nodes: [] }); for (var i = 0; i < children.length; i++) { children[i].moveTo(clone); }atrule.prepend(clone); } } function processRule(rule, bubble) { var unwrapped = false; var after = rule; rule.each(function (child) { if (child.type === 'rule') { unwrapped = true; child.selectors = selectors(rule, child); after = pickComment(child.prev(), after); after = child.moveAfter(after); } else if (child.type === 'atrule') { if (bubble.indexOf(child.name) !== -1) { unwrapped = true; atruleChilds(rule, child); after = pickComment(child.prev(), after); after = child.moveAfter(after); } } }); if (unwrapped) { rule.raws.semicolon = true; if (rule.nodes.length === 0) rule.remove(); } } var bubble = ['media', 'supports', 'document']; var process$2 = function process$2(node) { node.each(function (child) { if (child.type === 'rule') { processRule(child, bubble); } else if (child.type === 'atrule') { process$2(child); } }); }; /* high performance StyleSheet for css-in-js systems - uses multiple style tags behind the scenes for millions of rules - uses `insertRule` for appending in production for *much* faster performance - 'polyfills' on server side // usage import StyleSheet from 'glamor/lib/sheet' let styleSheet = new StyleSheet() styleSheet.inject() - 'injects' the stylesheet into the page (or into memory if on server) styleSheet.insert('#box { border: 1px solid red; }') - appends a css rule into the stylesheet styleSheet.flush() - empties the stylesheet of all its contents */ function last(arr) { return arr[arr.length - 1]; } function sheetForTag(tag) { for (var i = 0; i < document.styleSheets.length; i++) { if (document.styleSheets[i].ownerNode === tag) { return document.styleSheets[i]; } } } var isBrowser = typeof document !== 'undefined'; var isDev = function (x) { return x === 'development' || !x; }("development"); var isTest = "development" === 'test'; var oldIE = function () { if (isBrowser) { var div = document.createElement('div'); div.innerHTML = '<!--[if lt IE 10]><i></i><![endif]-->'; return div.getElementsByTagName('i').length === 1; } }(); function makeStyleTag() { var tag = document.createElement('style'); tag.type = 'text/css'; tag.appendChild(document.createTextNode('')); (document.head || document.getElementsByTagName('head')[0]).appendChild(tag); return tag; } var StyleSheet = function () { function StyleSheet() { var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; var _ref$speedy = _ref.speedy; var speedy = _ref$speedy === undefined ? !isDev && !isTest : _ref$speedy; var _ref$maxLength = _ref.maxLength; var maxLength = _ref$maxLength === undefined ? isBrowser && oldIE ? 4000 : 65000 : _ref$maxLength; classCallCheck(this, StyleSheet); StyleSheet.instance = this; // for testing TODO: something better this.isSpeedy = speedy; // the big drawback here is that the css won't be editable in devtools this.sheet = undefined; this.tags = []; this.maxLength = maxLength; this.ctr = 0; } createClass(StyleSheet, [{ key: 'inject', value: function inject() { var _this = this; if (this.injected) { throw new Error('already injected stylesheet!'); } if (isBrowser) { // this section is just weird alchemy I found online off many sources this.tags[0] = makeStyleTag(); // this weirdness brought to you by firefox this.sheet = sheetForTag(this.tags[0]); } else { // server side 'polyfill'. just enough behavior to be useful. this.sheet = { cssRules: [], insertRule: function insertRule(rule) { // enough 'spec compliance' to be able to extract the rules later // in other words, just the cssText field var serverRule = { cssText: rule }; _this.sheet.cssRules.push(serverRule); return { serverRule: serverRule, appendRule: function appendRule(newCss) { return serverRule.cssText += newCss; } }; } }; } this.injected = true; } }, { key: 'speedy', value: function speedy(bool) { if (this.ctr !== 0) { throw new Error('cannot change speedy mode after inserting any rule to sheet. Either call speedy(' + bool + ') earlier in your app, or call flush() before speedy(' + bool + ')'); } this.isSpeedy = !!bool; } }, { key: '_insert', value: function _insert(rule) { // this weirdness for perf, and chrome's weird bug // https://stackoverflow.com/questions/20007992/chrome-suddenly-stopped-accepting-insertrule try { this.sheet.insertRule(rule, this.sheet.cssRules.length); // todo - correct index here } catch (e) { if (isDev) { // might need beter dx for this console.warn('whoops, illegal rule inserted', rule); //eslint-disable-line no-console } } } }, { key: 'insert', value: function insert(rule) { var _this2 = this; var insertedRule = void 0; if (isBrowser) { // this is the ultrafast version, works across browsers if (this.isSpeedy && this.sheet.insertRule) { this._insert(rule); } else { (function () { var textNode = document.createTextNode(rule); last(_this2.tags).appendChild(textNode); insertedRule = { textNode: textNode, appendRule: function appendRule(newCss) { return textNode.appendData(newCss); } }; if (!_this2.isSpeedy) { // sighhh _this2.sheet = sheetForTag(last(_this2.tags)); } })(); } } else { // server side is pretty simple insertedRule = this.sheet.insertRule(rule); } this.ctr++; if (isBrowser && this.ctr % this.maxLength === 0) { this.tags.push(makeStyleTag()); this.sheet = sheetForTag(last(this.tags)); } return insertedRule; } }, { key: 'flush', value: function flush() { if (isBrowser) { this.tags.forEach(function (tag) { return tag.parentNode.removeChild(tag); }); this.tags = []; this.sheet = null; this.ctr = 0; // todo - look for remnants in document.styleSheets } else { // simpler on server this.sheet.cssRules = []; } this.injected = false; } }, { key: 'rules', value: function rules() { if (!isBrowser) { return this.sheet.cssRules; } var arr = []; this.tags.forEach(function (tag) { return arr.splice.apply(arr, [arr.length, 0].concat(toConsumableArray(Array.from(sheetForTag(tag).cssRules)))); }); return arr; } }]); return StyleSheet; }(); // /* Wraps glamor's stylesheet and exports a singleton for the rest * of the app to use. */ var styleSheet = new StyleSheet({ speedy: false, maxLength: 40 }); // var ComponentStyle = function () { function ComponentStyle(rules, selector) { classCallCheck(this, ComponentStyle); this.rules = rules; this.selector = selector; } createClass(ComponentStyle, [{ key: 'generateAndInject', value: function generateAndInject() { if (!styleSheet.injected) styleSheet.inject(); var flatCSS = flatten(this.rules).join(''); if (this.selector) { flatCSS = this.selector + ' {' + flatCSS + '\n}'; } var root = safeParse(flatCSS); process$2(root); styleSheet.insert(root.toResult().css); } }]); return ComponentStyle; }(); var injectGlobal = function injectGlobal(strings) { for (var _len = arguments.length, interpolations = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { interpolations[_key - 1] = arguments[_key]; } var globalStyle = new ComponentStyle(css.apply(undefined, [strings].concat(interpolations))); globalStyle.generateAndInject(); }; /* Trying to avoid the unknown-prop errors on styled components by filtering by React's attribute whitelist. */ /* Logic copied from ReactDOMUnknownPropertyHook */ var reactProps = { children: true, dangerouslySetInnerHTML: true, key: true, ref: true, autoFocus: true, defaultValue: true, valueLink: true, defaultChecked: true, checkedLink: true, innerHTML: true, suppressContentEditableWarning: true, onFocusIn: true, onFocusOut: true, className: true, /* List copied from https://facebook.github.io/react/docs/events.html */ onCopy: true, onCut: true, onPaste: true, onCompositionEnd: true, onCompositionStart: true, onCompositionUpdate: true, onKeyDown: true, onKeyPress: true, onKeyUp: true, onFocus: true, onBlur: true, onChange: true, onInput: true, onSubmit: true, onClick: true, onContextMenu: true, onDoubleClick: true, onDrag: true, onDragEnd: true, onDragEnter: true, onDragExit: true, onDragLeave: true, onDragOver: true, onDragStart: true, onDrop: true, onMouseDown: true, onMouseEnter: true, onMouseLeave: true, onMouseMove: true, onMouseOut: true, onMouseOver: true, onMouseUp: true, onSelect: true, onTouchCancel: true, onTouchEnd: true, onTouchMove: true, onTouchStart: true, onScroll: true, onWheel: true, onAbort: true, onCanPlay: true, onCanPlayThrough: true, onDurationChange: true, onEmptied: true, onEncrypted: true, onEnded: true, onError: true, onLoadedData: true, onLoadedMetadata: true, onLoadStart: true, onPause: true, onPlay: true, onPlaying: true, onProgress: true, onRateChange: true, onSeeked: true, onSeeking: true, onStalled: true, onSuspend: true, onTimeUpdate: true, onVolumeChange: true, onWaiting: true, onLoad: true, onAnimationStart: true, onAnimationEnd: true, onAnimationIteration: true, onTransitionEnd: true, onCopyCapture: true, onCutCapture: true, onPasteCapture: true, onCompositionEndCapture: true, onCompositionStartCapture: true, onCompositionUpdateCapture: true, onKeyDownCapture: true, onKeyPressCapture: true, onKeyUpCapture: true, onFocusCapture: true, onBlurCapture: true, onChangeCapture: true, onInputCapture: true, onSubmitCapture: true, onClickCapture: true, onContextMenuCapture: true, onDoubleClickCapture: true, onDragCapture: true, onDragEndCapture: true, onDragEnterCapture: true, onDragExitCapture: true, onDragLeaveCapture: true, onDragOverCapture: true, onDragStartCapture: true, onDropCapture: true, onMouseDownCapture: true, onMouseEnterCapture: true, onMouseLeaveCapture: true, onMouseMoveCapture: true, onMouseOutCapture: true, onMouseOverCapture: true, onMouseUpCapture: true, onSelectCapture: true, onTouchCancelCapture: true, onTouchEndCapture: true, onTouchMoveCapture: true, onTouchStartCapture: true, onScrollCapture: true, onWheelCapture: true, onAbortCapture: true, onCanPlayCapture: true, onCanPlayThroughCapture: true, onDurationChangeCapture: true, onEmptiedCapture: true, onEncryptedCapture: true, onEndedCapture: true, onErrorCapture: true, onLoadedDataCapture: true, onLoadedMetadataCapture: true, onLoadStartCapture: true, onPauseCapture: true, onPlayCapture: true, onPlayingCapture: true, onProgressCapture: true, onRateChangeCapture: true, onSeekedCapture: true, onSeekingCapture: true, onStalledCapture: true, onSuspendCapture: true, onTimeUpdateCapture: true, onVolumeChangeCapture: true, onWaitingCapture: true, onLoadCapture: true, onAnimationStartCapture: true, onAnimationEndCapture: true, onAnimationIterationCapture: true, onTransitionEndCapture: true }; /* From HTMLDOMPropertyConfig */ var htmlProps = { /** * Standard Properties */ accept: true, acceptCharset: true, accessKey: true, action: true, allowFullScreen: true, allowTransparency: true, alt: true, // specifies target context for links with `preload` type as: true, async: true, autoComplete: true, // autoFocus is polyfilled/normalized by AutoFocusUtils // autoFocus: true, autoPlay: true, capture: true, cellPadding: true, cellSpacing: true, charSet: true, challenge: true, checked: true, cite: true, classID: true, className: true, cols: true, colSpan: true, content: true, contentEditable: true, contextMenu: true, controls: true, coords: true, crossOrigin: true, data: true, // For `<object />` acts as `src`. dateTime: true, default: true, defer: true, dir: true, disabled: true, download: true, draggable: true, encType: true, form: true, formAction: true, formEncType: true, formMethod: true, formNoValidate: true, formTarget: true, frameBorder: true, headers: true, height: true, hidden: true, high: true, href: true, hrefLang: true, htmlFor: true, httpEquiv: true, icon: true, id: true, inputMode: true, integrity: true, is: true, keyParams: true, keyType: true, kind: true, label: true, lang: true, list: true, loop: true, low: true, manifest: true, marginHeight: true, marginWidth: true, max: true, maxLength: true, media: true, mediaGroup: true, method: true, min: true, minLength: true, // Caution; `option.selected` is not updated if `select.multiple` is // disabled with `removeAttribute`. multiple: true, muted: true, name: true, nonce: true, noValidate: true, open: true, optimum: true, pattern: true, placeholder: true, playsInline: true, poster: true, preload: true, profile: true, radioGroup: true, readOnly: true, referrerPolicy: true, rel: true, required: true, reversed: true, role: true, rows: true, rowSpan: true, sandbox: true, scope: true, scoped: true, scrolling: true, seamless: true, selected: true, shape: true, size: true, sizes: true, span: true, spellCheck: true, src: true, srcDoc: true, srcLang: true, srcSet: true, start: true, step: true, style: true, summary: true, tabIndex: true, target: true, title: true, // Setting .type throws on non-<input> tags type: true, useMap: true, value: true, width: true, wmode: true, wrap: true, /** * RDFa Properties */ about: true, datatype: true, inlist: true, prefix: true, // property is also supported for OpenGraph in meta tags. property: true, resource: true, typeof: true, vocab: true, /** * Non-standard Properties */ // autoCapitalize and autoCorrect are supported in Mobile Safari for // keyboard hints. autoCapitalize: true, autoCorrect: true, // autoSave allows WebKit/Blink to persist values of input fields on page reloads autoSave: true, // color is for Safari mask-icon link color: true, // itemProp, itemScope, itemType are for // Microdata support. See http://schema.org/docs/gs.html itemProp: true, itemScope: true, itemType: true, // itemID and itemRef are for Microdata support as well but // only specified in the WHATWG spec document. See // https://html.spec.whatwg.org/multipage/microdata.html#microdata-dom-api itemID: true, itemRef: true, // results show looking glass icon and recent searches on input // search fields in WebKit/Blink results: true, // IE-only attribute that specifies security restrictions on an iframe // as an alternative to the sandbox attribute on IE<10 security: true, // IE-only attribute that controls focus behavior unselectable: 0 }; var svgProps = { accentHeight: true, accumulate: true, additive: true, alignmentBaseline: true, allowReorder: true, alphabetic: true, amplitude: true, arabicForm: true, ascent: true, attributeName: true, attributeType: true, autoReverse: true, azimuth: true, baseFrequency: true, baseProfile: true, baselineShift: true, bbox: true, begin: true, bias: true, by: true, calcMode: true, capHeight: true, clip: true, clipPath: true, clipRule: true, clipPathUnits: true, colorInterpolation: true, colorInterpolationFilters: true, colorProfile: true, colorRendering: true, contentScriptType: true, contentStyleType: true, cursor: true, cx: true, cy: true, d: true, decelerate: true, descent: true, diffuseConstant: true, direction: true, display: true, divisor: true, dominantBaseline: true, dur: true, dx: true, dy: true, edgeMode: true, elevation: true, enableBackground: true, end: true, exponent: true, externalResourcesRequired: true, fill: true, fillOpacity: true, fillRule: true, filter: true, filterRes: true, filterUnits: true, floodColor: true, floodOpacity: true, focusable: true, fontFamily: true, fontSize: true, fontSizeAdjust: true, fontStretch: true, fontStyle: true, fontVariant: true, fontWeight: true, format: true, from: true, fx: true, fy: true, g1: true, g2: true, glyphName: true, glyphOrientationHorizontal: true, glyphOrientationVertical: true, glyphRef: true, gradientTransform: true, gradientUnits: true, hanging: true, horizAdvX: true, horizOriginX: true, ideographic: true, imageRendering: true, in: true, in2: true, intercept: true, k: true, k1: true, k2: true, k3: true, k4: true, kernelMatrix: true, kernelUnitLength: true, kerning: true, keyPoints: true, keySplines: true, keyTimes: true, lengthAdjust: true, letterSpacing: true, lightingColor: true, limitingConeAngle: true, local: true, markerEnd: true, markerMid: true, markerStart: true, markerHeight: true, markerUnits: true, markerWidth: true, mask: true, maskContentUnits: true, maskUnits: true, mathematical: true, mode: true, numOctaves: true, offset: true, opacity: true, operator: true, order: true, orient: true, orientation: true, origin: true, overflow: true, overlinePosition: true, overlineThickness: true, paintOrder: true, panose1: true, pathLength: true, patternContentUnits: true, patternTransform: true, patternUnits: true, pointerEvents: true, points: true, pointsAtX: true, pointsAtY: true, pointsAtZ: true, preserveAlpha: true, preserveAspectRatio: true, primitiveUnits: true, r: true, radius: true, refX: true, refY: true, renderingIntent: true, repeatCount: true, repeatDur: true, requiredExtensions: true, requiredFeatures: true, restart: true, result: true, rotate: true, rx: true, ry: true, scale: true, seed: true, shapeRendering: true, slope: true, spacing: true, specularConstant: true, specularExponent: true, speed: true, spreadMethod: true, startOffset: true, stdDeviation: true, stemh: true, stemv: true, stitchTiles: true, stopColor: true, stopOpacity: true, strikethroughPosition: true, strikethroughThickness: true, string: true, stroke: true, strokeDasharray: true, strokeDashoffset: true, strokeLinecap: true, strokeLinejoin: true, strokeMiterlimit: true, strokeOpacity: true, strokeWidth: true, surfaceScale: true, systemLanguage: true, tableValues: true, targetX: true, targetY: true, textAnchor: true, textDecoration: true, textRendering: true, textLength: true, to: true, transform: true, u1: true, u2: true, underlinePosition: true, underlineThickness: true, unicode: true, unicodeBidi: true, unicodeRange: true, unitsPerEm: true, vAlphabetic: true, vHanging: true, vIdeographic: true, vMathematical: true, values: true, vectorEffect: true, version: true, vertAdvY: true, vertOriginX: true, vertOriginY: true, viewBox: true, viewTarget: true, visibility: true, widths: true, wordSpacing: true, writingMode: true, x: true, xHeight: true, x1: true, x2: true, xChannelSelector: true, xlinkActuate: true, xlinkArcrole: true, xlinkHref: true, xlinkRole: true, xlinkShow: true, xlinkTitle: true, xlinkType: true, xmlBase: true, xmlns: true, xmlnsXlink: true, xmlLang: true, xmlSpace: true, y: true, y1: true, y2: true, yChannelSelector: true, z: true, zoomAndPan: true }; /* From DOMProperty */ var ATTRIBUTE_NAME_START_CHAR = ':A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD'; var ATTRIBUTE_NAME_CHAR = ATTRIBUTE_NAME_START_CHAR + '\\-.0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040'; var isCustomAttribute = RegExp.prototype.test.bind(new RegExp('^(data|aria)-[' + ATTRIBUTE_NAME_CHAR + ']*$')); var hasOwnProperty$1 = {}.hasOwnProperty; var validAttr = (function (name) { return hasOwnProperty$1.call(htmlProps, name) || hasOwnProperty$1.call(svgProps, name) || isCustomAttribute(name.toLowerCase()) || hasOwnProperty$1.call(reactProps, name); }); /** * Checks if `value` is the * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an object, else `false`. * @example * * _.isObject({}); * // => true * * _.isObject([1, 2, 3]); * // => true * * _.isObject(_.noop); * // => true * * _.isObject(null); * // => false */ function isObject$1(value) { var type = typeof value === 'undefined' ? 'undefined' : _typeof(value); return value != null && (type == 'object' || type == 'function'); } var isObject_1 = isObject$1; var isObject = isObject_1; /** `Object#toString` result references. */ var funcTag = '[object Function]'; var genTag = '[object GeneratorFunction]'; var proxyTag = '[object Proxy]'; /** Used for built-in method references. */ var objectProto$1 = Object.prototype; /** * Used to resolve the * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) * of values. */ var objectToString$1 = objectProto$1.toString; /** * Checks if `value` is classified as a `Function` object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a function, else `false`. * @example * * _.isFunction(_); * // => true * * _.isFunction(/abc/); * // => false */ function isFunction(value) { // The use of `Object#toString` avoids issues with the `typeof` operator // in Safari 9 which returns 'object' for typed array and other constructors. var tag = isObject(value) ? objectToString$1.call(value) : ''; return tag == funcTag || tag == genTag || tag == proxyTag; } var isFunction_1 = isFunction; /** * Creates a broadcast that can be listened to, i.e. simple event emitter * * @see https://github.com/ReactTraining/react-broadcast */ var createBroadcast = function createBroadcast(initialValue) { var listeners = []; var currentValue = initialValue; return { publish: function publish(value) { currentValue = value; listeners.forEach(function (listener) { return listener(currentValue); }); }, subscribe: function subscribe(listener) { listeners.push(listener); // Publish to this subscriber once immediately. listener(currentValue); // eslint-disable-next-line no-return-assign return function () { return listeners = listeners.filter(function (item) { return item !== listener; }); }; } }; }; // NOTE: DO NOT CHANGE, changing this is a semver major change! var CHANNEL = '__styled-components__'; /** * Provide a theme to an entire react component tree via context and event listeners (have to do * both context and event emitter as pure components block context updates) */ var ThemeProvider = function (_Component) { inherits(ThemeProvider, _Component); function ThemeProvider() { classCallCheck(this, ThemeProvider); var _this = possibleConstructorReturn(this, (ThemeProvider.__proto__ || Object.getPrototypeOf(ThemeProvider)).call(this)); _this.getTheme = _this.getTheme.bind(_this); return _this; } createClass(ThemeProvider, [{ key: 'componentWillMount', value: function componentWillMount() { var _this2 = this; // If there is a ThemeProvider wrapper anywhere around this theme provider, merge this theme // with the outer theme if (this.context[CHANNEL]) { var subscribe = this.context[CHANNEL]; this.unsubscribeToOuter = subscribe(function (theme) { _this2.outerTheme = theme; }); } this.broadcast = createBroadcast(this.getTheme()); } }, { key: 'getChildContext', value: function getChildContext() { return Object.assign({}, this.context, defineProperty({}, CHANNEL, this.broadcast.subscribe)); } }, { key: 'componentWillReceiveProps', value: function componentWillReceiveProps(nextProps) { if (this.props.theme !== nextProps.theme) this.broadcast.publish(this.getTheme(nextProps.theme)); } }, { key: 'componentWillUnmount', value: function componentWillUnmount() { if (this.context[CHANNEL]) { this.unsubscribeToOuter(); } } // Get the theme from the props, supporting both (outerTheme) => {} as well as object notation }, { key: 'getTheme', value: function getTheme(passedTheme) { var theme = passedTheme || this.props.theme; if (isFunction_1(theme)) { var mergedTheme = theme(this.outerTheme); if (!isPlainObject_1(mergedTheme)) { throw new Error('[ThemeProvider] Please return an object from your theme function, i.e. theme={() => ({})}!'); } return mergedTheme; } if (!isPlainObject_1(theme)) { throw new Error('[ThemeProvider] Please make your theme prop a plain object'); } return Object.assign({}, this.outerTheme, theme); } }, { key: 'render', value: function render() { if (!this.props.children) { return null; } return React__default.Children.only(this.props.children); } }]); return ThemeProvider; }(React.Component); ThemeProvider.propTypes = { children: React.PropTypes.node, theme: React.PropTypes.oneOfType([React.PropTypes.func, React.PropTypes.object]) }; ThemeProvider.childContextTypes = defineProperty({}, CHANNEL, React.PropTypes.func.isRequired); ThemeProvider.contextTypes = defineProperty({}, CHANNEL, React.PropTypes.func); // /* eslint-disable react/prefer-stateless-function */ var AbstractStyledComponent = function (_Component) { inherits(AbstractStyledComponent, _Component); function AbstractStyledComponent() { classCallCheck(this, AbstractStyledComponent); return possibleConstructorReturn(this, (AbstractStyledComponent.__proto__ || Object.getPrototypeOf(AbstractStyledComponent)).apply(this, arguments)); } return AbstractStyledComponent; }(React.Component); var _styledComponent = (function (ComponentStyle) { var createStyledComponent = function createStyledComponent(target, rules, parent) { /* Handle styled(OtherStyledComponent) differently */ var isStyledComponent = AbstractStyledComponent.isPrototypeOf(target); if (isStyledComponent) { return createStyledComponent(target.target, target.rules.concat(rules), target); } var isTag = typeof target === 'string'; var componentStyle = new ComponentStyle(rules); var ParentComponent = parent || AbstractStyledComponent; var StyledComponent = function (_ParentComponent) { inherits(StyledComponent, _ParentComponent); function StyledComponent() { classCallCheck(this, StyledComponent); var _this2 = possibleConstructorReturn(this, (StyledComponent.__proto__ || Object.getPrototypeOf(StyledComponent)).call(this)); _this2.state = { theme: null }; return _this2; } createClass(StyledComponent, [{ key: 'componentWillMount', value: function componentWillMount() { var _this3 = this; // If there is a theme in the context, subscribe to the event emitter. This // is necessary due to pure components blocking context updates, this circumvents // that by updating when an event is emitted if (this.context[CHANNEL]) { var subscribe = this.context[CHANNEL]; this.unsubscribe = subscribe(function (theme) { // This will be called once immediately _this3.setState({ theme: theme }); }); } } }, { key: 'componentWillUnmount', value: function componentWillUnmount() { if (this.unsubscribe) { this.unsubscribe(); } } /* eslint-disable react/prop-types */ }, { key: 'render', value: function render() { var _this4 = this; var _props = this.props; var className = _props.className; var children = _props.children; var theme = this.state.theme || {}; var executionContext = Object.assign({}, this.props, { theme: theme }); var generatedClassName = componentStyle.generateAndInjectStyles(executionContext); var propsForElement = {}; /* Don't pass through non HTML tags through to HTML elements */ Object.keys(this.props).filter(function (propName) { return !isTag || validAttr(propName); }).forEach(function (propName) { propsForElement[propName] = _this4.props[propName]; }); propsForElement.className = [className, generatedClassName].filter(function (x) { return x; }).join(' '); return React.createElement(target, propsForElement, children); } }]); return StyledComponent; }(ParentComponent); /* Used for inheritance */ StyledComponent.rules = rules; StyledComponent.target = target; StyledComponent.displayName = isTag ? 'styled.' + target : 'Styled(' + target.displayName + ')'; StyledComponent.contextTypes = defineProperty({}, CHANNEL, React.PropTypes.func); return StyledComponent; }; return createStyledComponent; }); // var _styled = (function (styledComponent) { var styled = function styled(tag) { return function (strings) { for (var _len = arguments.length, interpolations = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { interpolations[_key - 1] = arguments[_key]; } return styledComponent(tag, css.apply(undefined, [strings].concat(interpolations))); }; }; /* Shorthands for all valid HTML Elements */ // Thanks to ReactDOMFactories for this handy list! styled.a = styled('a'); styled.abbr = styled('abbr'); styled.address = styled('address'); styled.area = styled('area'); styled.article = styled('article'); styled.aside = styled('aside'); styled.audio = styled('audio'); styled.b = styled('b'); styled.base = styled('base'); styled.bdi = styled('bdi'); styled.bdo = styled('bdo'); styled.big = styled('big'); styled.blockquote = styled('blockquote'); styled.body = styled('body'); styled.br = styled('br'); styled.button = styled('button'); styled.canvas = styled('canvas'); styled.caption = styled('caption'); styled.cite = styled('cite'); styled.code = styled('code'); styled.col = styled('col'); styled.colgroup = styled('colgroup'); styled.data = styled('data'); styled.datalist = styled('datalist'); styled.dd = styled('dd'); styled.del = styled('del'); styled.details = styled('details'); styled.dfn = styled('dfn'); styled.dialog = styled('dialog'); styled.div = styled('div'); styled.dl = styled('dl'); styled.dt = styled('dt'); styled.em = styled('em'); styled.embed = styled('embed'); styled.fieldset = styled('fieldset'); styled.figcaption = styled('figcaption'); styled.figure = styled('figure'); styled.footer = styled('footer'); styled.form = styled('form'); styled.h1 = styled('h1'); styled.h2 = styled('h2'); styled.h3 = styled('h3'); styled.h4 = styled('h4'); styled.h5 = styled('h5'); styled.h6 = styled('h6'); styled.head = styled('head'); styled.header = styled('header'); styled.hgroup = styled('hgroup'); styled.hr = styled('hr'); styled.html = styled('html'); styled.i = styled('i'); styled.iframe = styled('iframe'); styled.img = styled('img'); styled.input = styled('input'); styled.ins = styled('ins'); styled.kbd = styled('kbd'); styled.keygen = styled('keygen'); styled.label = styled('label'); styled.legend = styled('legend'); styled.li = styled('li'); styled.link = styled('link'); styled.main = styled('main'); styled.map = styled('map'); styled.mark = styled('mark'); styled.menu = styled('menu'); styled.menuitem = styled('menuitem'); styled.meta = styled('meta'); styled.meter = styled('meter'); styled.nav = styled('nav'); styled.noscript = styled('noscript'); styled.object = styled('object'); styled.ol = styled('ol'); styled.optgroup = styled('optgroup'); styled.option = styled('option'); styled.output = styled('output'); styled.p = styled('p'); styled.param = styled('param'); styled.picture = styled('picture'); styled.pre = styled('pre'); styled.progress = styled('progress'); styled.q = styled('q'); styled.rp = styled('rp'); styled.rt = styled('rt'); styled.ruby = styled('ruby'); styled.s = styled('s'); styled.samp = styled('samp'); styled.script = styled('script'); styled.section = styled('section'); styled.select = styled('select'); styled.small = styled('small'); styled.source = styled('source'); styled.span = styled('span'); styled.strong = styled('strong'); styled.style = styled('style'); styled.sub = styled('sub'); styled.summary = styled('summary'); styled.sup = styled('sup'); styled.table = styled('table'); styled.tbody = styled('tbody'); styled.td = styled('td'); styled.textarea = styled('textarea'); styled.tfoot = styled('tfoot'); styled.th = styled('th'); styled.thead = styled('thead'); styled.time = styled('time'); styled.title = styled('title'); styled.tr = styled('tr'); styled.track = styled('track'); styled.u = styled('u'); styled.ul = styled('ul'); styled.var = styled('var'); styled.video = styled('video'); styled.wbr = styled('wbr'); // SVG styled.circle = styled('circle'); styled.clipPath = styled('clipPath'); styled.defs = styled('defs'); styled.ellipse = styled('ellipse'); styled.g = styled('g'); styled.image = styled('image'); styled.line = styled('line'); styled.linearGradient = styled('linearGradient'); styled.mask = styled('mask'); styled.path = styled('path'); styled.pattern = styled('pattern'); styled.polygon = styled('polygon'); styled.polyline = styled('polyline'); styled.radialGradient = styled('radialGradient'); styled.rect = styled('rect'); styled.stop = styled('stop'); styled.svg = styled('svg'); styled.text = styled('text'); styled.tspan = styled('tspan'); return styled; }); function unwrapExports (x) { return x && x.__esModule ? x['default'] : x; } function createCommonjsModule(fn, module) { return module = { exports: {} }, fn(module, module.exports), module.exports; } var hash = createCommonjsModule(function (module, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = doHash; // murmurhash2 via https://gist.github.com/raycmorgan/588423 function doHash(str, seed) { var m = 0x5bd1e995; var r = 24; var h = seed ^ str.length; var length = str.length; var currentIndex = 0; while (length >= 4) { var k = UInt32(str, currentIndex); k = Umul32(k, m); k ^= k >>> r; k = Umul32(k, m); h = Umul32(h, m); h ^= k; currentIndex += 4; length -= 4; } switch (length) { case 3: h ^= UInt16(str, currentIndex); h ^= str.charCodeAt(currentIndex + 2) << 16; h = Umul32(h, m); break; case 2: h ^= UInt16(str, currentIndex); h = Umul32(h, m); break; case 1: h ^= str.charCodeAt(currentIndex); h = Umul32(h, m); break; } h ^= h >>> 13; h = Umul32(h, m); h ^= h >>> 15; return h >>> 0; } function UInt32(str, pos) { return str.charCodeAt(pos++) + (str.charCodeAt(pos++) << 8) + (str.charCodeAt(pos++) << 16) + (str.charCodeAt(pos) << 24); } function UInt16(str, pos) { return str.charCodeAt(pos++) + (str.charCodeAt(pos++) << 8); } function Umul32(n, m) { n = n | 0; m = m | 0; var nlo = n & 0xffff; var nhi = n >>> 16; var res = nlo * m + ((nhi * m & 0xffff) << 16) | 0; return res; } }); var hashStr = unwrapExports(hash); // var replaceWhitespace = function replaceWhitespace(str) { return str.replace(/\s|\\n/g, ''); }; var _keyframes = (function (nameGenerator) { return function (strings) { for (var _len = arguments.length, interpolations = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { interpolations[_key - 1] = arguments[_key]; } var rules = css.apply(undefined, [strings].concat(interpolations)); var hash = hashStr(replaceWhitespace(JSON.stringify(rules))); var name = nameGenerator(hash); var keyframes = new ComponentStyle(rules, '@keyframes ' + name); keyframes.generateAndInject(); return name; }; }); /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @typechecks */ var _hyphenPattern = /-(.)/g; /** * Camelcases a hyphenated string, for example: * * > camelize('background-color') * < "backgroundColor" * * @param {string} string * @return {string} */ function camelize$1(string) { return string.replace(_hyphenPattern, function (_, character) { return character.toUpperCase(); }); } var camelize_1 = camelize$1; var camelize = camelize_1; var msPattern$1 = /^-ms-/; /** * Camelcases a hyphenated CSS property name, for example: * * > camelizeStyleName('background-color') * < "backgroundColor" * > camelizeStyleName('-moz-transition') * < "MozTransition" * > camelizeStyleName('-ms-transition') * < "msTransition" * * As Andi Smith suggests * (http://www.andismith.com/blog/2012/02/modernizr-prefixed/), an `-ms` prefix * is converted to lowercase `ms`. * * @param {string} string * @return {string} */ function camelizeStyleName(string) { return camelize(string.replace(msPattern$1, 'ms-')); } var camelizeStyleName_1 = camelizeStyleName; var autoprefix_1 = createCommonjsModule(function (module, exports) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i];for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } }return target; }; // forked from https://www.npmjs.com/package/auto-prefixer function capitalize(str) { return str && str.charAt(0).toUpperCase() + str.substring(1); } function includes(obj, search) { if (typeof obj === 'number') { obj = obj.toString(); } return obj.indexOf(search) !== -1; } function values(obj) { return Object.keys(obj).map(function (key) { return obj[key]; }); } var webkitPrefix = 'Webkit'; var mozPrefix = 'Moz'; var msPrefix = 'ms'; var oPrefix = 'o'; var webkit = [webkitPrefix]; var webkitO = [webkitPrefix, oPrefix]; var moz = [mozPrefix]; var ms = [msPrefix]; var webkitMoz = [webkitPrefix, mozPrefix]; var webkitMozO = [webkitPrefix, mozPrefix, oPrefix]; var webkitMozMs = [webkitPrefix, mozPrefix, msPrefix]; var webkitMs = [webkitPrefix, msPrefix]; var allPrefixes = [webkitPrefix, msPrefix, mozPrefix, oPrefix]; var neededRules = { alignContent: webkit, alignItems: webkit, alignSelf: webkit, animation: webkitMoz, animationDelay: webkitMoz, animationDirection: webkitMoz, animationDuration: webkitMoz, animationFillMode: webkitMoz, animationIterationCount: webkitMoz, animationName: webkitMoz, animationPlayState: webkitMoz, animationTimingFunction: webkitMoz, appearance: webkitMoz, backfaceVisibility: webkitMoz, backgroundClip: webkit, borderImage: webkitMozO, borderImageSlice: webkitMozO, boxShadow: webkitMozMs, boxSizing: webkitMoz, clipPath: webkit, columns: webkitMoz, cursor: webkitMoz, flex: webkitMs, //new flex and 2012 specification , no support for old specification flexBasis: webkitMs, flexDirection: webkitMs, flexFlow: webkitMs, flexGrow: webkitMs, flexShrink: webkitMs, flexWrap: webkitMs, fontSmoothing: webkitMoz, justifyContent: webkitMoz, order: webkitMoz, perspective: webkitMoz, perspectiveOrigin: webkitMoz, transform: webkitMozMs, transformOrigin: webkitMozMs, transformOriginX: webkitMozMs, transformOriginY: webkitMozMs, transformOriginZ: webkitMozMs, transformStyle: webkitMozMs, transition: webkitMozMs, transitionDelay: webkitMozMs, transitionDuration: webkitMozMs, transitionProperty: webkitMozMs, transitionTimingFunction: webkitMozMs, userSelect: webkitMozMs }; var neededCssValues = { calc: webkitMoz, flex: webkitMs }; var clientPrefix = function () { if (typeof navigator === 'undefined') { //in server rendering return allPrefixes; //also default when not passing true to 'all vendors' explicitly } var sUsrAg = navigator.userAgent; if (includes(sUsrAg, 'Chrome')) { return webkit; } else if (includes(sUsrAg, 'Safari')) { return webkit; } else if (includes(sUsrAg, 'Opera')) { return webkitO; } else if (includes(sUsrAg, 'Firefox')) { return moz; } else if (includes(sUsrAg, 'MSIE')) { return ms; } return []; }(); function checkAndAddPrefix(styleObj, key, val, allVendors) { var oldFlex = true; function valueWithPrefix(cssVal, prefix) { return includes(val, cssVal) && (allVendors || includes(clientPrefix, prefix)) ? val.replace(cssVal, ['', prefix.toLowerCase(), cssVal].join('-')) : null; //example return -> 'transition: -webkit-transition' } function createObjectOfValuesWithPrefixes(cssVal) { return neededCssValues[cssVal].reduce(function (o, v) { o[v.toLowerCase()] = valueWithPrefix(cssVal, v); return o; }, {}); //example return -> {webkit: -webkit-calc(10% - 1px), moz: -moz-calc(10% - 1px)} } function composePrefixedValues(objOfPrefixedValues) { var composed = values(objOfPrefixedValues).filter(function (str) { return str !== null; }).map(function (str) { return key + ':' + str; }).join(';'); if (composed) { styleObj[key] = styleObj[key] + ';' + composed; } //example do -> {display: "flex;display:-webkit-flex;display:-ms-flexbox"} } function valWithoutFlex() { return val.replace('flex-', '').toLowerCase(); } if (val === 'flex' && key === 'display') { var flex = createObjectOfValuesWithPrefixes('flex'); if (flex.ms) { flex.ms = flex.ms.replace('flex', 'flexbox'); } //special case composePrefixedValues(flex); //if(oldFlex){styleObj[key] = styleObj[key] + ';display:-webkit-box'; } if (oldFlex) { styleObj[key] = '-webkit-box;display:' + styleObj[key]; } //display:flex is simple case, no need for other checks return styleObj; } var allPrefixedCssValues = Object.keys(neededCssValues).filter(function (c) { return c !== 'flex'; }).reduce(function (o, c) { o[c] = createObjectOfValuesWithPrefixes(c); return o; }, {}); /* example allPrefixedCssValues = { calc: { webkit: "translateX(-webkit-calc(10% - 10px))", moz: "translateX(-moz-calc(10% - 10px))" }, flex: { ms: null, webkit: null } };*/ //if(includes(val, 'gradient')){ // //} if (neededRules[key]) { var prefixes = allVendors ? neededRules[key] : neededRules[key].filter(function (vendor) { return includes(clientPrefix, vendor); }); var prefixedProperties = prefixes.reduce(function (obj, prefix) { var property = val; //add valueWithPrefixes in their position and null the property Object.keys(allPrefixedCssValues).forEach(function (cssKey) { var cssVal = allPrefixedCssValues[cssKey]; Object.keys(cssVal).forEach(function (vendor) { if (cssVal[vendor] && capitalize(prefix) === capitalize(vendor)) { property = cssVal[vendor]; cssVal[vendor] = null; } }); }); obj[prefix + capitalize(key)] = property; return obj; }, {}); if (oldFlex) { switch (key) { case 'flexDirection': if (includes(val, 'reverse')) { prefixedProperties.WebkitBoxDirection = 'reverse'; } else { prefixedProperties.WebkitBoxDirection = 'normal'; } if (includes(val, 'row')) { prefixedProperties.WebkitBoxOrient = prefixedProperties.boxOrient = 'horizontal'; } else if (includes(val, 'column')) { prefixedProperties.WebkitBoxOrient = 'vertical'; } break; case 'alignSelf': prefixedProperties.msFlexItemAlign = valWithoutFlex();break; case 'alignItems': prefixedProperties.WebkitBoxAlign = prefixedProperties.msFlexAlign = valWithoutFlex();break; case 'alignContent': if (val === 'spaceAround') { prefixedProperties.msFlexLinePack = 'distribute'; } else if (val === 'spaceBetween') { prefixedProperties.msFlexLinePack = 'justify'; } else { prefixedProperties.msFlexLinePack = valWithoutFlex(); } break; case 'justifyContent': if (val === 'spaceAround') { prefixedProperties.msFlexPack = 'distribute'; } else if (val === 'spaceBetween') { prefixedProperties.WebkitBoxPack = prefixedProperties.msFlexPack = 'justify'; } else { prefixedProperties.WebkitBoxPack = prefixedProperties.msFlexPack = valWithoutFlex(); } break; case 'flexBasis': prefixedProperties.msFlexPreferredSize = val;break; case 'order': prefixedProperties.msFlexOrder = '-moz-calc(' + val + ')'; //ugly hack to prevent react from adding 'px' prefixedProperties.WebkitBoxOrdinalGroup = '-webkit-calc(' + (parseInt(val) + 1) + ')'; //this might not work for browsers who don't support calc break; case 'flexGrow': prefixedProperties.WebkitBoxFlex = prefixedProperties.msFlexPositive = val;break; case 'flexShrink': prefixedProperties.msFlexNegative = val;break; case 'flex': prefixedProperties.WebkitBoxFlex = val;break; } } Object.assign(styleObj, prefixedProperties); } //if valueWithPrefixes were not added before Object.keys(allPrefixedCssValues).forEach(function (cssKey) { composePrefixedValues(allPrefixedCssValues[cssKey]); }); return styleObj; } function autoPrefixer(obj, allVendors) { Object.keys(obj).forEach(function (key) { return obj = checkAndAddPrefix(_extends({}, obj), key, obj[key], allVendors); }); return obj; } function gate(objOrBool) { var optionalBoolean = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1]; if (typeof objOrBool === 'boolean') { return function (obj) { return autoPrefixer(obj, objOrBool); }; } if (!objOrBool) { return {}; } else { return autoPrefixer(objOrBool, optionalBoolean); } // default: don't include all browsers } var autoprefix = exports.autoprefix = gate(true); }); var autoprefix_2 = autoprefix_1.autoprefix; var autoprefix$$1 = (function (root) { root.walkDecls(function (decl) { /* No point even checking custom props */ if (decl.prop.startsWith('--')) return; var objStyle = defineProperty({}, camelizeStyleName_1(decl.prop), decl.value); var prefixed = autoprefix_2(objStyle); Object.keys(prefixed).reverse().forEach(function (newProp) { decl.cloneBefore({ prop: hyphenateStyleName_1(newProp), value: prefixed[newProp] }); }); decl.remove(); }); }); // /* ComponentStyle is all the CSS-specific stuff, not the React-specific stuff. */ var _ComponentStyle = (function (nameGenerator) { var inserted = {}; var ComponentStyle = function () { function ComponentStyle(rules) { classCallCheck(this, ComponentStyle); this.rules = rules; if (!styleSheet.injected) styleSheet.inject(); this.insertedRule = styleSheet.insert(''); } /* * Flattens a rule set into valid CSS * Hashes it, wraps the whole chunk in a ._hashName {} * Parses that with PostCSS then runs PostCSS-Nested on it * Returns the hash to be injected on render() * */ createClass(ComponentStyle, [{ key: 'generateAndInjectStyles', value: function generateAndInjectStyles(executionContext) { var flatCSS = flatten(this.rules, executionContext).join('').replace(/^\s*\/\/.*$/gm, ''); // replace JS comments var hash = hashStr(flatCSS); if (!inserted[hash]) { var selector = nameGenerator(hash); inserted[hash] = selector; var root = safeParse('.' + selector + ' { ' + flatCSS + ' }'); process$2(root); autoprefix$$1(root); this.insertedRule.appendRule(root.toResult().css); } return inserted[hash]; } }]); return ComponentStyle; }(); return ComponentStyle; }); // /* Import singletons */ /* Import singleton constructors */ /* Import components */ /* Instantiate singletons */ var keyframes = _keyframes(generateAlphabeticName); var styled = _styled(_styledComponent(_ComponentStyle(generateAlphabeticName))); exports['default'] = styled; exports.css = css; exports.keyframes = keyframes; exports.injectGlobal = injectGlobal; exports.ThemeProvider = ThemeProvider; Object.defineProperty(exports, '__esModule', { value: true }); })));
/** * @author alteredq / http://alteredqualia.com/ * @author mrdoob / http://mrdoob.com/ */ THREE.Math = { generateUUID: function () { // http://www.broofa.com/Tools/Math.uuid.htm var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split( '' ); var uuid = new Array( 36 ); var rnd = 0, r; return function () { for ( var i = 0; i < 36; i ++ ) { if ( i === 8 || i === 13 || i === 18 || i === 23 ) { uuid[ i ] = '-'; } else if ( i === 14 ) { uuid[ i ] = '4'; } else { if ( rnd <= 0x02 ) rnd = 0x2000000 + ( Math.random() * 0x1000000 ) | 0; r = rnd & 0xf; rnd = rnd >> 4; uuid[ i ] = chars[ ( i === 19 ) ? ( r & 0x3 ) | 0x8 : r ]; } } return uuid.join( '' ); }; }(), clamp: function ( value, min, max ) { return Math.max( min, Math.min( max, value ) ); }, // compute euclidian modulo of m % n // https://en.wikipedia.org/wiki/Modulo_operation euclideanModulo: function ( n, m ) { return ( ( n % m ) + m ) % m; }, // Linear mapping from range <a1, a2> to range <b1, b2> mapLinear: function ( x, a1, a2, b1, b2 ) { return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 ); }, // http://en.wikipedia.org/wiki/Smoothstep smoothstep: function ( x, min, max ) { if ( x <= min ) return 0; if ( x >= max ) return 1; x = ( x - min ) / ( max - min ); return x * x * ( 3 - 2 * x ); }, smootherstep: function ( x, min, max ) { if ( x <= min ) return 0; if ( x >= max ) return 1; x = ( x - min ) / ( max - min ); return x * x * x * ( x * ( x * 6 - 15 ) + 10 ); }, // Random float from <0, 1> with 16 bits of randomness // (standard Math.random() creates repetitive patterns when applied over larger space) random16: function () { return ( 65280 * Math.random() + 255 * Math.random() ) / 65535; }, // Random integer from <low, high> interval randInt: function ( low, high ) { return low + Math.floor( Math.random() * ( high - low + 1 ) ); }, // Random float from <low, high> interval randFloat: function ( low, high ) { return low + Math.random() * ( high - low ); }, // Random float from <-range/2, range/2> interval randFloatSpread: function ( range ) { return range * ( 0.5 - Math.random() ); }, degToRad: function () { var degreeToRadiansFactor = Math.PI / 180; return function ( degrees ) { return degrees * degreeToRadiansFactor; }; }(), radToDeg: function () { var radianToDegreesFactor = 180 / Math.PI; return function ( radians ) { return radians * radianToDegreesFactor; }; }(), isPowerOfTwo: function ( value ) { return ( value & ( value - 1 ) ) === 0 && value !== 0; }, nearestPowerOfTwo: function ( value ) { return Math.pow( 2, Math.round( Math.log( value ) / Math.LN2 ) ); }, nextPowerOfTwo: function ( value ) { value --; value |= value >> 1; value |= value >> 2; value |= value >> 4; value |= value >> 8; value |= value >> 16; value ++; return value; } };
var chai = require('chai'); var expect = chai.expect; var request = require('supertest'); var app; var errorMessage = 'Parameter is not an integer'; // There are three ways to pass parameters to express: // - as part of the URL // - as GET parameter in the querystring // - as POST parameter in the body // URL params take precedence over GET params which take precedence over // POST params. function validation(req, res) { req.check('testparam', errorMessage).notEmpty().isInt(); var errors = req.validationErrors(); if (errors) { return res.send(errors); } res.send({ testparam: req.params.testparam || req.query.testparam || req.body.testparam }); } function fail(body) { expect(body).to.have.length(1); expect(body[0]).to.have.property('msg', errorMessage); } function pass(body) { expect(body).to.have.property('testparam', '42'); } function getRoute(path, test, done) { request(app) .get(path) .end(function(err, res) { test(res.body); done(); }); } function postRoute(path, data, test, done) { request(app) .post(path) .send(data) .end(function(err, res) { test(res.body); done(); }); } // This before() is required in each set of tests in // order to use a new validation function in each file before(function() { delete require.cache[require.resolve('./helpers/app')]; app = require('./helpers/app')(validation); }); describe('#check()/#assert()/#validate()', function() { describe('GET tests', function() { it('should return an error when param does not validate', function(done) { getRoute('/test', fail, done); }); it('should return a success when param validates', function(done) { getRoute('/42', pass, done); }); // GET only: Test URL over GET param precedence it('should return an error when param and query does not validate', function(done) { getRoute('/test?testparam=gettest', fail, done); }); it('should return a success when param validates, but query does not', function(done) { getRoute('/42?testparam=gettest', pass, done); }); it('should return an error when query does not validate', function(done) { getRoute('/?testparam=test', fail, done); }); it('should return a success when query validates', function(done) { getRoute('/?testparam=42', pass, done); }); }); describe('POST tests', function() { it('should return an error when param does not validate', function(done) { postRoute('/test', null, fail, done); }); it('should return a success when param validates', function(done) { postRoute('/42', null, pass, done); }); // POST only: Test URL over GET over POST param precedence it('should return an error when body validates, but failing param/query is present', function(done) { postRoute('/test?testparam=gettest', { testparam: '42' }, fail, done); }); it('should return a success when param validates, but non-validating body is present', function(done) { postRoute('/42?testparam=42', { testparam: 'posttest' }, pass, done); }); it('should return an error when query does not validate, but body validates', function(done) { postRoute('/?testparam=test', { testparam: '42' }, fail, done); }); it('should return a success when query validates, but non-validating body is present', function(done) { postRoute('/?testparam=42', { testparam: 'posttest' }, pass, done); }); it('should return an error when body does not validate', function(done) { postRoute('/', { testparam: 'test' }, fail, done); }); it('should return a success when body validates', function(done) { postRoute('/', { testparam: '42' }, pass, done); }); }); });
run_spec(__dirname, ["babel", "flow"]);
var plugin = function(options){ return function(style){ var nodes = this.nodes; style.define('add', function(a, b) { return a.operate('+', b); }); style.define('something', function() { return new nodes.Ident('foobar'); }); style.define('set_red', function(color, value) { return new nodes.RGBA(value.val, color.g, color.b, color.a); }); style.define('get_opt', function(name) { var val = options[name.val]; switch (typeof val) { case 'boolean': return new nodes.Boolean(val); case 'number': return new nodes.Unit(val); case 'string': default: return new nodes.String(val); } }); }; }; module.exports = plugin;
/** * * Apply left click on an element. If selector is not provided, click on the last * moved-to location. * * @param {String} selector element to click on * @uses protocol/element, protocol/buttonPress * @type action * */ var handleMouseButtonCommand = require('../helpers/handleMouseButtonCommand'); module.exports = function leftClick (selector) { return handleMouseButtonCommand.call(this, selector, 'left'); };
/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactReconciler */ 'use strict'; var ReactRef = require('ReactRef'); var ReactInstrumentation = require('ReactInstrumentation'); var warning = require('fbjs/lib/warning'); /** * Helper to call ReactRef.attachRefs with this composite component, split out * to avoid allocations in the transaction mount-ready queue. */ function attachRefs(transaction) { ReactRef.attachRefs( this, this._currentElement, transaction, ); } var ReactReconciler = { /** * Initializes the component, renders markup, and registers event listeners. * * @param {ReactComponent} internalInstance * @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction * @param {?object} the containing host component instance * @param {?object} info about the host container * @return {?string} Rendered markup to be inserted into the DOM. * @final * @internal */ mountComponent: function( internalInstance, transaction, hostParent, hostContainerInfo, context, parentDebugID // 0 in production and for roots ) { if (__DEV__) { if (internalInstance._debugID !== 0) { ReactInstrumentation.debugTool.onBeforeMountComponent( internalInstance._debugID, internalInstance._currentElement, parentDebugID ); } } var markup = internalInstance.mountComponent( transaction, hostParent, hostContainerInfo, context, parentDebugID ); if (internalInstance._currentElement && internalInstance._currentElement.ref != null) { transaction.getReactMountReady().enqueue(attachRefs, internalInstance); } if (__DEV__) { if (internalInstance._debugID !== 0) { ReactInstrumentation.debugTool.onMountComponent( internalInstance._debugID ); } } return markup; }, /** * Returns a value that can be passed to * ReactComponentEnvironment.replaceNodeWithMarkup. */ getHostNode: function(internalInstance) { return internalInstance.getHostNode(); }, /** * Releases any resources allocated by `mountComponent`. * * @final * @internal */ unmountComponent: function(internalInstance, safely) { if (__DEV__) { if (internalInstance._debugID !== 0) { ReactInstrumentation.debugTool.onBeforeUnmountComponent( internalInstance._debugID ); } } ReactRef.detachRefs(internalInstance, internalInstance._currentElement); internalInstance.unmountComponent(safely); if (__DEV__) { if (internalInstance._debugID !== 0) { ReactInstrumentation.debugTool.onUnmountComponent( internalInstance._debugID ); } } }, /** * Update a component using a new element. * * @param {ReactComponent} internalInstance * @param {ReactElement} nextElement * @param {ReactReconcileTransaction} transaction * @param {object} context * @internal */ receiveComponent: function( internalInstance, nextElement, transaction, context ) { var prevElement = internalInstance._currentElement; if (nextElement === prevElement && context === internalInstance._context ) { // Since elements are immutable after the owner is rendered, // we can do a cheap identity compare here to determine if this is a // superfluous reconcile. It's possible for state to be mutable but such // change should trigger an update of the owner which would recreate // the element. We explicitly check for the existence of an owner since // it's possible for an element created outside a composite to be // deeply mutated and reused. // TODO: Bailing out early is just a perf optimization right? // TODO: Removing the return statement should affect correctness? return; } if (__DEV__) { if (internalInstance._debugID !== 0) { ReactInstrumentation.debugTool.onBeforeUpdateComponent( internalInstance._debugID, nextElement ); } } var refsChanged = ReactRef.shouldUpdateRefs( prevElement, nextElement ); if (refsChanged) { ReactRef.detachRefs(internalInstance, prevElement); } internalInstance.receiveComponent(nextElement, transaction, context); if (refsChanged && internalInstance._currentElement && internalInstance._currentElement.ref != null) { transaction.getReactMountReady().enqueue(attachRefs, internalInstance); } if (__DEV__) { if (internalInstance._debugID !== 0) { ReactInstrumentation.debugTool.onUpdateComponent( internalInstance._debugID ); } } }, /** * Flush any dirty changes in a component. * * @param {ReactComponent} internalInstance * @param {ReactReconcileTransaction} transaction * @internal */ performUpdateIfNecessary: function( internalInstance, transaction, updateBatchNumber ) { if (internalInstance._updateBatchNumber !== updateBatchNumber) { // The component's enqueued batch number should always be the current // batch or the following one. warning( internalInstance._updateBatchNumber == null || internalInstance._updateBatchNumber === updateBatchNumber + 1, 'performUpdateIfNecessary: Unexpected batch number (current %s, ' + 'pending %s)', updateBatchNumber, internalInstance._updateBatchNumber ); return; } if (__DEV__) { if (internalInstance._debugID !== 0) { ReactInstrumentation.debugTool.onBeforeUpdateComponent( internalInstance._debugID, internalInstance._currentElement ); } } internalInstance.performUpdateIfNecessary(transaction); if (__DEV__) { if (internalInstance._debugID !== 0) { ReactInstrumentation.debugTool.onUpdateComponent( internalInstance._debugID ); } } }, }; module.exports = ReactReconciler;
/** * @fileoverview Main Espree file that converts Acorn into Esprima output. * * This file contains code from the following MIT-licensed projects: * 1. Acorn * 2. Babylon * 3. Babel-ESLint * * This file also contains code from Esprima, which is BSD licensed. * * Acorn is Copyright 2012-2015 Acorn Contributors (https://github.com/marijnh/acorn/blob/master/AUTHORS) * Babylon is Copyright 2014-2015 various contributors (https://github.com/babel/babel/blob/master/packages/babylon/AUTHORS) * Babel-ESLint is Copyright 2014-2015 Sebastian McKenzie <sebmck@gmail.com> * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * Esprima is Copyright (c) jQuery Foundation, Inc. and Contributors, All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* eslint no-undefined:0, no-use-before-define: 0 */ "use strict"; var astNodeTypes = require("./lib/ast-node-types"), commentAttachment = require("./lib/comment-attachment"), TokenTranslator = require("./lib/token-translator"), acornJSX = require("acorn-jsx/inject"), rawAcorn = require("acorn"); var acorn = acornJSX(rawAcorn); var DEFAULT_ECMA_VERSION = 5; var lookahead, extra, lastToken; /** * Object.assign polyfill for Node < 4 * @param {Object} target The target object * @param {...Object} sources Sources for the object * @returns {Object} `target` after being mutated */ var assign = Object.assign || function assign(target) { for (var argIndex = 1; argIndex < arguments.length; argIndex++) { if (arguments[argIndex] !== null && typeof arguments[argIndex] === "object") { var keys = Object.keys(arguments[argIndex]); for (var keyIndex = 0; keyIndex < keys.length; keyIndex++) { target[keys[keyIndex]] = arguments[argIndex][keys[keyIndex]]; } } } return target; }; /** * Resets the extra object to its default. * @returns {void} * @private */ function resetExtra() { extra = { tokens: null, range: false, loc: false, comment: false, comments: [], tolerant: false, errors: [], strict: false, ecmaFeatures: {}, ecmaVersion: DEFAULT_ECMA_VERSION, isModule: false }; } var tt = acorn.tokTypes, getLineInfo = acorn.getLineInfo; // custom type for JSX attribute values tt.jsxAttrValueToken = {}; /** * Normalize ECMAScript version from the initial config * @param {number} ecmaVersion ECMAScript version from the initial config * @returns {number} normalized ECMAScript version */ function normalizeEcmaVersion(ecmaVersion) { if (typeof ecmaVersion === "number") { var version = ecmaVersion; // Calculate ECMAScript edition number from official year version starting with // ES2015, which corresponds with ES6 (or a difference of 2009). if (version >= 2015) { version -= 2009; } switch (version) { case 3: case 5: case 6: case 7: case 8: case 9: return version; default: throw new Error("Invalid ecmaVersion."); } } else { return DEFAULT_ECMA_VERSION; } } /** * Determines if a node is valid given the set of ecmaFeatures. * @param {ASTNode} node The node to check. * @returns {boolean} True if the node is allowed, false if not. * @private */ function isValidNode(node) { var ecma = extra.ecmaFeatures; switch (node.type) { case "ExperimentalSpreadProperty": case "ExperimentalRestProperty": return ecma.experimentalObjectRestSpread; case "ImportDeclaration": case "ExportNamedDeclaration": case "ExportDefaultDeclaration": case "ExportAllDeclaration": return extra.isModule; default: return true; } } /** * Performs last-minute Esprima-specific compatibility checks and fixes. * @param {ASTNode} result The node to check. * @returns {ASTNode} The finished node. * @private * @this acorn.Parser */ function esprimaFinishNode(result) { // ensure that parsed node was allowed through ecmaFeatures if (!isValidNode(result)) { this.unexpected(result.start); } // https://github.com/marijnh/acorn/issues/323 if (result.type === "TryStatement") { delete result.guardedHandlers; } else if (result.type === "CatchClause") { delete result.guard; } // Acorn doesn't count the opening and closing backticks as part of templates // so we have to adjust ranges/locations appropriately. if (result.type === "TemplateElement") { // additional adjustment needed if ${ is the last token var terminalDollarBraceL = this.input.slice(result.end, result.end + 2) === "${"; if (result.range) { result.range[0]--; result.range[1] += (terminalDollarBraceL ? 2 : 1); } if (result.loc) { result.loc.start.column--; result.loc.end.column += (terminalDollarBraceL ? 2 : 1); } } // Acorn uses undefined instead of null, which affects serialization if (result.type === "Literal" && result.value === undefined) { result.value = null; } if (extra.attachComment) { commentAttachment.processComment(result); } if (result.type.indexOf("Function") > -1 && !result.generator) { result.generator = false; } return result; } /** * Determines if a token is valid given the set of ecmaFeatures. * @param {acorn.Parser} parser The parser to check. * @returns {boolean} True if the token is allowed, false if not. * @private */ function isValidToken(parser) { var ecma = extra.ecmaFeatures; var type = parser.type; switch (type) { case tt.jsxName: case tt.jsxText: case tt.jsxTagStart: case tt.jsxTagEnd: return ecma.jsx; // https://github.com/ternjs/acorn/issues/363 case tt.regexp: if (extra.ecmaVersion < 6 && parser.value.flags && parser.value.flags.indexOf("y") > -1) { return false; } return true; default: return true; } } /** * Injects esprimaFinishNode into the finishNode process. * @param {Function} finishNode Original finishNode function. * @returns {ASTNode} The finished node. * @private */ function wrapFinishNode(finishNode) { return /** @this acorn.Parser */ function(node, type, pos, loc) { var result = finishNode.call(this, node, type, pos, loc); return esprimaFinishNode.call(this, result); }; } acorn.plugins.espree = function(instance) { instance.extend("finishNode", wrapFinishNode); instance.extend("finishNodeAt", wrapFinishNode); instance.extend("next", function(next) { return /** @this acorn.Parser */ function() { if (!isValidToken(this)) { this.unexpected(); } return next.call(this); }; }); // needed for experimental object rest/spread instance.extend("checkLVal", function(checkLVal) { return /** @this acorn.Parser */ function(expr, isBinding, checkClashes) { if (extra.ecmaFeatures.experimentalObjectRestSpread && expr.type === "ObjectPattern") { for (var i = 0; i < expr.properties.length; i++) { if (expr.properties[i].type.indexOf("Experimental") === -1) { this.checkLVal(expr.properties[i].value, isBinding, checkClashes); } } return undefined; } return checkLVal.call(this, expr, isBinding, checkClashes); }; }); instance.extend("parseTopLevel", function(parseTopLevel) { return /** @this acorn.Parser */ function(node) { if (extra.ecmaFeatures.impliedStrict && this.options.ecmaVersion >= 5) { this.strict = true; } return parseTopLevel.call(this, node); }; }); instance.extend("toAssignable", function(toAssignable) { return /** @this acorn.Parser */ function(node, isBinding, refDestructuringErrors) { if (extra.ecmaFeatures.experimentalObjectRestSpread && node.type === "ObjectExpression" ) { node.type = "ObjectPattern"; for (var i = 0; i < node.properties.length; i++) { var prop = node.properties[i]; if (prop.type === "ExperimentalSpreadProperty") { prop.type = "ExperimentalRestProperty"; } else if (prop.kind !== "init") { this.raise(prop.key.start, "Object pattern can't contain getter or setter"); } else { this.toAssignable(prop.value, isBinding); } } return node; } else { return toAssignable.call(this, node, isBinding, refDestructuringErrors); } }; }); /** * Method to parse an object rest or object spread. * @returns {ASTNode} The node representing object rest or object spread. * @this acorn.Parser */ instance.parseObjectRest = function() { var node = this.startNode(); this.next(); node.argument = this.parseIdent(); if (this.type === tt.comma) { this.raise(this.start, "Unexpected trailing comma after rest property"); } return this.finishNode(node, "ExperimentalRestProperty"); }; instance.extend("parseProperty", function(parseProperty) { /** * Override `parseProperty` method to parse rest/spread properties. * @param {boolean} isPattern True if the object is a destructuring pattern. * @param {Object} refDestructuringErrors ? * @returns {ASTNode} The node representing a rest/spread property. * @this acorn.Parser */ return function(isPattern, refDestructuringErrors) { if (extra.ecmaFeatures.experimentalObjectRestSpread && this.type === tt.ellipsis) { var prop; if (isPattern) { prop = this.parseObjectRest(); } else { prop = this.parseSpread(); prop.type = "ExperimentalSpreadProperty"; } return prop; } return parseProperty.call(this, isPattern, refDestructuringErrors); }; }); instance.extend("checkPropClash", function(checkPropClash) { /** * Override `checkPropClash` method to avoid clash on rest/spread properties. * @param {ASTNode} prop A property node to check. * @param {Object} propHash Names map. * @param {Object} refDestructuringErrors Destructuring error information. * @returns {void} * @this acorn.Parser */ return function(prop, propHash, refDestructuringErrors) { if (prop.type === "ExperimentalRestProperty" || prop.type === "ExperimentalSpreadProperty") { return; } checkPropClash.call(this, prop, propHash, refDestructuringErrors); }; }); /** * Overwrites the default raise method to throw Esprima-style errors. * @param {int} pos The position of the error. * @param {string} message The error message. * @throws {SyntaxError} A syntax error. * @returns {void} */ instance.raise = instance.raiseRecoverable = function(pos, message) { var loc = getLineInfo(this.input, pos); var err = new SyntaxError(message); err.index = pos; err.lineNumber = loc.line; err.column = loc.column + 1; // acorn uses 0-based columns throw err; }; /** * Overwrites the default unexpected method to throw Esprima-style errors. * @param {int} pos The position of the error. * @throws {SyntaxError} A syntax error. * @returns {void} */ instance.unexpected = function(pos) { var message = "Unexpected token"; if (pos !== null && pos !== undefined) { this.pos = pos; if (this.options.locations) { while (this.pos < this.lineStart) { this.lineStart = this.input.lastIndexOf("\n", this.lineStart - 2) + 1; --this.curLine; } } this.nextToken(); } if (this.end > this.start) { message += " " + this.input.slice(this.start, this.end); } this.raise(this.start, message); }; /* * Esprima-FB represents JSX strings as tokens called "JSXText", but Acorn-JSX * uses regular tt.string without any distinction between this and regular JS * strings. As such, we intercept an attempt to read a JSX string and set a flag * on extra so that when tokens are converted, the next token will be switched * to JSXText via onToken. */ instance.extend("jsx_readString", function(jsxReadString) { return /** @this acorn.Parser */ function(quote) { var result = jsxReadString.call(this, quote); if (this.type === tt.string) { extra.jsxAttrValueToken = true; } return result; }; }); }; //------------------------------------------------------------------------------ // Tokenizer //------------------------------------------------------------------------------ /** * Tokenizes the given code. * @param {string} code The code to tokenize. * @param {Object} options Options defining how to tokenize. * @returns {Token[]} An array of tokens. * @throws {SyntaxError} If the input code is invalid. * @private */ function tokenize(code, options) { var toString, tokens, impliedStrict, translator = new TokenTranslator(tt, code); toString = String; if (typeof code !== "string" && !(code instanceof String)) { code = toString(code); } lookahead = null; // Options matching. options = assign({}, options); var acornOptions = { ecmaVersion: DEFAULT_ECMA_VERSION, plugins: { espree: true } }; resetExtra(); // Of course we collect tokens here. options.tokens = true; extra.tokens = []; extra.range = (typeof options.range === "boolean") && options.range; acornOptions.ranges = extra.range; extra.loc = (typeof options.loc === "boolean") && options.loc; acornOptions.locations = extra.loc; extra.comment = typeof options.comment === "boolean" && options.comment; if (extra.comment) { acornOptions.onComment = function() { var comment = convertAcornCommentToEsprimaComment.apply(this, arguments); extra.comments.push(comment); }; } extra.tolerant = typeof options.tolerant === "boolean" && options.tolerant; acornOptions.ecmaVersion = extra.ecmaVersion = normalizeEcmaVersion(options.ecmaVersion); // apply parsing flags if (options.ecmaFeatures && typeof options.ecmaFeatures === "object") { extra.ecmaFeatures = assign({}, options.ecmaFeatures); impliedStrict = extra.ecmaFeatures.impliedStrict; extra.ecmaFeatures.impliedStrict = typeof impliedStrict === "boolean" && impliedStrict; } try { var tokenizer = acorn.tokenizer(code, acornOptions); while ((lookahead = tokenizer.getToken()).type !== tt.eof) { translator.onToken(lookahead, extra); } // filterTokenLocation(); tokens = extra.tokens; if (extra.comment) { tokens.comments = extra.comments; } if (extra.tolerant) { tokens.errors = extra.errors; } } catch (e) { throw e; } return tokens; } //------------------------------------------------------------------------------ // Parser //------------------------------------------------------------------------------ /** * Converts an Acorn comment to a Esprima comment. * @param {boolean} block True if it's a block comment, false if not. * @param {string} text The text of the comment. * @param {int} start The index at which the comment starts. * @param {int} end The index at which the comment ends. * @param {Location} startLoc The location at which the comment starts. * @param {Location} endLoc The location at which the comment ends. * @returns {Object} The comment object. * @private */ function convertAcornCommentToEsprimaComment(block, text, start, end, startLoc, endLoc) { var comment = { type: block ? "Block" : "Line", value: text }; if (typeof start === "number") { comment.start = start; comment.end = end; comment.range = [start, end]; } if (typeof startLoc === "object") { comment.loc = { start: startLoc, end: endLoc }; } return comment; } /** * Parses the given code. * @param {string} code The code to tokenize. * @param {Object} options Options defining how to tokenize. * @returns {ASTNode} The "Program" AST node. * @throws {SyntaxError} If the input code is invalid. * @private */ function parse(code, options) { var program, toString = String, translator, impliedStrict, acornOptions = { ecmaVersion: DEFAULT_ECMA_VERSION, plugins: { espree: true } }; lastToken = null; if (typeof code !== "string" && !(code instanceof String)) { code = toString(code); } resetExtra(); commentAttachment.reset(); if (typeof options !== "undefined") { extra.range = (typeof options.range === "boolean") && options.range; extra.loc = (typeof options.loc === "boolean") && options.loc; extra.attachComment = (typeof options.attachComment === "boolean") && options.attachComment; if (extra.loc && options.source !== null && options.source !== undefined) { extra.source = toString(options.source); } if (typeof options.tokens === "boolean" && options.tokens) { extra.tokens = []; translator = new TokenTranslator(tt, code); } if (typeof options.comment === "boolean" && options.comment) { extra.comment = true; extra.comments = []; } if (typeof options.tolerant === "boolean" && options.tolerant) { extra.errors = []; } if (extra.attachComment) { extra.range = true; extra.comments = []; commentAttachment.reset(); } acornOptions.ecmaVersion = extra.ecmaVersion = normalizeEcmaVersion(options.ecmaVersion); if (options.sourceType === "module") { extra.isModule = true; // modules must be in 6 at least if (acornOptions.ecmaVersion < 6) { acornOptions.ecmaVersion = 6; extra.ecmaVersion = 6; } acornOptions.sourceType = "module"; } // apply parsing flags after sourceType to allow overriding if (options.ecmaFeatures && typeof options.ecmaFeatures === "object") { extra.ecmaFeatures = assign({}, options.ecmaFeatures); impliedStrict = extra.ecmaFeatures.impliedStrict; extra.ecmaFeatures.impliedStrict = typeof impliedStrict === "boolean" && impliedStrict; if (options.ecmaFeatures.globalReturn) { acornOptions.allowReturnOutsideFunction = true; } } acornOptions.onToken = function(token) { if (extra.tokens) { translator.onToken(token, extra); } if (token.type !== tt.eof) { lastToken = token; } }; if (extra.attachComment || extra.comment) { acornOptions.onComment = function() { var comment = convertAcornCommentToEsprimaComment.apply(this, arguments); extra.comments.push(comment); if (extra.attachComment) { commentAttachment.addComment(comment); } }; } if (extra.range) { acornOptions.ranges = true; } if (extra.loc) { acornOptions.locations = true; } if (extra.ecmaFeatures.jsx) { // Should process jsx plugin before espree plugin. acornOptions.plugins = { jsx: true, espree: true }; } } program = acorn.parse(code, acornOptions); program.sourceType = extra.isModule ? "module" : "script"; if (extra.comment || extra.attachComment) { program.comments = extra.comments; } if (extra.tokens) { program.tokens = extra.tokens; } /* * Adjust opening and closing position of program to match Esprima. * Acorn always starts programs at range 0 whereas Esprima starts at the * first AST node's start (the only real difference is when there's leading * whitespace or leading comments). Acorn also counts trailing whitespace * as part of the program whereas Esprima only counts up to the last token. */ if (program.range) { program.range[0] = program.body.length ? program.body[0].range[0] : program.range[0]; program.range[1] = lastToken ? lastToken.range[1] : program.range[1]; } if (program.loc) { program.loc.start = program.body.length ? program.body[0].loc.start : program.loc.start; program.loc.end = lastToken ? lastToken.loc.end : program.loc.end; } return program; } //------------------------------------------------------------------------------ // Public //------------------------------------------------------------------------------ exports.version = require("./package.json").version; exports.tokenize = tokenize; exports.parse = parse; // Deep copy. /* istanbul ignore next */ exports.Syntax = (function() { var name, types = {}; if (typeof Object.create === "function") { types = Object.create(null); } for (name in astNodeTypes) { if (astNodeTypes.hasOwnProperty(name)) { types[name] = astNodeTypes[name]; } } if (typeof Object.freeze === "function") { Object.freeze(types); } return types; }()); /* istanbul ignore next */ exports.VisitorKeys = (function() { var visitorKeys = require("./lib/visitor-keys"); var name, keys = {}; if (typeof Object.create === "function") { keys = Object.create(null); } for (name in visitorKeys) { if (visitorKeys.hasOwnProperty(name)) { keys[name] = visitorKeys[name]; } } if (typeof Object.freeze === "function") { Object.freeze(keys); } return keys; }());
/** * ag-grid - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components * @version v7.2.1 * @link http://www.ag-grid.com/ * @license MIT */ "use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; var dragAndDropService_1 = require("../dragAndDrop/dragAndDropService"); var context_1 = require("../context/context"); var moveColumnController_1 = require("./moveColumnController"); var column_1 = require("../entities/column"); var gridPanel_1 = require("../gridPanel/gridPanel"); var bodyDropPivotTarget_1 = require("./bodyDropPivotTarget"); var columnController_1 = require("../columnController/columnController"); var BodyDropTarget = (function () { function BodyDropTarget(pinned, eContainer) { this.pinned = pinned; this.eContainer = eContainer; } BodyDropTarget.prototype.getSecondaryContainers = function () { return this.eSecondaryContainers; }; BodyDropTarget.prototype.getContainer = function () { return this.eContainer; }; BodyDropTarget.prototype.init = function () { this.moveColumnController = new moveColumnController_1.MoveColumnController(this.pinned, this.eContainer); this.context.wireBean(this.moveColumnController); this.bodyDropPivotTarget = new bodyDropPivotTarget_1.BodyDropPivotTarget(this.pinned); this.context.wireBean(this.bodyDropPivotTarget); switch (this.pinned) { case column_1.Column.PINNED_LEFT: this.eSecondaryContainers = this.gridPanel.getDropTargetLeftContainers(); break; case column_1.Column.PINNED_RIGHT: this.eSecondaryContainers = this.gridPanel.getDropTargetPinnedRightContainers(); break; default: this.eSecondaryContainers = this.gridPanel.getDropTargetBodyContainers(); break; } this.dragAndDropService.addDropTarget(this); }; BodyDropTarget.prototype.getIconName = function () { return this.currentDropListener.getIconName(); }; // we want to use the bodyPivotTarget if the user is dragging columns in from the toolPanel // and we are in pivot mode, as it has to logic to set pivot/value/group on the columns when // dropped into the grid's body. BodyDropTarget.prototype.isUseBodyDropPivotTarget = function (draggingEvent) { // if not in pivot mode, then we never use the pivot drop target if (!this.columnController.isPivotMode()) { return false; } // otherwise we use the drop target if the column came from the toolPanel (ie not reordering) return draggingEvent.dragSource.type === dragAndDropService_1.DragSourceType.ToolPanel; }; BodyDropTarget.prototype.onDragEnter = function (draggingEvent) { // we pick the drop listener depending on whether we are in pivot mode are not. if we are // in pivot mode, then dropping cols changes the row group, pivot, value stats. otherwise // we change visibility state and position. // if (this.columnController.isPivotMode()) { var useBodyDropPivotTarget = this.isUseBodyDropPivotTarget(draggingEvent); if (useBodyDropPivotTarget) { this.currentDropListener = this.bodyDropPivotTarget; } else { this.currentDropListener = this.moveColumnController; } this.currentDropListener.onDragEnter(draggingEvent); }; BodyDropTarget.prototype.onDragLeave = function (params) { this.currentDropListener.onDragLeave(params); }; BodyDropTarget.prototype.onDragging = function (params) { this.currentDropListener.onDragging(params); }; BodyDropTarget.prototype.onDragStop = function (params) { this.currentDropListener.onDragStop(params); }; __decorate([ context_1.Autowired('context'), __metadata('design:type', context_1.Context) ], BodyDropTarget.prototype, "context", void 0); __decorate([ context_1.Autowired('gridPanel'), __metadata('design:type', gridPanel_1.GridPanel) ], BodyDropTarget.prototype, "gridPanel", void 0); __decorate([ context_1.Autowired('dragAndDropService'), __metadata('design:type', dragAndDropService_1.DragAndDropService) ], BodyDropTarget.prototype, "dragAndDropService", void 0); __decorate([ context_1.Autowired('columnController'), __metadata('design:type', columnController_1.ColumnController) ], BodyDropTarget.prototype, "columnController", void 0); __decorate([ context_1.PostConstruct, __metadata('design:type', Function), __metadata('design:paramtypes', []), __metadata('design:returntype', void 0) ], BodyDropTarget.prototype, "init", null); return BodyDropTarget; }()); exports.BodyDropTarget = BodyDropTarget;
'use strict'; if (mejs.i18n.ca !== undefined) { mejs.i18n.ca['mejs.speed-rate'] = 'Velocitat'; } if (mejs.i18n.cs !== undefined) { mejs.i18n.cs['mejs.speed-rate'] = 'Rychlost'; } if (mejs.i18n.de !== undefined) { mejs.i18n.de['mejs.speed-rate'] = 'Geschwindigkeitsrate'; } if (mejs.i18n.es !== undefined) { mejs.i18n.es['mejs.speed-rate'] = 'Velocidad'; } if (mejs.i18n.fa !== undefined) { mejs.i18n.fa['mejs.speed-rate'] = 'نرخ سرعت'; } if (mejs.i18n.fr !== undefined) { mejs.i18n.fr['mejs.speed-rate'] = 'Vitesse'; } if (mejs.i18n.hr !== undefined) { mejs.i18n.hr['mejs.speed-rate'] = 'Brzina reprodukcije'; } if (mejs.i18n.hu !== undefined) { mejs.i18n.hu['mejs.speed-rate'] = 'Sebesség'; } if (mejs.i18n.it !== undefined) { mejs.i18n.it['mejs.speed-rate'] = 'Velocità'; } if (mejs.i18n.ja !== undefined) { mejs.i18n.ja['mejs.speed-rate'] = '高速'; } if (mejs.i18n.ko !== undefined) { mejs.i18n.ko['mejs.speed-rate'] = '속도 속도'; } if (mejs.i18n.nl !== undefined) { mejs.i18n.nl['mejs.speed-rate'] = 'Snelheidsgraad'; } if (mejs.i18n.pl !== undefined) { mejs.i18n.pl['mejs.speed-rate'] = 'Prędkość'; } if (mejs.i18n.pt !== undefined) { mejs.i18n.pt['mejs.speed-rate'] = 'Taxa de velocidade'; } if (mejs.i18n.ro !== undefined) { mejs.i18n.ro['mejs.speed-rate'] = 'Viteză de viteză'; } if (mejs.i18n.ru !== undefined) { mejs.i18n.ru['mejs.speed-rate'] = 'Скорость воспроизведения'; } if (mejs.i18n.sk !== undefined) { mejs.i18n.sk['mejs.speed-rate'] = 'Rýchlosť'; } if (mejs.i18n.sv !== undefined) { mejs.i18n.sv['mejs.speed-rate'] = 'Hastighet'; } if (mejs.i18n.uk !== undefined) { mejs.i18n.uk['mejs.speed-rate'] = 'Швидкість відтворення'; } if (mejs.i18n.zh !== undefined) { mejs.i18n.zh['mejs.speed-rate'] = '速度'; } if (mejs.i18n['zh-CN'] !== undefined) { mejs.i18n['zh-CN']['mejs.speed-rate'] = '速度'; }
Ext.define('KitchenSink.view.button.LinkButtons', { extend: 'Ext.Container', xtype: 'link-buttons', layout: 'vbox', //<example> exampleDescription: [ '<p>This example shows how to create buttons that act as a link and navigate to ', 'a url when clicked. This is achieved using the <code>href</code> config.</p>' ], themes: { classic: { width: 420, iconSmall: 'resources/images/icons/add16.gif', iconMedium: 'resources/images/icons/add24.gif', iconLarge: 'resources/images/icons/add.gif' }, access: { width: 470 }, neptune: { width: 475, glyph: 72 } }, //</example> initComponent: function() { Ext.apply(this, { width: this.themeInfo.width, items: [{ xtype: 'checkbox', boxLabel: 'disabled', margin: '0 0 0 10', listeners: { change: this.toggleDisabled, scope: this } }, { xtype: 'container', layout: { type: 'table', columns: 4, tdAttrs: { style: 'padding: 5px 10px;' } }, defaults: { href: 'http://www.sencha.com/' }, items: [{ xtype: 'component', html: 'Text Only' }, { xtype: 'button', text: 'Small' }, { xtype: 'button', text: 'Medium', scale: 'medium' }, { xtype: 'button', text: 'Large', scale: 'large' }, { xtype: 'component', html: 'Icon Only' }, { icon: this.themeInfo.iconSmall, glyph: this.themeInfo.glyph, xtype: 'button' }, { xtype: 'button', icon: this.themeInfo.iconMedium, glyph: this.themeInfo.glyph, scale: 'medium' }, { xtype: 'button', icon: this.themeInfo.iconLarge, glyph: this.themeInfo.glyph, scale: 'large' }, { xtype: 'component', html: 'Icon and Text (left)' }, { xtype: 'button', icon: this.themeInfo.iconSmall, glyph: this.themeInfo.glyph, text: 'Small' }, { xtype: 'button', icon: this.themeInfo.iconMedium, glyph: this.themeInfo.glyph, text: 'Medium', scale: 'medium' }, { xtype: 'button', icon: this.themeInfo.iconLarge, glyph: this.themeInfo.glyph, text: 'Large', scale: 'large' }, { xtype: 'component', html: 'Icon and Text (top)' }, { xtype: 'button', icon: this.themeInfo.iconSmall, glyph: this.themeInfo.glyph, text: 'Small', iconAlign: 'top' }, { xtype: 'button', icon: this.themeInfo.iconMedium, glyph: this.themeInfo.glyph, text: 'Medium', scale: 'medium', iconAlign: 'top' }, { xtype: 'button', icon: this.themeInfo.iconLarge, glyph: this.themeInfo.glyph, text: 'Large', scale: 'large', iconAlign: 'top' }, { xtype: 'component', html: 'Icon and Text (right)' }, { xtype: 'button', icon: this.themeInfo.iconSmall, glyph: this.themeInfo.glyph, text: 'Small', iconAlign: 'right' }, { xtype: 'button', icon: this.themeInfo.iconMedium, glyph: this.themeInfo.glyph, text: 'Medium', scale: 'medium', iconAlign: 'right' }, { xtype: 'button', icon: this.themeInfo.iconLarge, glyph: this.themeInfo.glyph, text: 'Large', scale: 'large', iconAlign: 'right' }, { xtype: 'component', html: 'Icon and Text (bottom)' }, { xtype: 'button', icon: this.themeInfo.iconSmall, glyph: this.themeInfo.glyph, text: 'Small', iconAlign: 'bottom' }, { xtype: 'button', icon: this.themeInfo.iconMedium, glyph: this.themeInfo.glyph, text: 'Medium', scale: 'medium', iconAlign: 'bottom' }, { xtype: 'button', icon: this.themeInfo.iconLarge, glyph: this.themeInfo.glyph, text: 'Large', scale: 'large', iconAlign: 'bottom' }] }] }); this.callParent(); }, toggleDisabled: function(checkbox, newValue, oldValue) { var toggleFn = newValue ? 'disable' : 'enable'; Ext.each(this.query('button'), function(item) { item[toggleFn](); }); } });
(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);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){ /** * MUI CSS/JS main module * @module main */ (function(win) { 'use strict'; // return if library has been loaded already if (win._muiLoadedJS) return; else win._muiLoadedJS = true; // load dependencies var jqLite = require('src/js/lib/jqLite'), dropdown = require('src/js/dropdown'), overlay = require('src/js/overlay'), ripple = require('src/js/ripple'), select = require('src/js/select'), tabs = require('src/js/tabs'), textfield = require('src/js/textfield'); // expose api win.mui = { overlay: overlay, tabs: tabs.api }; // init libraries jqLite.ready(function() { textfield.initListeners(); select.initListeners(); ripple.initListeners(); dropdown.initListeners(); tabs.initListeners(); }); })(window); },{"src/js/dropdown":7,"src/js/lib/jqLite":8,"src/js/overlay":9,"src/js/ripple":10,"src/js/select":11,"src/js/tabs":12,"src/js/textfield":13}],2:[function(require,module,exports){ /** * MUI config module * @module config */ /** Define module API */ module.exports = { /** Use debug mode */ debug: true }; },{}],3:[function(require,module,exports){ /** * MUI CSS/JS animation helper module * @module lib/animationHelpers */ 'use strict'; var jqLite = require('./jqLite'), util = require('./util'), animationEvents = 'animationstart mozAnimationStart webkitAnimationStart', animationCallbacks = {}; /** * Register callbacks * @param {String} name - The animation name * @param {Function} callbackFn = The callback function */ function onAnimationStartFn(name, callbackFn) { // get/set callback function var callbacks = animationCallbacks[name]; if (!callbacks) callbacks = animationCallbacks[name] = []; callbacks.push(callbackFn); // initialize listeners if (!this.init) { // add css classes loadCss(); // add listener jqLite.on(document, animationEvents, animationStartHandler, true); // set flag this.init = true; } } /** * Animation start handler * @param {Event} ev - The DOM event */ function animationStartHandler(ev) { var callbacks = animationCallbacks[ev.animationName] || [], i = callbacks.length; // exit if a callback hasn't been registered if (!i) return; // stop other callbacks from firing ev.stopImmediatePropagation(); // iterate through callbacks while (i--) callbacks[i](ev); } /** * Load animation css */ function loadCss() { // define rules var rules = [ ['.mui-btn', 'mui-btn-inserted'], ['[data-mui-toggle="dropdown"]', 'mui-dropdown-inserted'], [ '.mui-btn[data-mui-toggle="dropdown"]', 'mui-btn-inserted,mui-dropdown-inserted' ], ['[data-mui-toggle="tab"]', 'mui-tab-inserted'], ['.mui-textfield > input', 'mui-textfield-inserted'], ['.mui-textfield > textarea', 'mui-textfield-inserted'], ['.mui-select > select', 'mui-select-inserted'], ['.mui-select > select ~ .mui-event-trigger', 'mui-node-inserted'], ['.mui-select > select:disabled ~ .mui-event-trigger', 'mui-node-disabled'] ]; // build css var css = '', rule; for (var i=0, m=rules.length; i < m; i++) { rule = rules[i]; // use an IE-only property to trigger animation cross-browser css += '@keyframes ' + rule[1] + '{from{-ms-zoom:1;}to{-ms-zoom:1;}}'; css += rule[0]; css += '{animation-duration:0.0001s;animation-name:' + rule[1] + ';}'; } // add CSS to DOM util.loadStyle(css); } /** * Define module API */ module.exports = { animationEvents: animationEvents, onAnimationStart: onAnimationStartFn } },{"./jqLite":5,"./util":6}],4:[function(require,module,exports){ /** * MUI CSS/JS form helpers module * @module lib/forms.py */ 'use strict'; var wrapperPadding = 15, // from CSS inputHeight = 32, // from CSS rowHeight = 42, // from CSS menuPadding = 8; // from CSS /** * Menu position/size/scroll helper * @returns {Object} Object with keys 'height', 'top', 'scrollTop' */ function getMenuPositionalCSSFn(wrapperEl, numRows, selectedRow) { var viewHeight = document.documentElement.clientHeight; // determine 'height' var h = numRows * rowHeight + 2 * menuPadding, height = Math.min(h, viewHeight); // determine 'top' var top, initTop, minTop, maxTop; initTop = (menuPadding + rowHeight) - (wrapperPadding + inputHeight); initTop -= selectedRow * rowHeight; minTop = -1 * wrapperEl.getBoundingClientRect().top; maxTop = (viewHeight - height) + minTop; top = Math.min(Math.max(initTop, minTop), maxTop); // determine 'scrollTop' var scrollTop = 0, scrollIdeal, scrollMax; if (h > viewHeight) { scrollIdeal = (menuPadding + (selectedRow + 1) * rowHeight) - (-1 * top + wrapperPadding + inputHeight); scrollMax = numRows * rowHeight + 2 * menuPadding - height; scrollTop = Math.min(scrollIdeal, scrollMax); } return { 'height': height + 'px', 'top': top + 'px', 'scrollTop': scrollTop }; } /** Define module API */ module.exports = { getMenuPositionalCSS: getMenuPositionalCSSFn }; },{}],5:[function(require,module,exports){ /** * MUI CSS/JS jqLite module * @module lib/jqLite */ 'use strict'; /** * Add a class to an element. * @param {Element} element - The DOM element. * @param {string} cssClasses - Space separated list of class names. */ function jqLiteAddClass(element, cssClasses) { if (!cssClasses || !element.setAttribute) return; var existingClasses = _getExistingClasses(element), splitClasses = cssClasses.split(' '), cssClass; for (var i=0; i < splitClasses.length; i++) { cssClass = splitClasses[i].trim(); if (existingClasses.indexOf(' ' + cssClass + ' ') === -1) { existingClasses += cssClass + ' '; } } element.setAttribute('class', existingClasses.trim()); } /** * Get or set CSS properties. * @param {Element} element - The DOM element. * @param {string} [name] - The property name. * @param {string} [value] - The property value. */ function jqLiteCss(element, name, value) { // Return full style object if (name === undefined) { return getComputedStyle(element); } var nameType = jqLiteType(name); // Set multiple values if (nameType === 'object') { for (var key in name) element.style[_camelCase(key)] = name[key]; return; } // Set a single value if (nameType === 'string' && value !== undefined) { element.style[_camelCase(name)] = value; } var styleObj = getComputedStyle(element), isArray = (jqLiteType(name) === 'array'); // Read single value if (!isArray) return _getCurrCssProp(element, name, styleObj); // Read multiple values var outObj = {}, key; for (var i=0; i < name.length; i++) { key = name[i]; outObj[key] = _getCurrCssProp(element, key, styleObj); } return outObj; } /** * Check if element has class. * @param {Element} element - The DOM element. * @param {string} cls - The class name string. */ function jqLiteHasClass(element, cls) { if (!cls || !element.getAttribute) return false; return (_getExistingClasses(element).indexOf(' ' + cls + ' ') > -1); } /** * Return the type of a variable. * @param {} somevar - The JavaScript variable. */ function jqLiteType(somevar) { // handle undefined if (somevar === undefined) return 'undefined'; // handle others (of type [object <Type>]) var typeStr = Object.prototype.toString.call(somevar); if (typeStr.indexOf('[object ') === 0) { return typeStr.slice(8, -1).toLowerCase(); } else { throw new Error("MUI: Could not understand type: " + typeStr); } } /** * Attach an event handler to a DOM element * @param {Element} element - The DOM element. * @param {string} events - Space separated event names. * @param {Function} callback - The callback function. * @param {Boolean} useCapture - Use capture flag. */ function jqLiteOn(element, events, callback, useCapture) { useCapture = (useCapture === undefined) ? false : useCapture; var cache = element._muiEventCache = element._muiEventCache || {}; events.split(' ').map(function(event) { // add to DOM element.addEventListener(event, callback, useCapture); // add to cache cache[event] = cache[event] || []; cache[event].push([callback, useCapture]); }); } /** * Remove an event handler from a DOM element * @param {Element} element - The DOM element. * @param {string} events - Space separated event names. * @param {Function} callback - The callback function. * @param {Boolean} useCapture - Use capture flag. */ function jqLiteOff(element, events, callback, useCapture) { useCapture = (useCapture === undefined) ? false : useCapture; // remove from cache var cache = element._muiEventCache = element._muiEventCache || {}, argsList, args, i; events.split(' ').map(function(event) { argsList = cache[event] || []; i = argsList.length; while (i--) { args = argsList[i]; // remove all events if callback is undefined if (callback === undefined || (args[0] === callback && args[1] === useCapture)) { // remove from cache argsList.splice(i, 1); // remove from DOM element.removeEventListener(event, args[0], args[1]); } } }); } /** * Attach an event hander which will only execute once per element per event * @param {Element} element - The DOM element. * @param {string} events - Space separated event names. * @param {Function} callback - The callback function. * @param {Boolean} useCapture - Use capture flag. */ function jqLiteOne(element, events, callback, useCapture) { events.split(' ').map(function(event) { jqLiteOn(element, event, function onFn(ev) { // execute callback if (callback) callback.apply(this, arguments); // remove wrapper jqLiteOff(element, event, onFn, useCapture); }, useCapture); }); } /** * Get or set horizontal scroll position * @param {Element} element - The DOM element * @param {number} [value] - The scroll position */ function jqLiteScrollLeft(element, value) { var win = window; // get if (value === undefined) { if (element === win) { var docEl = document.documentElement; return (win.pageXOffset || docEl.scrollLeft) - (docEl.clientLeft || 0); } else { return element.scrollLeft; } } // set if (element === win) win.scrollTo(value, jqLiteScrollTop(win)); else element.scrollLeft = value; } /** * Get or set vertical scroll position * @param {Element} element - The DOM element * @param {number} value - The scroll position */ function jqLiteScrollTop(element, value) { var win = window; // get if (value === undefined) { if (element === win) { var docEl = document.documentElement; return (win.pageYOffset || docEl.scrollTop) - (docEl.clientTop || 0); } else { return element.scrollTop; } } // set if (element === win) win.scrollTo(jqLiteScrollLeft(win), value); else element.scrollTop = value; } /** * Return object representing top/left offset and element height/width. * @param {Element} element - The DOM element. */ function jqLiteOffset(element) { var win = window, rect = element.getBoundingClientRect(), scrollTop = jqLiteScrollTop(win), scrollLeft = jqLiteScrollLeft(win); return { top: rect.top + scrollTop, left: rect.left + scrollLeft, height: rect.height, width: rect.width }; } /** * Attach a callback to the DOM ready event listener * @param {Function} fn - The callback function. */ function jqLiteReady(fn) { var done = false, top = true, doc = document, win = doc.defaultView, root = doc.documentElement, add = doc.addEventListener ? 'addEventListener' : 'attachEvent', rem = doc.addEventListener ? 'removeEventListener' : 'detachEvent', pre = doc.addEventListener ? '' : 'on'; var init = function(e) { if (e.type == 'readystatechange' && doc.readyState != 'complete') { return; } (e.type == 'load' ? win : doc)[rem](pre + e.type, init, false); if (!done && (done = true)) fn.call(win, e.type || e); }; var poll = function() { try { root.doScroll('left'); } catch(e) { setTimeout(poll, 50); return; } init('poll'); }; if (doc.readyState == 'complete') { fn.call(win, 'lazy'); } else { if (doc.createEventObject && root.doScroll) { try { top = !win.frameElement; } catch(e) { } if (top) poll(); } doc[add](pre + 'DOMContentLoaded', init, false); doc[add](pre + 'readystatechange', init, false); win[add](pre + 'load', init, false); } } /** * Remove classes from a DOM element * @param {Element} element - The DOM element. * @param {string} cssClasses - Space separated list of class names. */ function jqLiteRemoveClass(element, cssClasses) { if (!cssClasses || !element.setAttribute) return; var existingClasses = _getExistingClasses(element), splitClasses = cssClasses.split(' '), cssClass; for (var i=0; i < splitClasses.length; i++) { cssClass = splitClasses[i].trim(); while (existingClasses.indexOf(' ' + cssClass + ' ') >= 0) { existingClasses = existingClasses.replace(' ' + cssClass + ' ', ' '); } } element.setAttribute('class', existingClasses.trim()); } // ------------------------------ // Utilities // ------------------------------ var SPECIAL_CHARS_REGEXP = /([\:\-\_]+(.))/g, MOZ_HACK_REGEXP = /^moz([A-Z])/, ESCAPE_REGEXP = /([.*+?^=!:${}()|\[\]\/\\])/g; function _getExistingClasses(element) { var classes = (element.getAttribute('class') || '').replace(/[\n\t]/g, ''); return ' ' + classes + ' '; } function _camelCase(name) { return name. replace(SPECIAL_CHARS_REGEXP, function(_, separator, letter, offset) { return offset ? letter.toUpperCase() : letter; }). replace(MOZ_HACK_REGEXP, 'Moz$1'); } function _escapeRegExp(string) { return string.replace(ESCAPE_REGEXP, "\\$1"); } function _getCurrCssProp(elem, name, computed) { var ret; // try computed style ret = computed.getPropertyValue(name); // try style attribute (if element is not attached to document) if (ret === '' && !elem.ownerDocument) ret = elem.style[_camelCase(name)]; return ret; } /** * Module API */ module.exports = { /** Add classes */ addClass: jqLiteAddClass, /** Get or set CSS properties */ css: jqLiteCss, /** Check for class */ hasClass: jqLiteHasClass, /** Remove event handlers */ off: jqLiteOff, /** Return offset values */ offset: jqLiteOffset, /** Add event handlers */ on: jqLiteOn, /** Add an execute-once event handler */ one: jqLiteOne, /** DOM ready event handler */ ready: jqLiteReady, /** Remove classes */ removeClass: jqLiteRemoveClass, /** Check JavaScript variable instance type */ type: jqLiteType, /** Get or set horizontal scroll position */ scrollLeft: jqLiteScrollLeft, /** Get or set vertical scroll position */ scrollTop: jqLiteScrollTop }; },{}],6:[function(require,module,exports){ /** * MUI CSS/JS utilities module * @module lib/util */ 'use strict'; var config = require('../config'), jqLite = require('./jqLite'), scrollLock = 0, scrollLockCls = 'mui-scroll-lock', scrollStyleEl, scrollEventHandler, _supportsPointerEvents; scrollEventHandler = function(ev) { // stop propagation on window scroll events if (!ev.target.tagName) ev.stopImmediatePropagation(); } /** * Logging function */ function logFn() { var win = window; if (config.debug && typeof win.console !== "undefined") { try { win.console.log.apply(win.console, arguments); } catch (a) { var e = Array.prototype.slice.call(arguments); win.console.log(e.join("\n")); } } } /** * Load CSS text in new stylesheet * @param {string} cssText - The css text. */ function loadStyleFn(cssText) { var doc = document, head; // copied from jQuery head = doc.head || doc.getElementsByTagName('head')[0] || doc.documentElement; var e = doc.createElement('style'); e.type = 'text/css'; if (e.styleSheet) e.styleSheet.cssText = cssText; else e.appendChild(doc.createTextNode(cssText)); // add to document head.insertBefore(e, head.firstChild); return e; } /** * Raise an error * @param {string} msg - The error message. */ function raiseErrorFn(msg, useConsole) { if (useConsole) { if (typeof console !== 'undefined') console.error('MUI Warning: ' + msg); } else { throw new Error('MUI: ' + msg); } } /** * Convert Classname object, with class as key and true/false as value, to an * class string. * @param {Object} classes The classes * @return {String} class string */ function classNamesFn(classes) { var cs = ''; for (var i in classes) { cs += (classes[i]) ? i + ' ' : ''; } return cs.trim(); } /** * Check if client supports pointer events. */ function supportsPointerEventsFn() { // check cache if (_supportsPointerEvents !== undefined) return _supportsPointerEvents; var element = document.createElement('x'); element.style.cssText = 'pointer-events:auto'; _supportsPointerEvents = (element.style.pointerEvents === 'auto'); return _supportsPointerEvents; } /** * Create callback closure. * @param {Object} instance - The object instance. * @param {String} funcName - The name of the callback function. */ function callbackFn(instance, funcName) { return function() {instance[funcName].apply(instance, arguments);}; } /** * Dispatch event. * @param {Element} element - The DOM element. * @param {String} eventType - The event type. * @param {Boolean} bubbles=true - If true, event bubbles. * @param {Boolean} cancelable=true = If true, event is cancelable * @param {Object} [data] - Data to add to event object */ function dispatchEventFn(element, eventType, bubbles, cancelable, data) { var ev = document.createEvent('HTMLEvents'), bubbles = (bubbles !== undefined) ? bubbles : true, cancelable = (cancelable !== undefined) ? cancelable : true, k; ev.initEvent(eventType, bubbles, cancelable); // add data to event object if (data) for (k in data) ev[k] = data[k]; // dispatch if (element) element.dispatchEvent(ev); return ev; } /** * Turn on window scroll lock. */ function enableScrollLockFn() { // increment counter scrollLock += 1; // add lock if (scrollLock === 1) { var htmlEl = document.documentElement, top = jqLite.scrollTop(window), left = jqLite.scrollLeft(window), cssProps, cssStr; // define scroll lock class dynamically cssProps = [ 'position:fixed', 'top:' + -top + 'px', 'right:0', 'bottom:0', 'left:' + -left + 'px' ]; // scrollbar-y if (htmlEl.scrollHeight > htmlEl.clientHeight) { cssProps.push('overflow-y:scroll'); } // scrollbar-x if (htmlEl.scrollWidth > htmlEl.clientWidth) { cssProps.push('overflow-x:scroll'); } // define css class dynamically cssStr = '.' + scrollLockCls + '{'; cssStr += cssProps.join(' !important;') + ' !important;}'; scrollStyleEl = loadStyleFn(cssStr); // cancel 'scroll' event listener callbacks jqLite.on(window, 'scroll', scrollEventHandler, true); // add scroll lock jqLite.addClass(htmlEl, scrollLockCls); } } /** * Turn off window scroll lock. * @param {Boolean} resetPos - Reset scroll position to original value. */ function disableScrollLockFn(resetPos) { // ignore if (scrollLock === 0) return; // decrement counter scrollLock -= 1; // remove lock if (scrollLock === 0) { var htmlEl = document.documentElement, top = parseInt(jqLite.css(htmlEl, 'top')), left = parseInt(jqLite.css(htmlEl, 'left')); // remove scroll lock and delete style element jqLite.removeClass(htmlEl, scrollLockCls); scrollStyleEl.parentNode.removeChild(scrollStyleEl); // restore scroll position window.scrollTo(-left, -top); // restore scroll event listeners jqLite.off(window, 'scroll', scrollEventHandler, true); } } /** * requestAnimationFrame polyfilled * @param {Function} callback - The callback function */ function requestAnimationFrameFn(callback) { var fn = window.requestAnimationFrame; if (fn) fn(callback); else setTimeout(callback, 0); } /** * Define the module API */ module.exports = { /** Create callback closures */ callback: callbackFn, /** Classnames object to string */ classNames: classNamesFn, /** Disable scroll lock */ disableScrollLock: disableScrollLockFn, /** Dispatch event */ dispatchEvent: dispatchEventFn, /** Enable scroll lock */ enableScrollLock: enableScrollLockFn, /** Log messages to the console when debug is turned on */ log: logFn, /** Load CSS text as new stylesheet */ loadStyle: loadStyleFn, /** Raise MUI error */ raiseError: raiseErrorFn, /** Request animation frame */ requestAnimationFrame: requestAnimationFrameFn, /** Support Pointer Events check */ supportsPointerEvents: supportsPointerEventsFn }; },{"../config":2,"./jqLite":5}],7:[function(require,module,exports){ /** * MUI CSS/JS dropdown module * @module dropdowns */ 'use strict'; var jqLite = require('./lib/jqLite'), util = require('./lib/util'), animationHelpers = require('./lib/animationHelpers'), attrKey = 'data-mui-toggle', attrSelector = '[data-mui-toggle="dropdown"]', openClass = 'mui--is-open', menuClass = 'mui-dropdown__menu'; /** * Initialize toggle element. * @param {Element} toggleEl - The toggle element. */ function initialize(toggleEl) { // check flag if (toggleEl._muiDropdown === true) return; else toggleEl._muiDropdown = true; // use type "button" to prevent form submission by default var tagName = toggleEl.tagName; if ((tagName === 'INPUT' || tagName === 'BUTTON') && !toggleEl.hasAttribute('type')) { toggleEl.type = 'button'; } // attach click handler jqLite.on(toggleEl, 'click', clickHandler); } /** * Handle click events on dropdown toggle element. * @param {Event} ev - The DOM event */ function clickHandler(ev) { // only left clicks if (ev.button !== 0) return; var toggleEl = this; // exit if toggle button is disabled if (toggleEl.getAttribute('disabled') !== null) return; // toggle dropdown toggleDropdown(toggleEl); } /** * Toggle the dropdown. * @param {Element} toggleEl - The dropdown toggle element. */ function toggleDropdown(toggleEl) { var wrapperEl = toggleEl.parentNode, menuEl = toggleEl.nextElementSibling, doc = wrapperEl.ownerDocument; // exit if no menu element if (!menuEl || !jqLite.hasClass(menuEl, menuClass)) { return util.raiseError('Dropdown menu element not found'); } // method to close dropdown function closeDropdownFn() { jqLite.removeClass(menuEl, openClass); // remove event handlers jqLite.off(doc, 'click', closeDropdownFn); } // method to open dropdown function openDropdownFn() { // position menu element below toggle button var wrapperRect = wrapperEl.getBoundingClientRect(), toggleRect = toggleEl.getBoundingClientRect(); var top = toggleRect.top - wrapperRect.top + toggleRect.height; jqLite.css(menuEl, 'top', top + 'px'); // add open class to wrapper jqLite.addClass(menuEl, openClass); // close dropdown when user clicks outside of menu setTimeout(function() {jqLite.on(doc, 'click', closeDropdownFn);}, 0); } // toggle dropdown if (jqLite.hasClass(menuEl, openClass)) closeDropdownFn(); else openDropdownFn(); } /** Define module API */ module.exports = { /** Initialize module listeners */ initListeners: function() { // markup elements available when method is called var elList = document.querySelectorAll(attrSelector), i = elList.length; while (i--) {initialize(elList[i]);} // listen for new elements animationHelpers.onAnimationStart('mui-dropdown-inserted', function(ev) { initialize(ev.target); }); } }; },{"./lib/animationHelpers":3,"./lib/jqLite":5,"./lib/util":6}],8:[function(require,module,exports){ module.exports=require(5) },{}],9:[function(require,module,exports){ /** * MUI CSS/JS overlay module * @module overlay */ 'use strict'; var util = require('./lib/util'), jqLite = require('./lib/jqLite'), overlayId = 'mui-overlay', bodyClass = 'mui--overflow-hidden', iosRegex = /(iPad|iPhone|iPod)/g, activeElement; /** * Turn overlay on/off. * @param {string} action - Turn overlay "on"/"off". * @param {object} [options] * @config {boolean} [keyboard] - If true, close when escape key is pressed. * @config {boolean} [static] - If false, close when backdrop is clicked. * @config {Function} [onclose] - Callback function to execute on close * @param {Element} [childElement] - Child element to add to overlay. */ function overlayFn(action) { var overlayEl; if (action === 'on') { // extract arguments var arg, options, childElement; // pull options and childElement from arguments for (var i=arguments.length - 1; i > 0; i--) { arg = arguments[i]; if (jqLite.type(arg) === 'object') options = arg; if (arg instanceof Element && arg.nodeType === 1) childElement = arg; } // option defaults options = options || {}; if (options.keyboard === undefined) options.keyboard = true; if (options.static === undefined) options.static = false; // execute method overlayEl = overlayOn(options, childElement); } else if (action === 'off') { overlayEl = overlayOff(); } else { // raise error util.raiseError("Expecting 'on' or 'off'"); } return overlayEl; } /** * Turn on overlay. * @param {object} options - Overlay options. * @param {Element} childElement - The child element. */ function overlayOn(options, childElement) { var doc = document, bodyEl = doc.body, overlayEl = doc.getElementById(overlayId); // cache activeElement if (doc.activeElement) activeElement = doc.activeElement; // add overlay util.enableScrollLock(); if (!overlayEl) { // create overlayEl overlayEl = doc.createElement('div'); overlayEl.setAttribute('id', overlayId); overlayEl.setAttribute('tabindex', '-1'); // add child element if (childElement) overlayEl.appendChild(childElement); bodyEl.appendChild(overlayEl); } else { // remove existing children while (overlayEl.firstChild) overlayEl.removeChild(overlayEl.firstChild); // add child element if (childElement) overlayEl.appendChild(childElement); } // iOS bugfix if (iosRegex.test(navigator.userAgent)) { jqLite.css(overlayEl, 'cursor', 'pointer'); } // handle options if (options.keyboard) addKeyupHandler(); else removeKeyupHandler(); if (options.static) removeClickHandler(overlayEl); else addClickHandler(overlayEl); // attach options overlayEl.muiOptions = options; // focus overlay element overlayEl.focus(); return overlayEl; } /** * Turn off overlay. */ function overlayOff() { var overlayEl = document.getElementById(overlayId), callbackFn; if (overlayEl) { // remove children while (overlayEl.firstChild) overlayEl.removeChild(overlayEl.firstChild); // remove overlay element overlayEl.parentNode.removeChild(overlayEl); // callback reference callbackFn = overlayEl.muiOptions.onclose; // remove click handler removeClickHandler(overlayEl); } util.disableScrollLock(); // remove keyup handler removeKeyupHandler(); // return focus to activeElement if (activeElement) activeElement.focus(); // execute callback if (callbackFn) callbackFn(); return overlayEl; } /** * Add keyup handler. */ function addKeyupHandler() { jqLite.on(document, 'keyup', onKeyup); } /** * Remove keyup handler. */ function removeKeyupHandler() { jqLite.off(document, 'keyup', onKeyup); } /** * Teardown overlay when escape key is pressed. */ function onKeyup(ev) { if (ev.keyCode === 27) overlayOff(); } /** * Add click handler. */ function addClickHandler(overlayEl) { jqLite.on(overlayEl, 'click', onClick); } /** * Remove click handler. */ function removeClickHandler(overlayEl) { jqLite.off(overlayEl, 'click', onClick); } /** * Teardown overlay when backdrop is clicked. */ function onClick(ev) { if (ev.target.id === overlayId) overlayOff(); } /** Define module API */ module.exports = overlayFn; },{"./lib/jqLite":5,"./lib/util":6}],10:[function(require,module,exports){ /** * MUI CSS/JS ripple module * @module ripple */ 'use strict'; var jqLite = require('./lib/jqLite'), util = require('./lib/util'), animationHelpers = require('./lib/animationHelpers'), supportsTouch = 'ontouchstart' in document.documentElement, mouseDownEvents = (supportsTouch) ? 'touchstart' : 'mousedown', mouseUpEvents = (supportsTouch) ? 'touchend' : 'mouseup mouseleave'; /** * Add ripple effects to button element. * @param {Element} buttonEl - The button element. */ function initialize(buttonEl) { // check flag if (buttonEl._muiRipple === true) return; else buttonEl._muiRipple = true; // exit if element is INPUT (doesn't support absolute positioned children) if (buttonEl.tagName === 'INPUT') return; // add ripple container (to avoid https://github.com/muicss/mui/issues/169) var el = document.createElement('span'); el.className = 'mui-btn__ripple-container'; el.innerHTML = '<span class="mui-ripple"></span>'; buttonEl.appendChild(el); // cache reference to ripple element buttonEl._rippleEl = el.children[0]; // attach event handler jqLite.on(buttonEl, mouseDownEvents, mouseDownHandler); } /** * MouseDown Event handler. * @param {Event} ev - The DOM event */ function mouseDownHandler(ev) { // only left clicks if (ev.type === 'mousedown' && ev.button !== 0) return; var buttonEl = this, rippleEl = buttonEl._rippleEl; // exit if button is disabled if (buttonEl.disabled) return; // add mouseup handler on first-click if (!rippleEl._init) { jqLite.on(buttonEl, mouseUpEvents, mouseUpHandler); rippleEl._init = true; } // get ripple element offset values and (x, y) position of click var offset = jqLite.offset(buttonEl), clickEv = (ev.type === 'touchstart') ? ev.touches[0] : ev, xPos = Math.round(clickEv.pageX - offset.left), yPos = Math.round(clickEv.pageY - offset.top), diameter; // calculate diameter diameter = Math.sqrt(offset.height * offset.height + offset.width * offset.width) * 2 + 2 + 'px'; // css transform var tEnd = 'translate(-50%, -50%) translate(' + xPos + 'px,' + yPos + 'px)', tStart = tEnd + ' scale(0.0001, 0.0001)'; // set position and initial scale jqLite.css(rippleEl, { width: diameter, height: diameter, webkitTransform: tStart, msTransform: tStart, transform: tStart }); jqLite.addClass(rippleEl, 'mui--is-visible'); jqLite.removeClass(rippleEl, 'mui--is-animating'); // start animation util.requestAnimationFrame(function() { jqLite.css(rippleEl, { webkitTransform: tEnd, msTransform: tEnd, transform: tEnd }); jqLite.addClass(rippleEl, 'mui--is-animating'); }); } /** * MouseUp event handler. * @param {Event} ev - The DOM event */ function mouseUpHandler(ev) { // get ripple element var rippleEl = this._rippleEl; // allow a repaint to occur before removing class so animation shows for // tap events util.requestAnimationFrame(function() { jqLite.removeClass(rippleEl, 'mui--is-visible'); }); } /** Define module API */ module.exports = { /** Initialize module listeners */ initListeners: function() { // markup elements available when method is called var elList = document.getElementsByClassName('mui-btn'), i = elList.length; while (i--) initialize(elList[i]); // listen for new elements animationHelpers.onAnimationStart('mui-btn-inserted', function(ev) { initialize(ev.target); }); } }; },{"./lib/animationHelpers":3,"./lib/jqLite":5,"./lib/util":6}],11:[function(require,module,exports){ /** * MUI CSS/JS select module * @module forms/select */ 'use strict'; var jqLite = require('./lib/jqLite'), util = require('./lib/util'), animationHelpers = require('./lib/animationHelpers'), formlib = require('./lib/forms'), wrapperClass = 'mui-select', cssSelector = '.mui-select > select', menuClass = 'mui-select__menu', selectedClass = 'mui--is-selected', disabledClass = 'mui--is-disabled', doc = document, win = window; /** * Initialize select element. * @param {Element} selectEl - The select element. */ function initialize(selectEl) { // check flag if (selectEl._muiSelect === true) return; else selectEl._muiSelect = true; // use default behavior on touch devices if ('ontouchstart' in doc.documentElement) return; // initialize element new Select(selectEl); // set flag selectEl._muiJs = true; } /** * Creates a new Select object * @class */ function Select(selectEl) { var wrapperEl = selectEl.parentNode; // instance variables this.selectEl = selectEl; this.wrapperEl = wrapperEl; this.useDefault = false; // currently unused but let's keep just in case this.isOpen = false; this.menu = null; // NOTE: To get around cross-browser issues with <select> behavior we will // defer focus to the parent element and handle events there // make wrapper tab focusable, remove tab focus from <select> if (!selectEl.disabled) wrapperEl.tabIndex = 0; if (!this.useDefault) selectEl.tabIndex = -1; var cb = util.callback; // prevent built-in menu from opening on <select> jqLite.on(selectEl, 'mousedown', cb(this, 'onInnerMouseDown')); // attach event listeners for custom menu jqLite.on(wrapperEl, 'click', cb(this, 'onWrapperClick')); jqLite.on(wrapperEl, 'blur focus', cb(this, 'onWrapperBlurOrFocus')); jqLite.on(wrapperEl, 'keydown', cb(this, 'onWrapperKeyDown')); // add element to detect 'disabled' change (using sister element due to // IE/Firefox issue var el = document.createElement('div'); el.className = 'mui-event-trigger'; wrapperEl.appendChild(el); // handle 'disabled' add/remove jqLite.on(el, animationHelpers.animationEvents, function(ev) { // no need to propagate ev.stopPropagation(); if (ev.animationName === 'mui-node-disabled') { ev.target.parentNode.removeAttribute('tabIndex'); } else { ev.target.parentNode.tabIndex = 0; } }); } /** * Dispatch focus and blur events on inner <select> element. * @param {Event} ev - The DOM event */ Select.prototype.onWrapperBlurOrFocus = function(ev) { util.dispatchEvent(this.selectEl, ev.type, false, false); } /** * Disable default dropdown on mousedown. * @param {Event} ev - The DOM event */ Select.prototype.onInnerMouseDown = function(ev) { // only left clicks if (ev.button !== 0 || this.useDefault) return; // prevent built-in menu from opening ev.preventDefault(); } /** * Handle keydown events when wrapper is focused **/ Select.prototype.onWrapperKeyDown = function(ev) { // check flag if (this.useDefault || ev.defaultPrevented) return; var keyCode = ev.keyCode; if (this.isOpen === false) { // spacebar, down, up if (keyCode === 32 || keyCode === 38 || keyCode === 40) { ev.preventDefault(); // open custom menu this.renderMenu(); } } else { var menu = this.menu; // tab if (keyCode === 9) return menu.destroy(); // escape | up | down | enter if (keyCode === 27 || keyCode === 40 || keyCode === 38 || keyCode === 13) { ev.preventDefault(); } if (keyCode === 27) { menu.destroy(); } else if (keyCode === 40) { menu.increment(); } else if (keyCode === 38) { menu.decrement(); } else if (keyCode === 13) { menu.selectCurrent(); menu.destroy(); } } } /** * Handle click events on wrapper element. * @param {Event} ev - The DOM event */ Select.prototype.onWrapperClick = function(ev) { // only left clicks, check default and disabled flags if (ev.button !== 0 || this.useDefault || this.selectEl.disabled) return; // focus wrapper this.wrapperEl.focus(); // open menu this.renderMenu(); } /** * Render options dropdown. */ Select.prototype.renderMenu = function() { // check flag if (this.isOpen) return; // render custom menu and reset flag var self = this; this.menu = new Menu(this.wrapperEl, this.selectEl, function() { self.isOpen = false; self.menu = null; self.wrapperEl.focus(); }); // set flag this.isOpen = true; } /** * Creates a new Menu * @class */ function Menu(wrapperEl, selectEl, wrapperCallbackFn) { // add scroll lock util.enableScrollLock(); // instance variables this.itemArray = []; this.origPos = null; this.currentPos = null; this.selectEl = selectEl; this.wrapperEl = wrapperEl; this.menuEl = this._createMenuEl(wrapperEl, selectEl); var cb = util.callback; this.onClickCB = cb(this, 'onClick'); this.destroyCB = cb(this, 'destroy'); this.wrapperCallbackFn = wrapperCallbackFn; // add to DOM wrapperEl.appendChild(this.menuEl); jqLite.scrollTop(this.menuEl, this.menuEl._muiScrollTop); // attach event handlers jqLite.on(this.menuEl, 'click', this.onClickCB); jqLite.on(win, 'resize', this.destroyCB); // attach event handler after current event loop exits var fn = this.destroyCB; setTimeout(function() {jqLite.on(doc, 'click', fn);}, 0); } /** * Create menu element * @param {Element} selectEl - The select element */ Menu.prototype._createMenuEl = function(wrapperEl, selectEl) { var menuEl = doc.createElement('div'), childEls = selectEl.children, itemArray = this.itemArray, itemPos = 0, selectedPos = 0, selectedRow = 0, docFrag = document.createDocumentFragment(), // for speed loopEl, rowEl, optionEls, inGroup, i, iMax, j, jMax; menuEl.className = menuClass; for (i=0, iMax=childEls.length; i < iMax; i++) { loopEl = childEls[i]; if (loopEl.tagName === 'OPTGROUP') { // add row item to menu rowEl = doc.createElement('div'); rowEl.textContent = loopEl.label; rowEl.className = 'mui-optgroup__label'; docFrag.appendChild(rowEl); inGroup = true; optionEls = loopEl.children; } else { inGroup = false; optionEls = [loopEl]; } // loop through option elements for (j=0, jMax=optionEls.length; j < jMax; j++) { loopEl = optionEls[j]; // add row item to menu rowEl = doc.createElement('div'); rowEl.textContent = loopEl.textContent; // handle optgroup options if (inGroup) jqLite.addClass(rowEl, 'mui-optgroup__option'); if (loopEl.disabled) { // do not attach muiIndex to disable <option> elements to make them // unselectable. jqLite.addClass(rowEl, disabledClass); } else { rowEl._muiIndex = loopEl.index; rowEl._muiPos = itemPos; // handle selected options if (loopEl.selected) { jqLite.addClass(rowEl, selectedClass); selectedRow = menuEl.children.length; selectedPos = itemPos; } // add to item array itemArray.push(rowEl); itemPos += 1; } docFrag.appendChild(rowEl); } } // add rows to menu menuEl.appendChild(docFrag); // save indices this.origPos = selectedPos; this.currentPos = selectedPos; // set position var props = formlib.getMenuPositionalCSS( wrapperEl, menuEl.children.length, selectedRow ); jqLite.css(menuEl, props); menuEl._muiScrollTop = props.scrollTop; return menuEl; } /** * Handle click events on menu element. * @param {Event} ev - The DOM event */ Menu.prototype.onClick = function(ev) { // don't allow events to bubble ev.stopPropagation(); var item = ev.target, index = item._muiIndex; // ignore clicks on non-items if (index === undefined) return; // select option this.currentPos = item._muiPos; this.selectCurrent(); // destroy menu this.destroy(); } /** * Increment selected item */ Menu.prototype.increment = function() { if (this.currentPos === this.itemArray.length - 1) return; // un-select old row jqLite.removeClass(this.itemArray[this.currentPos], selectedClass); // select new row this.currentPos += 1; jqLite.addClass(this.itemArray[this.currentPos], selectedClass); } /** * Decrement selected item */ Menu.prototype.decrement = function() { if (this.currentPos === 0) return; // un-select old row jqLite.removeClass(this.itemArray[this.currentPos], selectedClass); // select new row this.currentPos -= 1; jqLite.addClass(this.itemArray[this.currentPos], selectedClass); } /** * Select current item */ Menu.prototype.selectCurrent = function() { if (this.currentPos !== this.origPos) { this.selectEl.selectedIndex = this.itemArray[this.currentPos]._muiIndex; // trigger change event util.dispatchEvent(this.selectEl, 'change', false, false); } } /** * Destroy menu and detach event handlers */ Menu.prototype.destroy = function() { // remove scroll lock util.disableScrollLock(true); // remove event handlers jqLite.off(this.menuEl, 'click', this.clickCallbackFn); jqLite.off(doc, 'click', this.destroyCB); jqLite.off(win, 'resize', this.destroyCB); // remove element and execute wrapper callback var parentNode = this.menuEl.parentNode; if (parentNode) { parentNode.removeChild(this.menuEl); this.wrapperCallbackFn(); } } /** Define module API */ module.exports = { /** Initialize module listeners */ initListeners: function() { // markup elements available when method is called var elList = doc.querySelectorAll(cssSelector), i = elList.length; while (i--) initialize(elList[i]); // listen for mui-node-inserted events animationHelpers.onAnimationStart('mui-select-inserted', function(ev) { initialize(ev.target); }); } }; },{"./lib/animationHelpers":3,"./lib/forms":4,"./lib/jqLite":5,"./lib/util":6}],12:[function(require,module,exports){ /** * MUI CSS/JS tabs module * @module tabs */ 'use strict'; var jqLite = require('./lib/jqLite'), util = require('./lib/util'), animationHelpers = require('./lib/animationHelpers'), attrKey = 'data-mui-toggle', attrSelector = '[' + attrKey + '="tab"]', controlsAttrKey = 'data-mui-controls', activeClass = 'mui--is-active', showstartKey = 'mui.tabs.showstart', showendKey = 'mui.tabs.showend', hidestartKey = 'mui.tabs.hidestart', hideendKey = 'mui.tabs.hideend'; /** * Initialize the toggle element * @param {Element} toggleEl - The toggle element. */ function initialize(toggleEl) { // check flag if (toggleEl._muiTabs === true) return; else toggleEl._muiTabs = true; // attach click handler jqLite.on(toggleEl, 'click', clickHandler); } /** * Handle clicks on the toggle element. * @param {Event} ev - The DOM event. */ function clickHandler(ev) { // only left clicks if (ev.button !== 0) return; var toggleEl = this; // exit if toggle element is disabled if (toggleEl.getAttribute('disabled') !== null) return; activateTab(toggleEl); } /** * Activate the tab controlled by the toggle element. * @param {Element} toggleEl - The toggle element. */ function activateTab(currToggleEl) { var currTabEl = currToggleEl.parentNode, currPaneId = currToggleEl.getAttribute(controlsAttrKey), currPaneEl = document.getElementById(currPaneId), prevTabEl, prevPaneEl, prevPaneId, prevToggleEl, currData, prevData, ev1, ev2, cssSelector; // exit if already active if (jqLite.hasClass(currTabEl, activeClass)) return; // raise error if pane doesn't exist if (!currPaneEl) util.raiseError('Tab pane "' + currPaneId + '" not found'); // get previous pane prevPaneEl = getActiveSibling(currPaneEl); prevPaneId = prevPaneEl.id; // get previous toggle and tab elements cssSelector = '[' + controlsAttrKey + '="' + prevPaneId + '"]'; prevToggleEl = document.querySelectorAll(cssSelector)[0]; prevTabEl = prevToggleEl.parentNode; // define event data currData = {paneId: currPaneId, relatedPaneId: prevPaneId}; prevData = {paneId: prevPaneId, relatedPaneId: currPaneId}; // dispatch 'hidestart', 'showstart' events ev1 = util.dispatchEvent(prevToggleEl, hidestartKey, true, true, prevData); ev2 = util.dispatchEvent(currToggleEl, showstartKey, true, true, currData); // let events bubble setTimeout(function() { // exit if either event was canceled if (ev1.defaultPrevented || ev2.defaultPrevented) return; // de-activate previous if (prevTabEl) jqLite.removeClass(prevTabEl, activeClass); if (prevPaneEl) jqLite.removeClass(prevPaneEl, activeClass); // activate current jqLite.addClass(currTabEl, activeClass); jqLite.addClass(currPaneEl, activeClass); // dispatch 'hideend', 'showend' events util.dispatchEvent(prevToggleEl, hideendKey, true, false, prevData); util.dispatchEvent(currToggleEl, showendKey, true, false, currData); }, 0); } /** * Get previous active sibling. * @param {Element} el - The anchor element. */ function getActiveSibling(el) { var elList = el.parentNode.children, q = elList.length, activeEl = null, tmpEl; while (q-- && !activeEl) { tmpEl = elList[q]; if (tmpEl !== el && jqLite.hasClass(tmpEl, activeClass)) activeEl = tmpEl } return activeEl; } /** Define module API */ module.exports = { /** Initialize module listeners */ initListeners: function() { // markup elements available when method is called var elList = document.querySelectorAll(attrSelector), i = elList.length; while (i--) {initialize(elList[i]);} animationHelpers.onAnimationStart('mui-tab-inserted', function(ev) { initialize(ev.target); }); }, /** External API */ api: { activate: function(paneId) { var cssSelector = '[' + controlsAttrKey + '=' + paneId + ']', toggleEl = document.querySelectorAll(cssSelector); if (!toggleEl.length) { util.raiseError('Tab control for pane "' + paneId + '" not found'); } activateTab(toggleEl[0]); } } }; },{"./lib/animationHelpers":3,"./lib/jqLite":5,"./lib/util":6}],13:[function(require,module,exports){ /** * MUI CSS/JS form-control module * @module forms/form-control */ 'use strict'; var jqLite = require('./lib/jqLite'), util = require('./lib/util'), animationHelpers = require('./lib/animationHelpers'), cssSelector = '.mui-textfield > input, .mui-textfield > textarea', emptyClass = 'mui--is-empty', notEmptyClass = 'mui--is-not-empty', dirtyClass = 'mui--is-dirty', floatingLabelClass = 'mui-textfield--float-label'; /** * Initialize input element. * @param {Element} inputEl - The input element. */ function initialize(inputEl) { // check flag if (inputEl._muiTextfield === true) return; else inputEl._muiTextfield = true; if (inputEl.value.length) jqLite.addClass(inputEl, notEmptyClass); else jqLite.addClass(inputEl, emptyClass); jqLite.on(inputEl, 'input change', inputHandler); // add dirty class on focus jqLite.on(inputEl, 'focus', function(){jqLite.addClass(this, dirtyClass);}); } /** * Handle input events. */ function inputHandler() { var inputEl = this; if (inputEl.value.length) { jqLite.removeClass(inputEl, emptyClass); jqLite.addClass(inputEl, notEmptyClass); } else { jqLite.removeClass(inputEl, notEmptyClass); jqLite.addClass(inputEl, emptyClass) } jqLite.addClass(inputEl, dirtyClass); } /** Define module API */ module.exports = { /** Initialize input elements */ initialize: initialize, /** Initialize module listeners */ initListeners: function() { var doc = document; // markup elements available when method is called var elList = doc.querySelectorAll(cssSelector), i = elList.length; while (i--) initialize(elList[i]); // listen for new elements animationHelpers.onAnimationStart('mui-textfield-inserted', function(ev) { initialize(ev.target); }); // add transition css for floating labels setTimeout(function() { var css = '.mui-textfield.mui-textfield--float-label > label {' + [ '-webkit-transition', '-moz-transition', '-o-transition', 'transition', '' ].join(':all .15s ease-out;') + '}'; util.loadStyle(css); }, 150); // pointer-events shim for floating labels if (util.supportsPointerEvents() === false) { jqLite.on(doc, 'click', function(ev) { var targetEl = ev.target; if (targetEl.tagName === 'LABEL' && jqLite.hasClass(targetEl.parentNode, floatingLabelClass)) { var inputEl = targetEl.previousElementSibling; if (inputEl) inputEl.focus(); } }); } } }; },{"./lib/animationHelpers":3,"./lib/jqLite":5,"./lib/util":6}]},{},[1])
/** * ag-grid - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components * @version v6.2.0 * @link http://www.ag-grid.com/ * @license MIT */ var utils_1 = require("../utils"); var gridRow_1 = require("./gridRow"); var GridCell = (function () { function GridCell(rowIndex, floating, column) { this.rowIndex = rowIndex; this.column = column; this.floating = utils_1.Utils.makeNull(floating); } GridCell.prototype.getGridRow = function () { return new gridRow_1.GridRow(this.rowIndex, this.floating); }; GridCell.prototype.toString = function () { return "rowIndex = " + this.rowIndex + ", floating = " + this.floating + ", column = " + (this.column ? this.column.getId() : null); }; GridCell.prototype.createId = function () { return this.rowIndex + "." + this.floating + "." + this.column.getId(); }; return GridCell; })(); exports.GridCell = GridCell;
/* Lithuanian (UTF-8) initialisation for the jQuery UI date picker plugin. */ /* @author Arturas Paleicikas <arturas@avalon.lt> */ (function($) { $.datepick.regional['lt'] = { clearText: 'Išvalyti', clearStatus: '', closeText: 'Uždaryti', closeStatus: '', prevText: '&#x3c;Atgal', prevStatus: '', prevBigText: '&#x3c;&#x3c;', prevBigStatus: '', nextText: 'Pirmyn&#x3e;', nextStatus: '', nextBigText: '&#x3e;&#x3e;', nextBigStatus: '', currentText: 'Šiandien', currentStatus: '', monthNames: ['Sausis','Vasaris','Kovas','Balandis','Gegužė','Birželis', 'Liepa','Rugpjūtis','Rugsėjis','Spalis','Lapkritis','Gruodis'], monthNamesShort: ['Sau','Vas','Kov','Bal','Geg','Bir', 'Lie','Rugp','Rugs','Spa','Lap','Gru'], monthStatus: '', yearStatus: '', weekHeader: '', weekStatus: '', dayNames: ['sekmadienis','pirmadienis','antradienis','trečiadienis','ketvirtadienis','penktadienis','šeštadienis'], dayNamesShort: ['sek','pir','ant','tre','ket','pen','šeš'], dayNamesMin: ['Se','Pr','An','Tr','Ke','Pe','Še'], dayStatus: 'DD', dateStatus: 'D, M d', dateFormat: 'yy-mm-dd', firstDay: 1, initStatus: '', isRTL: false}; $.datepick.setDefaults($.datepick.regional['lt']); })(jQuery);
(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : typeof define === 'function' && define.amd ? define(['exports'], factory) : (factory((global.preact = global.preact || {}))); }(this, function (exports) { 'use strict'; function VNode(nodeName, attributes, children) { /** @type {string|function} */ this.nodeName = nodeName; /** @type {object<string>|undefined} */ this.attributes = attributes; /** @type {array<VNode>|undefined} */ this.children = children; /** Reference to the given key. */ this.key = attributes && attributes.key; } var NO_RENDER = 0; var SYNC_RENDER = 1; var DOM_RENDER = 2; var FORCE_RENDER = 3; var EMPTY = {}; var EMPTY_BASE = ''; var ATTR_KEY = typeof Symbol !== 'undefined' ? Symbol['for']('preactattr') : '__preactattr_'; // DOM properties that should NOT have "px" added when numeric var NON_DIMENSION_PROPS = { boxFlex: 1, boxFlexGroup: 1, columnCount: 1, fillOpacity: 1, flex: 1, flexGrow: 1, flexPositive: 1, flexShrink: 1, flexNegative: 1, fontWeight: 1, lineClamp: 1, lineHeight: 1, opacity: 1, order: 1, orphans: 1, strokeOpacity: 1, widows: 1, zIndex: 1, zoom: 1 }; var createObject = function createObject() { return {}; }; try { (function () { var Obj = function Obj() {} // eslint-disable-line ; Obj.prototype = Object.create(null); createObject = function () { return new Obj(); }; })(); } catch (e) {} /** Copy own-properties from `props` onto `obj`. * @returns obj * @private */ function extend(obj, props) { var pure = props.prototype === undefined; for (var i in props) { if (pure || hasOwnProperty.call(props, i)) { obj[i] = props[i]; } }return obj; } /** Fast clone. Note: does not filter out non-own properties. */ function clone(obj) { var out = {}; /*eslint guard-for-in:0*/ for (var i in obj) { out[i] = obj[i]; }return out; } /** Create a caching wrapper for the given function. * Note: As this method is only used for memoizing string operations, it does not safeguard against Object.prototype manipulation. * @private */ function memoize(fn) { var mem = createObject(); return function (k) { return mem[k] || (mem[k] = fn(k)); }; } /** Get a deep property value from the given object, expressed in dot-notation. * @private */ function delve(obj, key) { for (var p = key.split('.'), i = 0; i < p.length && obj; i++) { obj = obj[p[i]]; } return obj; } /** Convert an Array-like object to an Array * @private */ function toArray(obj) { var arr = [], i = obj.length; while (i--) arr[i] = obj[i]; return arr; } /** @private is the given object a Function? */ function isFunction(obj) { return 'function' === typeof obj; } /** @private is the given object a String? */ function isString(obj) { return 'string' === typeof obj; } /** @private Safe reference to builtin hasOwnProperty */ var hasOwnProperty = ({}).hasOwnProperty; /** Check if a value is `null` or `undefined`. * @private */ function empty(x) { return x === undefined || x === null; } /** Check if a value is `null`, `undefined`, or explicitly `false`. */ function falsey(value) { return value === false || empty(value); } /** Convert a hashmap of styles to CSSText * @private */ function styleObjToCss(s) { var str = ''; /* eslint guard-for-in:0 */ for (var prop in s) { var val = s[prop]; if (!empty(val)) { if (str) str += ' '; str += jsToCss(prop); str += ': '; str += val; if (typeof val === 'number' && !NON_DIMENSION_PROPS[prop]) { str += 'px'; } str += ';'; } } return str; } /** Convert a hashmap of CSS classes to a space-delimited className string * @private */ function hashToClassName(c) { var str = ''; for (var prop in c) { if (c[prop]) { if (str) str += ' '; str += prop; } } return str; } /** Convert a JavaScript camel-case CSS property name to a CSS property name * @private * @function */ var jsToCss = memoize(function (s) { return toLowerCase(s.replace(/([A-Z])/g, '-$1')); }); /** Just a memoized String.prototype.toLowerCase */ var toLowerCase = memoize(function (s) { return s.toLowerCase(); }); // For animations, rAF is vastly superior. However, it scores poorly on benchmarks :( // export const setImmediate = typeof requestAnimationFrame==='function' ? requestAnimationFrame : setTimeout; var ch = undefined; try { ch = new MessageChannel(); } catch (e) {} /** Call a function asynchronously, as soon as possible. * @param {Function} callback */ var setImmediate = ch ? function (f) { ch.port1.onmessage = f; ch.port2.postMessage(''); } : setTimeout; /** Global options * @public * @namespace options {Object} */ var options = { /** If `true`, `prop` changes trigger synchronous component updates. * @name syncComponentUpdates * @type Boolean * @default true */ //syncComponentUpdates: true, /** Processes all created VNodes. * @param {VNode} vnode A newly-created VNode to normalize/process */ vnode: function vnode(n) { var attrs = n.attributes; if (!attrs || isFunction(n.nodeName)) return; // normalize className to class. var p = attrs.className; if (p) { attrs['class'] = p; delete attrs.className; } if (attrs['class']) normalize(attrs, 'class', hashToClassName); if (attrs.style) normalize(attrs, 'style', styleObjToCss); } }; function normalize(obj, prop, fn) { var v = obj[prop]; if (v && !isString(v)) { obj[prop] = fn(v); } } /** Invoke a hook on the `options` export. */ function optionsHook(name, a) { return hook(options, name, a); } /** Invoke a "hook" method with arguments if it exists. * @private */ function hook(obj, name, a, b, c) { if (obj[name]) return obj[name](a, b, c); } /** Invoke hook() on a component and child components (recursively) * @private */ function deepHook(obj, type) { do { hook(obj, type); } while (obj = obj._component); } var SHARED_TEMP_ARRAY = []; /** JSX/hyperscript reviver * @see http://jasonformat.com/wtf-is-jsx * @public * @example * /** @jsx h *\/ * import { render, h } from 'preact'; * render(<span>foo</span>, document.body); */ function h(nodeName, attributes, firstChild) { var len = arguments.length, children = undefined, arr = undefined, lastSimple = undefined; if (len > 2) { var type = typeof firstChild; if (len === 3 && type !== 'object' && type !== 'function') { if (!falsey(firstChild)) { children = [String(firstChild)]; } } else { children = []; for (var i = 2; i < len; i++) { var _p = arguments[i]; if (falsey(_p)) continue; if (_p.join) { arr = _p; } else { arr = SHARED_TEMP_ARRAY; arr[0] = _p; } for (var j = 0; j < arr.length; j++) { var child = arr[j], simple = !falsey(child) && !(child instanceof VNode); if (simple && !isString(child)) child = String(child); if (simple && lastSimple) { children[children.length - 1] += child; } else if (!falsey(child)) { children.push(child); } lastSimple = simple; } } } } else if (attributes && attributes.children) { return h(nodeName, attributes, attributes.children); } var p = new VNode(nodeName, attributes || undefined, children); optionsHook('vnode', p); return p; } /** Create an Event handler function that sets a given state property. * @param {Component} component The component whose state should be updated * @param {string} key A dot-notated key path to update in the component's state * @param {string} eventPath A dot-notated key path to the value that should be retrieved from the Event or component * @returns {function} linkedStateHandler * @private */ function createLinkedState(component, key, eventPath) { var path = key.split('.'), p0 = path[0], len = path.length; return function (e) { var _component$setState; var t = e && e.currentTarget || this, s = component.state, obj = s, v = undefined, i = undefined; if (isString(eventPath)) { v = delve(e, eventPath); if (empty(v) && (t = t._component)) { v = delve(t, eventPath); } } else { v = (t.nodeName + t.type).match(/^input(check|rad)/i) ? t.checked : t.value; } if (isFunction(v)) v = v.call(t); if (len > 1) { for (i = 0; i < len - 1; i++) { obj = obj[path[i]] || (obj[path[i]] = {}); } obj[path[i]] = v; v = s[p0]; } component.setState((_component$setState = {}, _component$setState[p0] = v, _component$setState)); }; } var items = []; var itemsOffline = []; function enqueueRender(component) { if (items.push(component) !== 1) return; (options.debounceRendering || setImmediate)(rerender); } function rerender() { if (!items.length) return; var currentItems = items, p = undefined; // swap online & offline items = itemsOffline; itemsOffline = currentItems; while (p = currentItems.pop()) { if (p._dirty) renderComponent(p); } } /** Check if a VNode is a reference to a stateless functional component. * A function component is represented as a VNode whose `nodeName` property is a reference to a function. * If that function is not a Component (ie, has no `.render()` method on a prototype), it is considered a stateless functional component. * @param {VNode} vnode A VNode * @private */ function isFunctionalComponent(_ref) { var nodeName = _ref.nodeName; return isFunction(nodeName) && !(nodeName.prototype && nodeName.prototype.render); } /** Construct a resultant VNode from a VNode referencing a stateless functional component. * @param {VNode} vnode A VNode with a `nodeName` property that is a reference to a function. * @private */ function buildFunctionalComponent(vnode, context) { return vnode.nodeName(getNodeProps(vnode), context || EMPTY) || EMPTY_BASE; } function ensureNodeData(node, data) { return node[ATTR_KEY] || (node[ATTR_KEY] = data || createObject()); } function getNodeType(node) { if (node instanceof Text) return 3; if (node instanceof Element) return 1; return 0; } /** Append multiple children to a Node. * Uses a Document Fragment to batch when appending 2 or more children * @private */ function appendChildren(parent, children) { var len = children.length, many = len > 2, into = many ? document.createDocumentFragment() : parent; for (var i = 0; i < len; i++) { into.appendChild(children[i]); }if (many) parent.appendChild(into); } /** Removes a given DOM Node from its parent. */ function removeNode(node) { var p = node.parentNode; if (p) p.removeChild(node); } /** Set a named attribute on the given Node, with special behavior for some names and event handlers. * If `value` is `null`, the attribute/handler will be removed. * @param {Element} node An element to mutate * @param {string} name The name/key to set, such as an event or attribute name * @param {any} value An attribute value, such as a function to be used as an event handler * @param {any} previousValue The last value that was set for this name/node pair * @private */ function setAccessor(node, name, value) { if (name === 'class') { node.className = value || ''; } else if (name === 'style') { node.style.cssText = value || ''; } else if (name === 'dangerouslySetInnerHTML') { if (value && value.__html) node.innerHTML = value.__html; } else if (name !== 'key' && name !== 'children') { // let valueIsFalsey = falsey(value); if (name !== 'type' && name in node) { node[name] = value; if (falsey(value)) node.removeAttribute(name); } else if (name.substring(0, 2) === 'on') { var type = normalizeEventName(name), l = node._listeners || (node._listeners = createObject()); if (!l[type]) node.addEventListener(type, eventProxy);else if (!value) node.removeEventListener(type, eventProxy); l[type] = value; } else if (falsey(value)) { node.removeAttribute(name); } else if (typeof value !== 'object' && !isFunction(value)) { node.setAttribute(name, value); } } ensureNodeData(node)[name] = value; } /** Proxy an event to hooked event handlers * @private */ function eventProxy(e) { return this._listeners[normalizeEventName(e.type)](optionsHook('event', e) || e); } /** Convert an Event name/type to lowercase and strip any "on*" prefix. * @function * @private */ var normalizeEventName = memoize(function (t) { return toLowerCase(t.replace(/^on/i, '')); }); /** Get a node's attributes as a hashmap. * @private */ function getRawNodeAttributes(node) { var list = node.attributes, attrs = createObject(), i = list.length; while (i--) attrs[list[i].name] = list[i].value; return attrs; } /** Check if two nodes are equivalent. * @param {Element} node * @param {VNode} vnode * @private */ function isSameNodeType(node, vnode) { if (isString(vnode)) return getNodeType(node) === 3; var nodeName = vnode.nodeName, type = typeof nodeName; if (type === 'string') { return node.normalizedNodeName === nodeName || isNamedNode(node, nodeName); } if (type === 'function') { return node._componentConstructor === nodeName || isFunctionalComponent(vnode); } } function isNamedNode(node, nodeName) { return toLowerCase(node.nodeName) === toLowerCase(nodeName); } /** * Reconstruct Component-style `props` from a VNode. * Ensures default/fallback values from `defaultProps`: * Own-properties of `defaultProps` not present in `vnode.attributes` are added. * @param {VNode} vnode * @returns {Object} props */ function getNodeProps(vnode) { var defaultProps = vnode.nodeName.defaultProps, props = clone(defaultProps || vnode.attributes); if (defaultProps) extend(props, vnode.attributes); if (vnode.children) props.children = vnode.children; return props; } /** DOM node pool, keyed on nodeName. */ var nodes = createObject(); function collectNode(node) { cleanNode(node); var name = toLowerCase(node.nodeName), list = nodes[name]; if (list) list.push(node);else nodes[name] = [node]; } function createNode(nodeName) { var name = toLowerCase(nodeName), list = nodes[name], node = list && list.pop() || document.createElement(nodeName); ensureNodeData(node); node.normalizedNodeName = name; return node; } function cleanNode(node) { removeNode(node); if (getNodeType(node) === 3) return; // When reclaiming externally created nodes, seed the attribute cache: (Issue #97) ensureNodeData(node, getRawNodeAttributes(node)); node._component = node._componentConstructor = null; // if (node.childNodes.length>0) { // console.trace(`Warning: Recycler collecting <${node.nodeName}> with ${node.childNodes.length} children.`); // for (let i=node.childNodes.length; i--; ) collectNode(node.childNodes[i]); // } } /** Apply differences in a given vnode (and it's deep children) to a real DOM Node. * @param {Element} [dom=null] A DOM node to mutate into the shape of the `vnode` * @param {VNode} vnode A VNode (with descendants forming a tree) representing the desired DOM structure * @returns {Element} dom The created/mutated element * @private */ function diff(dom, vnode, context, mountAll) { var originalAttributes = vnode.attributes; while (isFunctionalComponent(vnode)) { vnode = buildFunctionalComponent(vnode, context); } if (isString(vnode)) { if (dom) { if (getNodeType(dom) === 3) { if (dom.nodeValue !== vnode) { dom.nodeValue = vnode; } return dom; } collectNode(dom); } return document.createTextNode(vnode); } if (isFunction(vnode.nodeName)) { return buildComponentFromVNode(dom, vnode, context); } var out = dom, nodeName = vnode.nodeName; if (!isString(nodeName)) nodeName = String(nodeName); if (!dom) { out = createNode(nodeName); } else if (!isNamedNode(dom, nodeName)) { out = createNode(nodeName); // move children into the replacement node appendChildren(out, toArray(dom.childNodes)); // reclaim element nodes recollectNodeTree(dom); } diffNode(out, vnode, context, mountAll); diffAttributes(out, vnode); if (originalAttributes && originalAttributes.ref) { (out[ATTR_KEY].ref = originalAttributes.ref)(out); } return out; } /** Morph a DOM node to look like the given VNode. Creates DOM if it doesn't exist. */ function diffNode(dom, vnode, context, mountAll) { var vchildren = vnode.children, firstChild = dom.firstChild; if (vchildren && vchildren.length === 1 && typeof vchildren[0] === 'string' && firstChild instanceof Text && dom.childNodes.length === 1) { firstChild.nodeValue = vchildren[0]; } else if (vchildren || firstChild) { innerDiffNode(dom, vchildren, context, mountAll); } } function getKey(child) { var c = child._component; if (c) return c.__key; var data = child[ATTR_KEY]; if (data) return data.key; } /** Apply child and attribute changes between a VNode and a DOM Node to the DOM. */ function innerDiffNode(dom, vchildren, context, mountAll) { var originalChildren = dom.childNodes, children = undefined, keyed = undefined, keyedLen = 0, min = 0, vlen = vchildren && vchildren.length, len = originalChildren.length, childrenLen = 0; if (len) { children = []; for (var i = 0; i < len; i++) { var child = originalChildren[i], key = getKey(child); if (key || key === 0) { if (!keyed) keyed = createObject(); keyed[key] = child; keyedLen++; } else { children[childrenLen++] = child; } } } if (vlen) { for (var i = 0; i < vlen; i++) { var vchild = vchildren[i], child = undefined; // if (isFunctionalComponent(vchild)) { // vchild = buildFunctionalComponent(vchild); // } // attempt to find a node based on key matching if (keyedLen !== 0 && vchild.attributes) { var key = vchild.key; if (!empty(key) && hasOwnProperty.call(keyed, key)) { child = keyed[key]; keyed[key] = undefined; keyedLen--; } } // attempt to pluck a node of the same type from the existing children if (!child && min < childrenLen) { for (var j = min; j < childrenLen; j++) { var _c = children[j]; if (_c && isSameNodeType(_c, vchild)) { child = _c; children[j] = undefined; if (j === childrenLen - 1) childrenLen--; if (j === min) min++; break; } } } // morph the matched/found/created DOM child to match vchild (deep) child = diff(child, vchild, context, mountAll); var c = (mountAll || child.parentNode !== dom) && child._component; if (c) deepHook(c, 'componentWillMount'); var next = originalChildren[i]; if (next !== child && originalChildren[i + 1] !== child) { if (next) { dom.insertBefore(child, next); } else { dom.appendChild(child); } } if (c) deepHook(c, 'componentDidMount'); } } if (keyedLen) { /*eslint guard-for-in:0*/ for (var i in keyed) { if (hasOwnProperty.call(keyed, i) && keyed[i]) { children[min = childrenLen++] = keyed[i]; } } } // remove orphaned children if (min < childrenLen) { removeOrphanedChildren(children); } } /** Reclaim children that were unreferenced in the desired VTree */ function removeOrphanedChildren(children, unmountOnly) { for (var i = children.length; i--;) { var child = children[i]; if (child) { recollectNodeTree(child, unmountOnly); } } } /** Reclaim an entire tree of nodes, starting at the root. */ function recollectNodeTree(node, unmountOnly) { // @TODO: Need to make a call on whether Preact should remove nodes not created by itself. // Currently it *does* remove them. Discussion: https://github.com/developit/preact/issues/39 //if (!node[ATTR_KEY]) return; var attrs = node[ATTR_KEY]; if (attrs) hook(attrs, 'ref', null); var component = node._component; if (component) { unmountComponent(component, !unmountOnly); } else { if (!unmountOnly) { if (getNodeType(node) !== 1) { removeNode(node); return; } collectNode(node); } var c = node.childNodes; if (c && c.length) { removeOrphanedChildren(c, unmountOnly); } } } /** Apply differences in attributes from a VNode to the given DOM Node. */ function diffAttributes(dom, vnode) { var old = dom[ATTR_KEY] || getRawNodeAttributes(dom), attrs = vnode.attributes; // removeAttributes(dom, old, attrs || EMPTY); for (var _name in old) { if (!attrs || !(_name in attrs)) { setAccessor(dom, _name, null); } } // new & updated if (attrs) { for (var _name2 in attrs) { var value = attrs[_name2]; if (value === undefined) value = null; if (!(_name2 in old) || value != old[_name2]) { setAccessor(dom, _name2, value); } } } } /** Retains a pool of Components for re-use, keyed on component name. * Note: since component names are not unique or even necessarily available, these are primarily a form of sharding. * @private */ var components = createObject(); function collectComponent(component) { var name = component.constructor.name, list = components[name]; if (list) list.push(component);else components[name] = [component]; } function createComponent(Ctor, props, context) { var inst = new Ctor(props, context), list = components[Ctor.name]; if (list) { for (var i = 0; i < list.length; i++) { if (list[i].constructor === Ctor) { inst.nextBase = list[i].base; list.splice(i, 1); break; } } } return inst; } /** Mark component as dirty and queue up a render. * @param {Component} component * @private */ function triggerComponentRender(component) { if (!component._dirty) { component._dirty = true; enqueueRender(component); } } /** Set a component's `props` (generally derived from JSX attributes). * @param {Object} props * @param {Object} [opts] * @param {boolean} [opts.renderSync=false] If `true` and {@link options.syncComponentUpdates} is `true`, triggers synchronous rendering. * @param {boolean} [opts.render=true] If `false`, no render will be triggered. */ function setComponentProps(component, props, opts, context) { var d = component._disableRendering === true; component._disableRendering = true; if (component.__ref = props.ref) delete props.ref; if (component.__key = props.key) delete props.key; if (!empty(component.base)) { hook(component, 'componentWillReceiveProps', props, context); } if (context && context !== component.context) { if (!component.prevContext) component.prevContext = component.context; component.context = context; } if (!component.prevProps) component.prevProps = component.props; component.props = props; component._disableRendering = d; if (opts !== NO_RENDER) { if (opts === SYNC_RENDER || options.syncComponentUpdates !== false) { renderComponent(component); } else { triggerComponentRender(component); } } hook(component, '__ref', component); } /** Render a Component, triggering necessary lifecycle events and taking High-Order Components into account. * @param {Component} component * @param {Object} [opts] * @param {boolean} [opts.build=false] If `true`, component will build and store a DOM node if not already associated with one. * @private */ function renderComponent(component, opts) { if (component._disableRendering) return; var skip = undefined, rendered = undefined, props = component.props, state = component.state, context = component.context, previousProps = component.prevProps || props, previousState = component.prevState || state, previousContext = component.prevContext || context, isUpdate = component.base, initialBase = isUpdate || component.nextBase; // if updating if (isUpdate) { component.props = previousProps; component.state = previousState; component.context = previousContext; if (opts !== FORCE_RENDER && hook(component, 'shouldComponentUpdate', props, state, context) === false) { skip = true; } else { hook(component, 'componentWillUpdate', props, state, context); } component.props = props; component.state = state; component.context = context; } component.prevProps = component.prevState = component.prevContext = component.nextBase = null; component._dirty = false; if (!skip) { rendered = hook(component, 'render', props, state, context); var childComponent = rendered && rendered.nodeName, toUnmount = undefined, base = undefined; // context to pass to the child, can be updated via (grand-)parent component if (component.getChildContext) { context = extend(clone(context), component.getChildContext()); } if (isFunction(childComponent) && childComponent.prototype.render) { // set up high order component link var inst = component._component; if (inst && inst.constructor !== childComponent) { toUnmount = inst; inst = null; } var childProps = getNodeProps(rendered); if (inst) { setComponentProps(inst, childProps, SYNC_RENDER, context); } else { inst = createComponent(childComponent, childProps, context); inst._parentComponent = component; component._component = inst; if (isUpdate) deepHook(inst, 'componentWillMount'); setComponentProps(inst, childProps, NO_RENDER, context); renderComponent(inst, DOM_RENDER); if (isUpdate) deepHook(inst, 'componentDidMount'); } base = inst.base; } else { var cbase = initialBase; // destroy high order component link toUnmount = component._component; if (toUnmount) { cbase = component._component = null; } if (initialBase || opts === DOM_RENDER) { if (cbase) cbase._component = null; base = diff(cbase, rendered || EMPTY_BASE, context, !isUpdate); } } if (initialBase && base !== initialBase) { var p = initialBase.parentNode; if (p && base !== p) p.replaceChild(base, initialBase); } if (toUnmount) { unmountComponent(toUnmount, true); } component.base = base; if (base) { var componentRef = component, t = component; while (t = t._parentComponent) { componentRef = t; } base._component = componentRef; base._componentConstructor = componentRef.constructor; } if (isUpdate) { hook(component, 'componentDidUpdate', previousProps, previousState, previousContext); } } var cb = component._renderCallbacks, fn = undefined; if (cb) while (fn = cb.pop()) fn.call(component); return rendered; } /** Apply the Component referenced by a VNode to the DOM. * @param {Element} dom The DOM node to mutate * @param {VNode} vnode A Component-referencing VNode * @returns {Element} dom The created/mutated element * @private */ function buildComponentFromVNode(dom, vnode, context) { var c = dom && dom._component, oldDom = dom; var isOwner = c && dom._componentConstructor === vnode.nodeName; while (c && !isOwner && (c = c._parentComponent)) { isOwner = c.constructor === vnode.nodeName; } if (isOwner) { setComponentProps(c, getNodeProps(vnode), SYNC_RENDER, context); dom = c.base; } else { if (c) { unmountComponent(c, true); dom = oldDom = null; } dom = createComponentFromVNode(vnode, dom, context); if (oldDom && dom !== oldDom) { oldDom._component = null; recollectNodeTree(oldDom); } } return dom; } /** Instantiate and render a Component, given a VNode whose nodeName is a constructor. * @param {VNode} vnode * @private */ function createComponentFromVNode(vnode, dom, context) { var props = getNodeProps(vnode); var component = createComponent(vnode.nodeName, props, context); if (dom && !component.base) component.base = dom; setComponentProps(component, props, NO_RENDER, context); renderComponent(component, DOM_RENDER); // let node = component.base; //if (!node._component) { // node._component = component; // node._componentConstructor = vnode.nodeName; //} return component.base; } /** Remove a component from the DOM and recycle it. * @param {Element} dom A DOM node from which to unmount the given Component * @param {Component} component The Component instance to unmount * @private */ function unmountComponent(component, remove) { // console.log(`${remove?'Removing':'Unmounting'} component: ${component.constructor.name}`, component); hook(component, '__ref', null); hook(component, 'componentWillUnmount'); // recursively tear down & recollect high-order component children: var inner = component._component; if (inner) { unmountComponent(inner, remove); remove = false; } var base = component.base; if (base) { if (remove !== false) removeNode(base); removeOrphanedChildren(base.childNodes, true); } if (remove) { component._parentComponent = null; collectComponent(component); } hook(component, 'componentDidUnmount'); } /** Base Component class, for he ES6 Class method of creating Components * @public * * @example * class MyFoo extends Component { * render(props, state) { * return <div />; * } * } */ function Component(props, context) { /** @private */ this._dirty = true; /** @public */ this._disableRendering = false; /** @public */ this.prevState = this.prevProps = this.prevContext = this.base = this.nextBase = this._parentComponent = this._component = this.__ref = this.__key = this._linkedStates = this._renderCallbacks = null; /** @public */ this.context = context || createObject(); /** @type {object} */ this.props = props; /** @type {object} */ this.state = hook(this, 'getInitialState') || createObject(); } extend(Component.prototype, { /** Returns a `boolean` value indicating if the component should re-render when receiving the given `props` and `state`. * @param {object} nextProps * @param {object} nextState * @param {object} nextContext * @returns {Boolean} should the component re-render * @name shouldComponentUpdate * @function */ // shouldComponentUpdate() { // return true; // }, /** Returns a function that sets a state property when called. * Calling linkState() repeatedly with the same arguments returns a cached link function. * * Provides some built-in special cases: * - Checkboxes and radio buttons link their boolean `checked` value * - Inputs automatically link their `value` property * - Event paths fall back to any associated Component if not found on an element * - If linked value is a function, will invoke it and use the result * * @param {string} key The path to set - can be a dot-notated deep key * @param {string} [eventPath] If set, attempts to find the new state value at a given dot-notated path within the object passed to the linkedState setter. * @returns {function} linkStateSetter(e) * * @example Update a "text" state value when an input changes: * <input onChange={ this.linkState('text') } /> * * @example Set a deep state value on click * <button onClick={ this.linkState('touch.coords', 'touches.0') }>Tap</button */ linkState: function linkState(key, eventPath) { var c = this._linkedStates || (this._linkedStates = createObject()), cacheKey = key + '|' + eventPath; return c[cacheKey] || (c[cacheKey] = createLinkedState(this, key, eventPath)); }, /** Update component state by copying properties from `state` to `this.state`. * @param {object} state A hash of state properties to update with new values */ setState: function setState(state, callback) { var s = this.state; if (!this.prevState) this.prevState = clone(s); extend(s, isFunction(state) ? state(s, this.props) : state); if (callback) (this._renderCallbacks = this._renderCallbacks || []).push(callback); triggerComponentRender(this); }, /** Immediately perform a synchronous re-render of the component. * @private */ forceUpdate: function forceUpdate() { renderComponent(this, FORCE_RENDER); }, /** Accepts `props` and `state`, and returns a new Virtual DOM tree to build. * Virtual DOM is generally constructed via [JSX](http://jasonformat.com/wtf-is-jsx). * @param {object} props Props (eg: JSX attributes) received from parent element/component * @param {object} state The component's current state * @param {object} context Context object (if a parent component has provided context) * @returns VNode */ render: function render() { return null; } }); /** Render JSX into a `parent` Element. * @param {VNode} vnode A (JSX) VNode to render * @param {Element} parent DOM element to render into * @param {Element} [merge] Attempt to re-use an existing DOM tree rooted at `merge` * @public * * @example * // render a div into <body>: * render(<div id="hello">hello!</div>, document.body); * * @example * // render a "Thing" component into #foo: * const Thing = ({ name }) => <span>{ name }</span>; * render(<Thing name="one" />, document.querySelector('#foo')); */ function render(vnode, parent, merge) { var existing = merge && merge._component && merge._componentConstructor === vnode.nodeName, built = diff(merge, vnode, {}, false), c = !existing && built._component; if (c) deepHook(c, 'componentWillMount'); if (built.parentNode !== parent) { parent.appendChild(built); } if (c) deepHook(c, 'componentDidMount'); return built; } exports.h = h; exports.Component = Component; exports.render = render; exports.rerender = rerender; exports.options = options; })); //# sourceMappingURL=preact.dev.js.map
 Type.registerNamespace("_u"); _u.ExtensibilityStrings = function() { }; _u.ExtensibilityStrings.registerClass("_u.ExtensibilityStrings"); _u.ExtensibilityStrings.l_DeleteAttachmentDoesNotExist_Text = "No se pueden eliminar los datos adjuntos porque no se encuentran los datos adjuntos con el índice de datos adjuntos."; _u.ExtensibilityStrings.l_EwsRequestOversized_Text = "La solicitud supera el límite de tamaño de 1 MB. Modifique la solicitud de EWS."; _u.ExtensibilityStrings.l_ElevatedPermissionNeededForMethod_Text = 'Para llamar al método: "{0}" se necesita un permiso elevado.'; _u.ExtensibilityStrings.l_AttachmentErrorName_Text = "Error de datos adjuntos"; _u.ExtensibilityStrings.l_InvalidEventDates_Text = "La fecha de finalización se produce antes de la fecha de inicio."; _u.ExtensibilityStrings.l_DisplayNameTooLong_Text = "Uno o varios nombres de pantalla proporcionados son demasiado largos."; _u.ExtensibilityStrings.l_NumberOfRecipientsExceeded_Text = "El número total de destinatarios del campo no puede ser mayor de {0}."; _u.ExtensibilityStrings.l_HtmlSanitizationFailure_Text = "La inmunización HTML ha fallado."; _u.ExtensibilityStrings.l_DataWriteErrorName_Text = "Error de escritura de datos"; _u.ExtensibilityStrings.l_ElevatedPermissionNeeded_Text = "Para tener acceso a los miembros protegidos de la API de JavaScript para Office se necesita un permiso elevado."; _u.ExtensibilityStrings.l_ExceededMaxNumberOfAttachments_Text = "No se pueden agregar datos adjuntos porque el mensaje ya tiene el número máximo de datos adjuntos"; _u.ExtensibilityStrings.l_InternalProtocolError_Text = 'Error de protocolo interno: "{0}".'; _u.ExtensibilityStrings.l_AttachmentDeletedBeforeUploadCompletes_Text = "El usuario quitó los datos adjuntos antes de que finalizara la carga."; _u.ExtensibilityStrings.l_OffsetNotfound_Text = "No se encontró ningún desplazamiento de esta marca de hora."; _u.ExtensibilityStrings.l_AttachmentExceededSize_Text = "Los datos adjuntos no se pueden agregar porque son demasiado grandes."; _u.ExtensibilityStrings.l_InvalidEndTime_Text = "La hora de finalización no puede ser anterior a la hora de inicio."; _u.ExtensibilityStrings.l_ParametersNotAsExpected_Text = "Los parámetros especificados no coinciden con el formato esperado."; _u.ExtensibilityStrings.l_AttachmentUploadGeneralFailure_Text = "Los datos adjuntos no se pueden agregar al elemento."; _u.ExtensibilityStrings.l_NoValidRecipientsProvided_Text = "No se proporcionaron destinatarios válidos."; _u.ExtensibilityStrings.l_InvalidAttachmentId_Text = "El id. de datos adjuntos no es válido."; _u.ExtensibilityStrings.l_CannotAddAttachmentBeforeUpgrade_Text = "No se pueden agregar datos adjuntos mientras se recupera del servidor la respuesta o el reenvío completos."; _u.ExtensibilityStrings.l_EmailAddressTooLong_Text = "Una o varias direcciones de correo electrónico proporcionadas son demasiado largas."; _u.ExtensibilityStrings.l_InvalidAttachmentPath_Text = "La ruta de los datos adjuntos no es válida."; _u.ExtensibilityStrings.l_AttachmentDeleteGeneralFailure_Text = "Los datos adjuntos no se pueden eliminar del elemento."; _u.ExtensibilityStrings.l_InternalFormatError_Text = "Hubo un error de formato interno."; _u.ExtensibilityStrings.l_InvalidDate_Text = "La entrada no se resuelve en una fecha válida."; _u.ExtensibilityStrings.l_CursorPositionChanged_Text = "El usuario cambió la posición del cursor mientras se insertaban los datos."
/*! jQuery UI - v1.11.3 - 2015-02-13 * http://jqueryui.com * Copyright jQuery Foundation and other contributors; Licensed MIT */ (function(t){"function"==typeof define&&define.amd?define(["jquery","./effect"],t):t(jQuery)})(function(t){return t.effects.effect.drop=function(e,i){var s,n=t(this),o=["position","top","bottom","left","right","opacity","height","width"],a=t.effects.setMode(n,e.mode||"hide"),r="show"===a,h=e.direction||"left",l="up"===h||"down"===h?"top":"left",c="up"===h||"left"===h?"pos":"neg",u={opacity:r?1:0};t.effects.save(n,o),n.show(),t.effects.createWrapper(n),s=e.distance||n["top"===l?"outerHeight":"outerWidth"](!0)/2,r&&n.css("opacity",0).css(l,"pos"===c?-s:s),u[l]=(r?"pos"===c?"+=":"-=":"pos"===c?"-=":"+=")+s,n.animate(u,{queue:!1,duration:e.duration,easing:e.easing,complete:function(){"hide"===a&&n.hide(),t.effects.restore(n,o),t.effects.removeWrapper(n),i()}})}});
/** * @license Highcharts JS v6.0.1 (2017-10-05) * GridAxis * * (c) 2016 Lars A. V. Cabrera * * --- WORK IN PROGRESS --- * * License: www.highcharts.com/license */ 'use strict'; (function(factory) { if (typeof module === 'object' && module.exports) { module.exports = factory; } else { factory(Highcharts); } }(function(Highcharts) { (function(H) { /** * (c) 2016 Highsoft AS * Authors: Lars A. V. Cabrera * * License: www.highcharts.com/license */ var dateFormat = H.dateFormat, each = H.each, isObject = H.isObject, pick = H.pick, wrap = H.wrap, Axis = H.Axis, Chart = H.Chart, Tick = H.Tick; // Enum for which side the axis is on. // Maps to axis.side var axisSide = { top: 0, right: 1, bottom: 2, left: 3, 0: 'top', 1: 'right', 2: 'bottom', 3: 'left' }; /** * Checks if an axis is the outer axis in its dimension. Since * axes are placed outwards in order, the axis with the highest * index is the outermost axis. * * Example: If there are multiple x-axes at the top of the chart, * this function returns true if the axis supplied is the last * of the x-axes. * * @return true if the axis is the outermost axis in its dimension; * false if not */ Axis.prototype.isOuterAxis = function() { var axis = this, thisIndex = -1, isOuter = true; each(this.chart.axes, function(otherAxis, index) { if (otherAxis.side === axis.side) { if (otherAxis === axis) { // Get the index of the axis in question thisIndex = index; // Check thisIndex >= 0 in case thisIndex has // not been found yet } else if (thisIndex >= 0 && index > thisIndex) { // There was an axis on the same side with a // higher index. Exit the loop. isOuter = false; return; } } }); // There were either no other axes on the same side, // or the other axes were not farther from the chart return isOuter; }; /** * Shortcut function to Tick.label.getBBox().width. * * @return {number} width - the width of the tick label */ Tick.prototype.getLabelWidth = function() { return this.label.getBBox().width; }; /** * Get the maximum label length. * This function can be used in states where the axis.maxLabelLength has not * been set. * * @param {boolean} force - Optional parameter to force a new calculation, even * if a value has already been set * @return {number} maxLabelLength - the maximum label length of the axis */ Axis.prototype.getMaxLabelLength = function(force) { var tickPositions = this.tickPositions, ticks = this.ticks, maxLabelLength = 0; if (!this.maxLabelLength || force) { each(tickPositions, function(tick) { tick = ticks[tick]; if (tick && tick.labelLength > maxLabelLength) { maxLabelLength = tick.labelLength; } }); this.maxLabelLength = maxLabelLength; } return this.maxLabelLength; }; /** * Adds the axis defined in axis.options.title */ Axis.prototype.addTitle = function() { var axis = this, renderer = axis.chart.renderer, axisParent = axis.axisParent, horiz = axis.horiz, opposite = axis.opposite, options = axis.options, axisTitleOptions = options.title, hasData, showAxis, textAlign; // For reuse in Axis.render hasData = axis.hasData(); axis.showAxis = showAxis = hasData || pick(options.showEmpty, true); // Disregard title generation in original Axis.getOffset() options.title = ''; if (!axis.axisTitle) { textAlign = axisTitleOptions.textAlign; if (!textAlign) { textAlign = (horiz ? { low: 'left', middle: 'center', high: 'right' } : { low: opposite ? 'right' : 'left', middle: 'center', high: opposite ? 'left' : 'right' })[axisTitleOptions.align]; } axis.axisTitle = renderer.text( axisTitleOptions.text, 0, 0, axisTitleOptions.useHTML ) .attr({ zIndex: 7, rotation: axisTitleOptions.rotation || 0, align: textAlign }) .addClass('highcharts-axis-title') .css(axisTitleOptions.style) // Add to axisParent instead of axisGroup, to ignore the space // it takes .add(axisParent); axis.axisTitle.isNew = true; } // hide or show the title depending on whether showEmpty is set axis.axisTitle[showAxis ? 'show' : 'hide'](true); }; /** * Add custom date formats */ H.dateFormats = { // Week number W: function(timestamp) { var date = new Date(timestamp), day = date.getUTCDay() === 0 ? 7 : date.getUTCDay(), time = date.getTime(), startOfYear = new Date(date.getUTCFullYear(), 0, 1, -6), dayNumber; date.setDate(date.getUTCDate() + 4 - day); dayNumber = Math.floor((time - startOfYear) / 86400000); return 1 + Math.floor(dayNumber / 7); }, // First letter of the day of the week, e.g. 'M' for 'Monday'. E: function(timestamp) { return dateFormat('%a', timestamp, true).charAt(0); } }; /** * Prevents adding the last tick label if the axis is not a category axis. * * Since numeric labels are normally placed at starts and ends of a range of * value, and this module makes the label point at the value, an "extra" label * would appear. * * @param {function} proceed - the original function */ wrap(Tick.prototype, 'addLabel', function(proceed) { var axis = this.axis, isCategoryAxis = axis.options.categories !== undefined, tickPositions = axis.tickPositions, lastTick = tickPositions[tickPositions.length - 1], isLastTick = this.pos !== lastTick; if (!axis.options.grid || isCategoryAxis || isLastTick) { proceed.apply(this); } }); /** * Center tick labels vertically and horizontally between ticks * * @param {function} proceed - the original function * * @return {object} object - an object containing x and y positions * for the tick */ wrap(Tick.prototype, 'getLabelPosition', function(proceed, x, y, label) { var retVal = proceed.apply(this, Array.prototype.slice.call(arguments, 1)), axis = this.axis, options = axis.options, tickInterval = options.tickInterval || 1, newX, newPos, axisHeight, fontSize, labelMetrics, lblB, lblH, labelCenter; // Only center tick labels if axis has option grid: true if (options.grid) { fontSize = options.labels.style.fontSize; labelMetrics = axis.chart.renderer.fontMetrics(fontSize, label); lblB = labelMetrics.b; lblH = labelMetrics.h; if (axis.horiz && options.categories === undefined) { // Center x position axisHeight = axis.axisGroup.getBBox().height; newPos = this.pos + tickInterval / 2; retVal.x = axis.translate(newPos) + axis.left; labelCenter = (axisHeight / 2) + (lblH / 2) - Math.abs(lblH - lblB); // Center y position if (axis.side === axisSide.top) { retVal.y = y - labelCenter; } else { retVal.y = y + labelCenter; } } else { // Center y position if (options.categories === undefined) { newPos = this.pos + (tickInterval / 2); retVal.y = axis.translate(newPos) + axis.top + (lblB / 2); } // Center x position newX = (this.getLabelWidth() / 2) - (axis.maxLabelLength / 2); if (axis.side === axisSide.left) { retVal.x += newX; } else { retVal.x -= newX; } } } return retVal; }); /** * Draw vertical ticks extra long to create cell floors and roofs. * Overrides the tickLength for vertical axes. * * @param {function} proceed - the original function * @returns {array} retVal - */ wrap(Axis.prototype, 'tickSize', function(proceed) { var axis = this, retVal = proceed.apply(axis, Array.prototype.slice.call(arguments, 1)), labelPadding, distance; if (axis.options.grid && !axis.horiz) { labelPadding = (Math.abs(axis.defaultLeftAxisOptions.labels.x) * 2); if (!axis.maxLabelLength) { axis.maxLabelLength = axis.getMaxLabelLength(); } distance = axis.maxLabelLength + labelPadding; retVal[0] = distance; } return retVal; }); /** * Disregards space required by axisTitle, by adding axisTitle to axisParent * instead of axisGroup, and disregarding margins and offsets related to * axisTitle. * * @param {function} proceed - the original function */ wrap(Axis.prototype, 'getOffset', function(proceed) { var axis = this, axisOffset = axis.chart.axisOffset, side = axis.side, axisHeight, tickSize, options = axis.options, axisTitleOptions = options.title, addTitle = axisTitleOptions && axisTitleOptions.text && axisTitleOptions.enabled !== false; if (axis.options.grid && isObject(axis.options.title)) { tickSize = axis.tickSize('tick')[0]; if (axisOffset[side] && tickSize) { axisHeight = axisOffset[side] + tickSize; } if (addTitle) { // Use the custom addTitle() to add it, while preventing making room // for it axis.addTitle(); } proceed.apply(axis, Array.prototype.slice.call(arguments, 1)); axisOffset[side] = pick(axisHeight, axisOffset[side]); // Put axis options back after original Axis.getOffset() has been called options.title = axisTitleOptions; } else { proceed.apply(axis, Array.prototype.slice.call(arguments, 1)); } }); /** * Prevents rotation of labels when squished, as rotating them would not * help. * * @param {function} proceed - the original function */ wrap(Axis.prototype, 'renderUnsquish', function(proceed) { if (this.options.grid) { this.labelRotation = 0; this.options.labels.rotation = 0; } proceed.apply(this); }); /** * Places leftmost tick at the start of the axis, to create a left wall. * * @param {function} proceed - the original function */ wrap(Axis.prototype, 'setOptions', function(proceed, userOptions) { var axis = this; if (userOptions.grid && axis.horiz) { userOptions.startOnTick = true; userOptions.minPadding = 0; userOptions.endOnTick = true; } proceed.apply(this, Array.prototype.slice.call(arguments, 1)); }); /** * Draw an extra line on the far side of the the axisLine, * creating cell roofs of a grid. * * @param {function} proceed - the original function */ wrap(Axis.prototype, 'render', function(proceed) { var axis = this, options = axis.options, labelPadding, distance, lineWidth, linePath, yStartIndex, yEndIndex, xStartIndex, xEndIndex, renderer = axis.chart.renderer, axisGroupBox; if (options.grid) { labelPadding = (Math.abs(axis.defaultLeftAxisOptions.labels.x) * 2); distance = axis.maxLabelLength + labelPadding; lineWidth = options.lineWidth; // Remove right wall before rendering if (axis.rightWall) { axis.rightWall.destroy(); } // Call original Axis.render() to obtain axis.axisLine and // axis.axisGroup proceed.apply(axis); axisGroupBox = axis.axisGroup.getBBox(); // Add right wall on horizontal axes if (axis.horiz) { axis.rightWall = renderer.path([ 'M', axisGroupBox.x + axis.width + 1, // account for left wall axisGroupBox.y, 'L', axisGroupBox.x + axis.width + 1, // account for left wall axisGroupBox.y + axisGroupBox.height ]) .attr({ stroke: options.tickColor || '#ccd6eb', 'stroke-width': options.tickWidth || 1, zIndex: 7, class: 'grid-wall' }) .add(axis.axisGroup); } if (axis.isOuterAxis() && axis.axisLine) { if (axis.horiz) { // -1 to avoid adding distance each time the chart updates distance = axisGroupBox.height - 1; } if (lineWidth) { linePath = axis.getLinePath(lineWidth); xStartIndex = linePath.indexOf('M') + 1; xEndIndex = linePath.indexOf('L') + 1; yStartIndex = linePath.indexOf('M') + 2; yEndIndex = linePath.indexOf('L') + 2; // Negate distance if top or left axis if (axis.side === axisSide.top || axis.side === axisSide.left) { distance = -distance; } // If axis is horizontal, reposition line path vertically if (axis.horiz) { linePath[yStartIndex] = linePath[yStartIndex] + distance; linePath[yEndIndex] = linePath[yEndIndex] + distance; } else { // If axis is vertical, reposition line path horizontally linePath[xStartIndex] = linePath[xStartIndex] + distance; linePath[xEndIndex] = linePath[xEndIndex] + distance; } if (!axis.axisLineExtra) { axis.axisLineExtra = renderer.path(linePath) .attr({ stroke: options.lineColor, 'stroke-width': lineWidth, zIndex: 7 }) .add(axis.axisGroup); } else { axis.axisLineExtra.animate({ d: linePath }); } // show or hide the line depending on options.showEmpty axis.axisLine[axis.showAxis ? 'show' : 'hide'](true); } } } else { proceed.apply(axis); } }); /** * Wraps chart rendering with the following customizations: * 1. Prohibit timespans of multitudes of a time unit * 2. Draw cell walls on vertical axes * * @param {function} proceed - the original function */ wrap(Chart.prototype, 'render', function(proceed) { // 25 is optimal height for default fontSize (11px) // 25 / 11 ≈ 2.28 var fontSizeToCellHeightRatio = 25 / 11, fontMetrics, fontSize; each(this.axes, function(axis) { var options = axis.options; if (options.grid) { fontSize = options.labels.style.fontSize; fontMetrics = axis.chart.renderer.fontMetrics(fontSize); // Prohibit timespans of multitudes of a time unit, // e.g. two days, three weeks, etc. if (options.type === 'datetime') { options.units = [ ['millisecond', [1]], ['second', [1]], ['minute', [1]], ['hour', [1]], ['day', [1]], ['week', [1]], ['month', [1]], ['year', null] ]; } // Make tick marks taller, creating cell walls of a grid. // Use cellHeight axis option if set if (axis.horiz) { options.tickLength = options.cellHeight || fontMetrics.h * fontSizeToCellHeightRatio; } else { options.tickWidth = 1; if (!options.lineWidth) { options.lineWidth = 1; } } } }); // Call original Chart.render() proceed.apply(this); }); }(Highcharts)); }));
/* * @author Interactive agency «Central marketing» http://centralmarketing.ru * @copyright Copyright (c) 2015, Interactive agency «Central marketing» * @license http://opensource.org/licenses/MIT The MIT License (MIT) * @version 3.1.6 at 30/09/2015 (19:35) * * goodshare.js * * Useful jQuery plugin that will help your website visitors share a link on social networks and microblogs. * Easy to install and configuring on any of your website! * * @category jQuery plugin */ ;(function($, window, document, undefined) { $(document).ready(function() { goodshare = { init: function(_element, _options) { /* * Default options: * * type = vk * url = current browser adress stroke * title = current document <title> * text = current document <meta property="og:description" ... /> * image = current document <meta property="og:image" ... /> */ var self = goodshare, options = $.extend({ type: 'vk', url: location.href, title: document.title, text: $('meta[property="og:description"]').attr('content'), image: $('meta[property="og:image"]').attr('content') }, $(_element).data(), _options); /* * Open popup */ if (self.popup(link = self[options.type](options)) !== null) return false; }, /* * Share link > Vkontakte * @see http://vk.com */ vk: function(_options) { var options = $.extend({ url: location.href, title: document.title, text: '', image: '' }, _options); return 'http://vk.com/share.php?' + 'url=' + encodeURIComponent(options.url) + '&title=' + encodeURIComponent(options.title) + '&description=' + encodeURIComponent(options.text) + '&image=' + encodeURIComponent(options.image); }, /* * Share link > Odnoklassniki * @see http://ok.ru */ ok: function(_options) { var options = $.extend({ url: location.href, title: document.title }, _options); return 'http://www.odnoklassniki.ru/dk?st.cmd=addShare&st.s=1' + '&st.comments=' + encodeURIComponent(options.title) + '&st._surl=' + encodeURIComponent(options.url); }, /* * Share link > Facebook * @see http://facebook.com */ fb: function(_options) { var options = $.extend({ url: location.href, title: document.title }, _options); return 'http://www.facebook.com/sharer.php?' + 'u=' + encodeURIComponent(options.url); }, /* * Share link > LiveJournal * @see http://livejournal.com */ lj: function(_options) { var options = $.extend({ url: location.href, title: document.title, text: '' }, _options); return 'http://livejournal.com/update.bml?' + 'subject=' + encodeURIComponent(options.title) + '&event=' + encodeURIComponent('<a href="' + options.url + '">' + options.title + '</a> ' + options.text); }, /* * Share link > Twitter * @see http://twitter.com */ tw: function(_options) { var options = $.extend({ url: location.href, title: document.title }, _options); return 'http://twitter.com/share?' + 'url=' + encodeURIComponent(options.url) + '&text=' + encodeURIComponent(options.title); }, /* * Share link > Google Plus * @see http://plus.google.com */ gp: function(_options) { var options = $.extend({ url: location.href }, _options); return 'https://plus.google.com/share?' + 'url=' + encodeURIComponent(options.url); }, /* * Share link > My@Mail.Ru * @see http://my.mail.ru */ mr: function(_options) { var options = $.extend({ url: location.href, title: document.title, image: '', text: '' }, _options); return 'http://connect.mail.ru/share?' + 'url=' + encodeURIComponent(options.url) + '&title=' + encodeURIComponent(options.title) + '&description=' + encodeURIComponent(options.text) + '&imageurl=' + encodeURIComponent(options.image); }, /* * Share link > LinkedIn * @see http://linkedin.com */ li: function(_options) { var options = $.extend({ url: location.href, title: document.title }, _options); return 'http://www.linkedin.com/shareArticle?' + 'url=' + encodeURIComponent(options.url) + '&text=' + encodeURIComponent(options.title) + '&mini=true'; }, /* * Share link > tumblr * @see http://tumblr.com */ tm: function(_options) { var options = $.extend({ url: location.href, title: document.title, text: '' }, _options); return 'http://www.tumblr.com/share/link?' + 'url=' + encodeURIComponent(options.url) + '&name=' + encodeURIComponent(options.title) + '&description=' + encodeURIComponent(options.text); }, /* * Share link > Blogger * @see https://www.blogger.com */ bl: function(_options) { var options = $.extend({ url: location.href, title: document.title }, _options); return 'https://www.blogger.com/blog-this.g?' + 'u=' + encodeURIComponent(options.url) + '&n=' + encodeURIComponent(options.title); }, /* * Share link > Pinterest * @see http://www.pinterest.com */ pt: function(_options) { var options = $.extend({ url: location.href, title: document.title }, _options); return 'https://www.pinterest.com/pin/create/button/?' + 'url=' + encodeURIComponent(options.url) + '&description=' + encodeURIComponent(options.title); }, /* * Share link > Evernote * @see http://www.evernote.com */ en: function(_options) { var options = $.extend({ url: location.href, title: document.title, text: '' }, _options); return 'https://www.evernote.com/clip.action?' + 'url=' + encodeURIComponent(options.url) + '&title=' + encodeURIComponent(options.title) + '&body=' + encodeURIComponent(options.text + '<br/><a href="' + options.url + '">' + options.title + '</a>'); }, /* * Share link > Digg * @see http://www.digg.com */ di: function(_options) { var options = $.extend({ url: location.href, title: document.title }, _options); return 'http://digg.com/submit?' + 'url=' + encodeURIComponent(options.url) + '&title=' + encodeURIComponent(options.title); }, /* * Share link > Reddit * @see http://www.reddit.com */ rd: function(_options) { var options = $.extend({ url: location.href, title: document.title }, _options); return 'http://www.reddit.com/submit?' + 'url=' + encodeURIComponent(options.url) + '&title=' + encodeURIComponent(options.title); }, /* * Share link > StumbleUpon * @see http://www.stumbleupon.com */ su: function(_options) { var options = $.extend({ url: location.href, title: document.title }, _options); return 'http://www.stumbleupon.com/submit?' + 'url=' + encodeURIComponent(options.url) + '&title=' + encodeURIComponent(options.title); }, /* * Share link > Pocket * @see https://getpocket.com */ po: function(_options) { var options = $.extend({ url: location.href, title: document.title }, _options); return 'https://getpocket.com/save?' + 'url=' + encodeURIComponent(options.url) + '&title=' + encodeURIComponent(options.title); }, /* * Share link > Surfingbird * @see http://www.surfingbird.ru */ sb: function(_options) { var options = $.extend({ url: location.href, title: document.title, text: '' }, _options); return 'http://surfingbird.ru/share?' + 'url=' + encodeURIComponent(options.url) + '&title=' + encodeURIComponent(options.title) + '&description=' + encodeURIComponent(options.text); }, /* * Share link > Buffer * @see http://buffer.com */ bf: function(_options) { var options = $.extend({ url: location.href, title: document.title }, _options); return 'https://buffer.com/add?' + 'url=' + encodeURIComponent(options.url) + '&text=' + encodeURIComponent(options.title); }, /* * Share link > Readability * @see http://www.readability.com */ ra: function(_options) { var options = $.extend({ url: location.href }, _options); return 'http://www.readability.com/save?' + 'url=' + encodeURIComponent(options.url); }, /* * Popup window */ popup: function(url) { return window.open(url, '', 'toolbar=0,status=0,scrollbars=0,width=630,height=440'); } }; /* * Function roundCount() * Return rounded and pretty value of share count. * * @example roundCount(response.shares) // Rounded value of Facebook counter. */ var roundCount = function(number) { if (number > 999 && number <= 999999) var result = number/1000 + 'k'; else if (number > 999999) var result = '>1M'; else var result = number; return result; }; /* * Function existCount() * Check exist counter element. * * @example existCount('[data-counter="fb"]') // Checked exist Facebook counter element. */ var existCount = function(element) { return ($(element).length > 0); }; /* * Share counter > Vkontakte * @see http://vk.com/dev */ if (existCount('[data-counter="vk"]')) { $.getJSON('https://vk.com/share.php?act=count&index=1&url=' + encodeURIComponent(location.href) + '&callback=?', function(response) {}); VK = {}; VK.Share = {}; VK.Share.count = function(index, count) { $('[data-counter="vk"]').text(roundCount(count)); } }; /* * Share counter > Facebook * @see https://developers.facebook.com */ if (existCount('[data-counter="fb"]')) { $.getJSON('http://graph.facebook.com/?id=' + encodeURIComponent(location.href) + '&callback=?', function(response) { if (response.shares === undefined) $('[data-counter="fb"]').text('0'); else $('[data-counter="fb"]').text(roundCount(response.shares)); }) }; /* * Share counter > Odnoklassniki * @see https://apiok.ru */ if (existCount('[data-counter="ok"]')) { $.getJSON('https://connect.ok.ru/dk?st.cmd=extLike&uid=1&ref=' + encodeURIComponent(location.href) + '&callback=?', function(response) {}); ODKL = {}; ODKL.updateCount = function(index, count) { $('[data-counter="ok"]').text(roundCount(count)); } }; /* * Share counter > Twitter * @see https://dev.twitter.com */ if (existCount('[data-counter="tw"]')) { $.getJSON('http://cdn.api.twitter.com/1/urls/count.json?url=' + encodeURIComponent(location.href) + '&callback=?', function(response) { $('[data-counter="tw"]').text(roundCount(response.count)); }) }; /* * Share counter > Google Plus * @see https://developers.google.com/+/ */ if (existCount('[data-counter="gp"]')) { $.ajax({ type: 'POST', url: 'https://clients6.google.com/rpc', processData: true, contentType: 'application/json', data: JSON.stringify({ 'method': 'pos.plusones.get', 'id': location.href, 'params': { 'nolog': true, 'id': location.href, 'source': 'widget', 'userId': '@viewer', 'groupId': '@self' }, 'jsonrpc': '2.0', 'key': 'p', 'apiVersion': 'v1' }), success: function(response) { $('[data-counter="gp"]').text(roundCount(response.result.metadata.globalCounts.count)); } }) }; /* * Share counter > My@Mail.Ru * @see http://api.mail.ru */ if (existCount('[data-counter="mr"]')) { $.getJSON('http://connect.mail.ru/share_count?url_list=' + encodeURIComponent(location.href) + '&callback=1&func=?', function(response) { var url = encodeURIComponent(location.href); for (var url in response) { if (response.hasOwnProperty(url)) { var count = response[url].shares; break; } } if ($.isEmptyObject(response)) $('[data-counter="mr"]').text('0'); else $('[data-counter="mr"]').text(roundCount(count)); }) }; /* * Share counter > LinkedIn * @see https://developer.linkedin.com */ if (existCount('[data-counter="li"]')) { $.getJSON('http://www.linkedin.com/countserv/count/share?url=' + encodeURIComponent(location.href) + '&callback=?', function(response) { $('[data-counter="li"]').text(roundCount(response.count)); }) } /* * Share counter > tumblr * @see https://www.tumblr.com/developers */ if (existCount('[data-counter="tm"]')) { $.getJSON('http://api.tumblr.com/v2/share/stats?url=' + encodeURIComponent(location.href) + '&callback=?', function(response) { $('[data-counter="tm"]').text(roundCount(response.response.note_count)); }) }; /* * Share counter > Pinterest * @see https://developers.pinterest.com */ if (existCount('[data-counter="pt"]')) { $.getJSON('http://api.pinterest.com/v1/urls/count.json?url=' + encodeURIComponent(location.href) + '&callback=?', function(response) { $('[data-counter="pt"]').text(roundCount(response.count)); }) }; /* * Share counter > Reddit * @see https://www.reddit.com/dev/api */ if (existCount('[data-counter="rd"]')) { $.getJSON('https://www.reddit.com/api/info.json?url=' + encodeURIComponent(location.href) + '&jsonp=?', function(response) { var count = response.data.children; if (count.length === 0) $('[data-counter="rd"]').text('0'); else $('[data-counter="rd"]').text(roundCount(count[0].data.score)); }) }; /* * Share counter > StumbleUpon * @see http://help.stumbleupon.com */ if (existCount('[data-counter="su"]')) { $.getJSON('http://query.yahooapis.com/v1/public/yql?q=' + encodeURIComponent('select * from html where url="http://www.stumbleupon.com/services/1.01/badge.getinfo?url=' + location.href + '" and xpath="*"') + '&format=json&callback=?', function(response) { var count = $.parseJSON(response.query.results.html.body); if (count.result.views === undefined) $('[data-counter="su"]').text('0'); else $('[data-counter="su"]').text(roundCount(count.result.views)); }) }; /* * Share counter > Pocket * @see https://widgets.getpocket.com/v1/button?count=horizontal&url=[URL_HERE] */ if (existCount('[data-counter="po"]')) { $.getJSON('http://query.yahooapis.com/v1/public/yql?q=' + encodeURIComponent('select * from html where url="https://widgets.getpocket.com/v1/button?count=horizontal&url=' + location.href + '" and xpath="*"') + '&format=json&callback=?', function(response) { $('[data-counter="po"]').text(roundCount(response.query.results.html.body.div.a.span.em.content)); }) }; /* * Share counter > Surfingbird * @see http://surfingbird.ru/button?url=[URL_HERE] */ if (existCount('[data-counter="sb"]')) { $.getJSON('http://anyorigin.com/dev/get?url=' + encodeURIComponent('http://surfingbird.ru/button?url=' + location.href) + '&callback=?', function(response) { var count = $(response.contents).find('span.stats-num').text(); $('[data-counter="sb"]').text(roundCount(count)); }) }; /* * Share counter > Buffer * @see https://buffer.com/developers */ if (existCount('[data-counter="bf"]')) { $.getJSON('https://api.bufferapp.com/1/links/shares.json?url=' + encodeURIComponent(location.href) + '&callback=?', function(response) { $('[data-counter="bf"]').text(roundCount(response.shares)); }) }; /* * Init goodshare.js click */ $(document).on('click', '.goodshare', function(event) { event.preventDefault(); goodshare.init(this); }); }); })(jQuery, window, document);
/** * Select2 Norwegian translation. * * Author: Torgeir Veimo <torgeir.veimo@gmail.com> */(function(e){"use strict";e.extend(e.fn.select2.defaults,{formatNoMatches:function(){return"Ingen treff"},formatInputTooShort:function(e,t){var n=t-e.length;return"Vennligst skriv inn "+n+(n>1?" flere tegn":" tegn til")},formatInputTooLong:function(e,t){var n=e.length-t;return"Vennligst fjern "+n+" tegn"},formatSelectionTooBig:function(e){return"Du kan velge maks "+e+" elementer"},formatLoadMore:function(e){return"Laster flere resultater…"},formatSearching:function(){return"Søker…"}})})(jQuery);
define(['../lang/toString', './WHITE_SPACES', './ltrim', './rtrim'], function(toString, WHITE_SPACES, ltrim, rtrim){ /** * Remove white-spaces from beginning and end of string. */ function trim(str, chars) { str = toString(str); chars = chars || WHITE_SPACES; return ltrim(rtrim(str, chars), chars); } return trim; });
/* axios v0.8.0 | (c) 2015 by Matt Zabriskie */ (function webpackUniversalModuleDefinition(root, factory) { if(typeof exports === 'object' && typeof module === 'object') module.exports = factory(); else if(typeof define === 'function' && define.amd) define([], factory); else if(typeof exports === 'object') exports["axios"] = factory(); else root["axios"] = factory(); })(this, function() { return /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) /******/ return installedModules[moduleId].exports; /******/ /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ exports: {}, /******/ id: moduleId, /******/ loaded: false /******/ }; /******/ /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ /******/ // Flag the module as loaded /******/ module.loaded = true; /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /******/ /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(0); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ function(module, exports, __webpack_require__) { module.exports = __webpack_require__(1); /***/ }, /* 1 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var defaults = __webpack_require__(2); var utils = __webpack_require__(3); var dispatchRequest = __webpack_require__(4); var InterceptorManager = __webpack_require__(12); var isAbsoluteURL = __webpack_require__(13); var combineURLs = __webpack_require__(14); function Axios (defaultConfig) { this.defaultConfig = utils.merge({ headers: {}, timeout: defaults.timeout, transformRequest: defaults.transformRequest, transformResponse: defaults.transformResponse }, defaultConfig); this.interceptors = { request: new InterceptorManager(), response: new InterceptorManager() }; } Axios.prototype.request = function (config) { // Allow for axios('example/url'[, config]) a la fetch API if (typeof config === 'string') { config = utils.merge({ url: arguments[0] }, arguments[1]); } config = utils.merge(this.defaultConfig, { method: 'get' }, config); if (config.baseURL && !isAbsoluteURL(config.url)) { config.url = combineURLs(config.baseURL, config.url); } // Don't allow overriding defaults.withCredentials config.withCredentials = config.withCredentials || defaults.withCredentials; // Hook up interceptors middleware var chain = [dispatchRequest, undefined]; var promise = Promise.resolve(config); this.interceptors.request.forEach(function (interceptor) { chain.unshift(interceptor.fulfilled, interceptor.rejected); }); this.interceptors.response.forEach(function (interceptor) { chain.push(interceptor.fulfilled, interceptor.rejected); }); while (chain.length) { promise = promise.then(chain.shift(), chain.shift()); } return promise; }; var defaultInstance = new Axios(); var axios = module.exports = bind(Axios.prototype.request, defaultInstance); axios.create = function (defaultConfig) { return new Axios(defaultConfig); }; // Expose defaults axios.defaults = defaults; // Expose all/spread axios.all = function (promises) { return Promise.all(promises); }; axios.spread = __webpack_require__(15); // Expose interceptors axios.interceptors = defaultInstance.interceptors; // Helpers function bind (fn, thisArg) { return function () { var args = new Array(arguments.length); for (var i = 0; i < args.length; i++) { args[i] = arguments[i]; } return fn.apply(thisArg, args); }; } // Provide aliases for supported request methods utils.forEach(['delete', 'get', 'head'], function (method) { Axios.prototype[method] = function (url, config) { return this.request(utils.merge(config || {}, { method: method, url: url })); }; axios[method] = bind(Axios.prototype[method], defaultInstance); }); utils.forEach(['post', 'put', 'patch'], function (method) { Axios.prototype[method] = function (url, data, config) { return this.request(utils.merge(config || {}, { method: method, url: url, data: data })); }; axios[method] = bind(Axios.prototype[method], defaultInstance); }); /***/ }, /* 2 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var utils = __webpack_require__(3); var PROTECTION_PREFIX = /^\)\]\}',?\n/; var DEFAULT_CONTENT_TYPE = { 'Content-Type': 'application/x-www-form-urlencoded' }; module.exports = { transformRequest: [function (data, headers) { if(utils.isFormData(data)) { return data; } if (utils.isArrayBuffer(data)) { return data; } if (utils.isArrayBufferView(data)) { return data.buffer; } if (utils.isObject(data) && !utils.isFile(data) && !utils.isBlob(data)) { // Set application/json if no Content-Type has been specified if (!utils.isUndefined(headers)) { utils.forEach(headers, function (val, key) { if (key.toLowerCase() === 'content-type') { headers['Content-Type'] = val; } }); if (utils.isUndefined(headers['Content-Type'])) { headers['Content-Type'] = 'application/json;charset=utf-8'; } } return JSON.stringify(data); } return data; }], transformResponse: [function (data) { if (typeof data === 'string') { data = data.replace(PROTECTION_PREFIX, ''); try { data = JSON.parse(data); } catch (e) { /* Ignore */ } } return data; }], headers: { common: { 'Accept': 'application/json, text/plain, */*' }, patch: utils.merge(DEFAULT_CONTENT_TYPE), post: utils.merge(DEFAULT_CONTENT_TYPE), put: utils.merge(DEFAULT_CONTENT_TYPE) }, timeout: 0, xsrfCookieName: 'XSRF-TOKEN', xsrfHeaderName: 'X-XSRF-TOKEN' }; /***/ }, /* 3 */ /***/ function(module, exports) { 'use strict'; /*global toString:true*/ // utils is a library of generic helper functions non-specific to axios var toString = Object.prototype.toString; /** * Determine if a value is an Array * * @param {Object} val The value to test * @returns {boolean} True if value is an Array, otherwise false */ function isArray(val) { return toString.call(val) === '[object Array]'; } /** * Determine if a value is an ArrayBuffer * * @param {Object} val The value to test * @returns {boolean} True if value is an ArrayBuffer, otherwise false */ function isArrayBuffer(val) { return toString.call(val) === '[object ArrayBuffer]'; } /** * Determine if a value is a FormData * * @param {Object} val The value to test * @returns {boolean} True if value is an FormData, otherwise false */ function isFormData(val) { return toString.call(val) === '[object FormData]'; } /** * Determine if a value is a view on an ArrayBuffer * * @param {Object} val The value to test * @returns {boolean} True if value is a view on an ArrayBuffer, otherwise false */ function isArrayBufferView(val) { if ((typeof ArrayBuffer !== 'undefined') && (ArrayBuffer.isView)) { return ArrayBuffer.isView(val); } else { return (val) && (val.buffer) && (val.buffer instanceof ArrayBuffer); } } /** * Determine if a value is a String * * @param {Object} val The value to test * @returns {boolean} True if value is a String, otherwise false */ function isString(val) { return typeof val === 'string'; } /** * Determine if a value is a Number * * @param {Object} val The value to test * @returns {boolean} True if value is a Number, otherwise false */ function isNumber(val) { return typeof val === 'number'; } /** * Determine if a value is undefined * * @param {Object} val The value to test * @returns {boolean} True if the value is undefined, otherwise false */ function isUndefined(val) { return typeof val === 'undefined'; } /** * Determine if a value is an Object * * @param {Object} val The value to test * @returns {boolean} True if value is an Object, otherwise false */ function isObject(val) { return val !== null && typeof val === 'object'; } /** * Determine if a value is a Date * * @param {Object} val The value to test * @returns {boolean} True if value is a Date, otherwise false */ function isDate(val) { return toString.call(val) === '[object Date]'; } /** * Determine if a value is a File * * @param {Object} val The value to test * @returns {boolean} True if value is a File, otherwise false */ function isFile(val) { return toString.call(val) === '[object File]'; } /** * Determine if a value is a Blob * * @param {Object} val The value to test * @returns {boolean} True if value is a Blob, otherwise false */ function isBlob(val) { return toString.call(val) === '[object Blob]'; } /** * Trim excess whitespace off the beginning and end of a string * * @param {String} str The String to trim * @returns {String} The String freed of excess whitespace */ function trim(str) { return str.replace(/^\s*/, '').replace(/\s*$/, ''); } /** * Determine if we're running in a standard browser environment * * This allows axios to run in a web worker, and react-native. * Both environments support XMLHttpRequest, but not fully standard globals. * * web workers: * typeof window -> undefined * typeof document -> undefined * * react-native: * typeof document.createElement -> undefined */ function isStandardBrowserEnv() { return ( typeof window !== 'undefined' && typeof document !== 'undefined' && typeof document.createElement === 'function' ); } /** * Iterate over an Array or an Object invoking a function for each item. * * If `obj` is an Array callback will be called passing * the value, index, and complete array for each item. * * If 'obj' is an Object callback will be called passing * the value, key, and complete object for each property. * * @param {Object|Array} obj The object to iterate * @param {Function} fn The callback to invoke for each item */ function forEach(obj, fn) { // Don't bother if no value provided if (obj === null || typeof obj === 'undefined') { return; } // Force an array if not already something iterable if (typeof obj !== 'object' && !isArray(obj)) { obj = [obj]; } // Iterate over array values if (isArray(obj)) { for (var i = 0, l = obj.length; i < l; i++) { fn.call(null, obj[i], i, obj); } } // Iterate over object keys else { for (var key in obj) { if (obj.hasOwnProperty(key)) { fn.call(null, obj[key], key, obj); } } } } /** * Accepts varargs expecting each argument to be an object, then * immutably merges the properties of each object and returns result. * * When multiple objects contain the same key the later object in * the arguments list will take precedence. * * Example: * * ```js * var result = merge({foo: 123}, {foo: 456}); * console.log(result.foo); // outputs 456 * ``` * * @param {Object} obj1 Object to merge * @returns {Object} Result of all merge properties */ function merge(/*obj1, obj2, obj3, ...*/) { var result = {}; var assignValue = function (val, key) { result[key] = val; }; var length = arguments.length; for (var i = 0; i < length; i++) { forEach(arguments[i], assignValue); } return result; } module.exports = { isArray: isArray, isArrayBuffer: isArrayBuffer, isFormData: isFormData, isArrayBufferView: isArrayBufferView, isString: isString, isNumber: isNumber, isObject: isObject, isUndefined: isUndefined, isDate: isDate, isFile: isFile, isBlob: isBlob, isStandardBrowserEnv: isStandardBrowserEnv, forEach: forEach, merge: merge, trim: trim }; /***/ }, /* 4 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; /** * Dispatch a request to the server using whichever adapter * is supported by the current environment. * * @param {object} config The config that is to be used for the request * @returns {Promise} The Promise to be fulfilled */ module.exports = function dispatchRequest(config) { return new Promise(function (resolve, reject) { try { // For browsers use XHR adapter if ((typeof XMLHttpRequest !== 'undefined') || (typeof ActiveXObject !== 'undefined')) { __webpack_require__(5)(resolve, reject, config); } // For node use HTTP adapter else if (typeof process !== 'undefined') { __webpack_require__(5)(resolve, reject, config); } } catch (e) { reject(e); } }); }; /***/ }, /* 5 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; /*global ActiveXObject:true*/ var defaults = __webpack_require__(2); var utils = __webpack_require__(3); var buildURL = __webpack_require__(6); var parseHeaders = __webpack_require__(7); var transformData = __webpack_require__(8); var isURLSameOrigin = __webpack_require__(9); var btoa = window.btoa || __webpack_require__(10) module.exports = function xhrAdapter(resolve, reject, config) { // Transform request data var data = transformData( config.data, config.headers, config.transformRequest ); // Merge headers var requestHeaders = utils.merge( defaults.headers.common, defaults.headers[config.method] || {}, config.headers || {} ); if (utils.isFormData(data)) { delete requestHeaders['Content-Type']; // Let the browser set it } var adapter = (XMLHttpRequest || ActiveXObject); var loadEvent = 'onreadystatechange'; var xDomain = false; // For IE 8/9 CORS support if(!isURLSameOrigin(config.url) && window.XDomainRequest){ adapter = window.XDomainRequest; loadEvent = 'onload'; xDomain = true; } // HTTP basic authentication if (config.auth) { var username = config.auth.username || ''; var password = config.auth.password || ''; requestHeaders['Authorization'] = 'Basic: ' + btoa(username + ':' + password); } // Create the request var request = new adapter('Microsoft.XMLHTTP'); request.open(config.method.toUpperCase(), buildURL(config.url, config.params, config.paramsSerializer), true); // Set the request timeout in MS request.timeout = config.timeout; // Listen for ready state request[loadEvent] = function () { if (request && (request.readyState === 4 || xDomain)) { // Prepare the response var responseHeaders = xDomain ? null : parseHeaders(request.getAllResponseHeaders()); var responseData = ['text', ''].indexOf(config.responseType || '') !== -1 ? request.responseText : request.response; var response = { data: transformData( responseData, responseHeaders, config.transformResponse ), status: request.status, statusText: request.statusText, headers: responseHeaders, config: config }; // Resolve or reject the Promise based on the status ((request.status >= 200 && request.status < 300) || (request.responseText && xDomain) ? resolve : reject)(response); // Clean up request request = null; } }; // Add xsrf header // This is only done if running in a standard browser environment. // Specifically not if we're in a web worker, or react-native. if (utils.isStandardBrowserEnv()) { var cookies = __webpack_require__(11); // Add xsrf header var xsrfValue = isURLSameOrigin(config.url) ? cookies.read(config.xsrfCookieName || defaults.xsrfCookieName) : undefined; if (xsrfValue) { requestHeaders[config.xsrfHeaderName || defaults.xsrfHeaderName] = xsrfValue; } } // Add headers to the request if(!xDomain) utils.forEach(requestHeaders, function (val, key) { // Remove Content-Type if data is undefined if (!data && key.toLowerCase() === 'content-type') { delete requestHeaders[key]; } // Otherwise add header to the request else { request.setRequestHeader(key, val); } }); // Add withCredentials to request if needed if (config.withCredentials) { request.withCredentials = true; } // Add responseType to request if needed if (config.responseType) { try { request.responseType = config.responseType; } catch (e) { if (request.responseType !== 'json') { throw e; } } } if (utils.isArrayBuffer(data)) { data = new DataView(data); } // Send the request request.send(data); }; /***/ }, /* 6 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var utils = __webpack_require__(3); function encode(val) { return encodeURIComponent(val). replace(/%40/gi, '@'). replace(/%3A/gi, ':'). replace(/%24/g, '$'). replace(/%2C/gi, ','). replace(/%20/g, '+'). replace(/%5B/gi, '['). replace(/%5D/gi, ']'); } /** * Build a URL by appending params to the end * * @param {string} url The base of the url (e.g., http://www.google.com) * @param {object} [params] The params to be appended * @returns {string} The formatted url */ module.exports = function buildURL(url, params, paramsSerializer) { if (!params) { return url; } var serializedParams; if (paramsSerializer) { serializedParams = paramsSerializer(params); } else { var parts = []; utils.forEach(params, function (val, key) { if (val === null || typeof val === 'undefined') { return; } if (utils.isArray(val)) { key = key + '[]'; } if (!utils.isArray(val)) { val = [val]; } utils.forEach(val, function (v) { if (utils.isDate(v)) { v = v.toISOString(); } else if (utils.isObject(v)) { v = JSON.stringify(v); } parts.push(encode(key) + '=' + encode(v)); }); }); serializedParams = parts.join('&'); } if (serializedParams) { url += (url.indexOf('?') === -1 ? '?' : '&') + serializedParams; } return url; }; /***/ }, /* 7 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var utils = __webpack_require__(3); /** * Parse headers into an object * * ``` * Date: Wed, 27 Aug 2014 08:58:49 GMT * Content-Type: application/json * Connection: keep-alive * Transfer-Encoding: chunked * ``` * * @param {String} headers Headers needing to be parsed * @returns {Object} Headers parsed into an object */ module.exports = function parseHeaders(headers) { var parsed = {}, key, val, i; if (!headers) { return parsed; } utils.forEach(headers.split('\n'), function(line) { i = line.indexOf(':'); key = utils.trim(line.substr(0, i)).toLowerCase(); val = utils.trim(line.substr(i + 1)); if (key) { parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val; } }); return parsed; }; /***/ }, /* 8 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var utils = __webpack_require__(3); /** * Transform the data for a request or a response * * @param {Object|String} data The data to be transformed * @param {Array} headers The headers for the request or response * @param {Array|Function} fns A single function or Array of functions * @returns {*} The resulting transformed data */ module.exports = function transformData(data, headers, fns) { utils.forEach(fns, function (fn) { data = fn(data, headers); }); return data; }; /***/ }, /* 9 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var utils = __webpack_require__(3); module.exports = ( utils.isStandardBrowserEnv() ? // Standard browser envs have full support of the APIs needed to test // whether the request URL is of the same origin as current location. (function () { var msie = /(msie|trident)/i.test(navigator.userAgent); var urlParsingNode = document.createElement('a'); var originURL; /** * Parse a URL to discover it's components * * @param {String} url The URL to be parsed * @returns {Object} */ function resolveURL(url) { var href = url; if (msie) { // IE needs attribute set twice to normalize properties urlParsingNode.setAttribute('href', href); href = urlParsingNode.href; } urlParsingNode.setAttribute('href', href); // urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils return { href: urlParsingNode.href, protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '', host: urlParsingNode.host, search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, '') : '', hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '', hostname: urlParsingNode.hostname, port: urlParsingNode.port, pathname: (urlParsingNode.pathname.charAt(0) === '/') ? urlParsingNode.pathname : '/' + urlParsingNode.pathname }; } originURL = resolveURL(window.location.href); /** * Determine if a URL shares the same origin as the current location * * @param {String} requestURL The URL to test * @returns {boolean} True if URL shares the same origin, otherwise false */ return function isURLSameOrigin(requestURL) { var parsed = (utils.isString(requestURL)) ? resolveURL(requestURL) : requestURL; return (parsed.protocol === originURL.protocol && parsed.host === originURL.host); }; })() : // Non standard browser envs (web workers, react-native) lack needed support. (function () { return function isURLSameOrigin() { return true; }; })() ); /***/ }, /* 10 */ /***/ function(module, exports) { 'use strict'; // btoa polyfill for IE<10 courtesy https://github.com/davidchambers/Base64.js var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='; function InvalidCharacterError(message) { this.message = message; } InvalidCharacterError.prototype = new Error; InvalidCharacterError.prototype.name = 'InvalidCharacterError'; function btoa (input) { var str = String(input); for ( // initialize result and counter var block, charCode, idx = 0, map = chars, output = ''; // if the next str index does not exist: // change the mapping table to "=" // check if d has no fractional digits str.charAt(idx | 0) || (map = '=', idx % 1); // "8 - idx % 1 * 8" generates the sequence 2, 4, 6, 8 output += map.charAt(63 & block >> 8 - idx % 1 * 8) ) { charCode = str.charCodeAt(idx += 3/4); if (charCode > 0xFF) { throw new InvalidCharacterError('\'btoa\' failed: The string to be encoded contains characters outside of the Latin1 range.'); } block = block << 8 | charCode; } return output; }; module.exports = btoa /***/ }, /* 11 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var utils = __webpack_require__(3); module.exports = ( utils.isStandardBrowserEnv() ? // Standard browser envs support document.cookie (function () { return { write: function write(name, value, expires, path, domain, secure) { var cookie = []; cookie.push(name + '=' + encodeURIComponent(value)); if (utils.isNumber(expires)) { cookie.push('expires=' + new Date(expires).toGMTString()); } if (utils.isString(path)) { cookie.push('path=' + path); } if (utils.isString(domain)) { cookie.push('domain=' + domain); } if (secure === true) { cookie.push('secure'); } document.cookie = cookie.join('; '); }, read: function read(name) { var match = document.cookie.match(new RegExp('(^|;\\s*)(' + name + ')=([^;]*)')); return (match ? decodeURIComponent(match[3]) : null); }, remove: function remove(name) { this.write(name, '', Date.now() - 86400000); } }; })() : // Non standard browser env (web workers, react-native) lack needed support. (function () { return { write: function write() {}, read: function read() { return null; }, remove: function remove() {} }; })() ); /***/ }, /* 12 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var utils = __webpack_require__(3); function InterceptorManager() { this.handlers = []; } /** * Add a new interceptor to the stack * * @param {Function} fulfilled The function to handle `then` for a `Promise` * @param {Function} rejected The function to handle `reject` for a `Promise` * * @return {Number} An ID used to remove interceptor later */ InterceptorManager.prototype.use = function (fulfilled, rejected) { this.handlers.push({ fulfilled: fulfilled, rejected: rejected }); return this.handlers.length - 1; }; /** * Remove an interceptor from the stack * * @param {Number} id The ID that was returned by `use` */ InterceptorManager.prototype.eject = function (id) { if (this.handlers[id]) { this.handlers[id] = null; } }; /** * Iterate over all the registered interceptors * * This method is particularly useful for skipping over any * interceptors that may have become `null` calling `remove`. * * @param {Function} fn The function to call for each interceptor */ InterceptorManager.prototype.forEach = function (fn) { utils.forEach(this.handlers, function (h) { if (h !== null) { fn(h); } }); }; module.exports = InterceptorManager; /***/ }, /* 13 */ /***/ function(module, exports) { 'use strict'; /** * Determines whether the specified URL is absolute * * @param {string} url The URL to test * @returns {boolean} True if the specified URL is absolute, otherwise false */ module.exports = function isAbsoluteURL(url) { // A URL is considered absolute if it begins with "<scheme>://" or "//" (protocol-relative URL). // RFC 3986 defines scheme name as a sequence of characters beginning with a letter and followed // by any combination of letters, digits, plus, period, or hyphen. return /^([a-z][a-z\d\+\-\.]*:)?\/\//i.test(url); }; /***/ }, /* 14 */ /***/ function(module, exports) { 'use strict'; /** * Creates a new URL by combining the specified URLs * * @param {string} baseURL The base URL * @param {string} relativeURL The relative URL * @returns {string} The combined URL */ module.exports = function combineURLs(baseURL, relativeURL) { return baseURL.replace(/\/+$/, '') + '/' + relativeURL.replace(/^\/+/, ''); }; /***/ }, /* 15 */ /***/ function(module, exports) { 'use strict'; /** * Syntactic sugar for invoking a function and expanding an array for arguments. * * Common use case would be to use `Function.prototype.apply`. * * ```js * function f(x, y, z) {} * var args = [1, 2, 3]; * f.apply(null, args); * ``` * * With `spread` this example can be re-written. * * ```js * spread(function(x, y, z) {})([1, 2, 3]); * ``` * * @param {Function} callback * @returns {Function} */ module.exports = function spread(callback) { return function (arr) { return callback.apply(null, arr); }; }; /***/ } /******/ ]) }); ; //# sourceMappingURL=axios.map
/* * SystemJS v0.11.3 */ (function($__global) { $__global.upgradeSystemLoader = function() { $__global.upgradeSystemLoader = undefined; // indexOf polyfill for IE var indexOf = Array.prototype.indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) if (this[i] === item) return i; return -1; } // Absolute URL parsing, from https://gist.github.com/Yaffle/1088850 function parseURI(url) { var m = String(url).replace(/^\s+|\s+$/g, '').match(/^([^:\/?#]+:)?(\/\/(?:[^:@\/?#]*(?::[^:@\/?#]*)?@)?(([^:\/?#]*)(?::(\d*))?))?([^?#]*)(\?[^#]*)?(#[\s\S]*)?/); // authority = '//' + user + ':' + pass '@' + hostname + ':' port return (m ? { href : m[0] || '', protocol : m[1] || '', authority: m[2] || '', host : m[3] || '', hostname : m[4] || '', port : m[5] || '', pathname : m[6] || '', search : m[7] || '', hash : m[8] || '' } : null); } function toAbsoluteURL(base, href) { function removeDotSegments(input) { var output = []; input.replace(/^(\.\.?(\/|$))+/, '') .replace(/\/(\.(\/|$))+/g, '/') .replace(/\/\.\.$/, '/../') .replace(/\/?[^\/]*/g, function (p) { if (p === '/..') output.pop(); else output.push(p); }); return output.join('').replace(/^\//, input.charAt(0) === '/' ? '/' : ''); } href = parseURI(href || ''); base = parseURI(base || ''); return !href || !base ? null : (href.protocol || base.protocol) + (href.protocol || href.authority ? href.authority : base.authority) + removeDotSegments(href.protocol || href.authority || href.pathname.charAt(0) === '/' ? href.pathname : (href.pathname ? ((base.authority && !base.pathname ? '/' : '') + base.pathname.slice(0, base.pathname.lastIndexOf('/') + 1) + href.pathname) : base.pathname)) + (href.protocol || href.authority || href.pathname ? href.search : (href.search || base.search)) + href.hash; } // clone the original System loader var System; (function() { var originalSystem = $__global.System; System = $__global.System = new LoaderPolyfill(originalSystem); System.baseURL = originalSystem.baseURL; System.paths = { '*': '*.js' }; System.originalSystem = originalSystem; })(); System.noConflict = function() { $__global.SystemJS = System; $__global.System = System.originalSystem; } /* * Meta Extension * * Sets default metadata on a load record (load.metadata) from * loader.meta[moduleName]. * Also provides an inline meta syntax for module meta in source. * * Eg: * * loader.meta['my/module'] = { some: 'meta' }; * * load.metadata.some = 'meta' will now be set on the load record. * * The same meta could be set with a my/module.js file containing: * * my/module.js * "some meta"; * "another meta"; * console.log('this is my/module'); * * The benefit of inline meta is that coniguration doesn't need * to be known in advance, which is useful for modularising * configuration and avoiding the need for configuration injection. * * * Example * ------- * * The simplest meta example is setting the module format: * * System.meta['my/module'] = { format: 'amd' }; * * or inside 'my/module.js': * * "format amd"; * define(...); * */ function meta(loader) { var metaRegEx = /^(\s*\/\*.*\*\/|\s*\/\/[^\n]*|\s*"[^"]+"\s*;?|\s*'[^']+'\s*;?)+/; var metaPartRegEx = /\/\*.*\*\/|\/\/[^\n]*|"[^"]+"\s*;?|'[^']+'\s*;?/g; loader.meta = {}; function setConfigMeta(loader, load) { var meta = loader.meta && loader.meta[load.name]; if (meta) { for (var p in meta) load.metadata[p] = load.metadata[p] || meta[p]; } } var loaderLocate = loader.locate; loader.locate = function(load) { setConfigMeta(this, load); return loaderLocate.call(this, load); } var loaderTranslate = loader.translate; loader.translate = function(load) { // detect any meta header syntax var meta = load.source.match(metaRegEx); if (meta) { var metaParts = meta[0].match(metaPartRegEx); for (var i = 0; i < metaParts.length; i++) { var len = metaParts[i].length; var firstChar = metaParts[i].substr(0, 1); if (metaParts[i].substr(len - 1, 1) == ';') len--; if (firstChar != '"' && firstChar != "'") continue; var metaString = metaParts[i].substr(1, metaParts[i].length - 3); var metaName = metaString.substr(0, metaString.indexOf(' ')); if (metaName) { var metaValue = metaString.substr(metaName.length + 1, metaString.length - metaName.length - 1); if (load.metadata[metaName] instanceof Array) load.metadata[metaName].push(metaValue); else if (!load.metadata[metaName]) load.metadata[metaName] = metaValue; } } } // config meta overrides setConfigMeta(this, load); return loaderTranslate.call(this, load); } } /* * Instantiate registry extension * * Supports Traceur System.register 'instantiate' output for loading ES6 as ES5. * * - Creates the loader.register function * - Also supports metadata.format = 'register' in instantiate for anonymous register modules * - Also supports metadata.deps, metadata.execute and metadata.executingRequire * for handling dynamic modules alongside register-transformed ES6 modules * * Works as a standalone extension, but benefits from having a more * advanced __eval defined like in SystemJS polyfill-wrapper-end.js * * The code here replicates the ES6 linking groups algorithm to ensure that * circular ES6 compiled into System.register can work alongside circular AMD * and CommonJS, identically to the actual ES6 loader. * */ function register(loader) { if (typeof indexOf == 'undefined') indexOf = Array.prototype.indexOf; if (typeof __eval == 'undefined') __eval = 0 || eval; // uglify breaks without the 0 || // define exec for easy evaluation of a load record (load.name, load.source, load.address) // main feature is source maps support handling var curSystem; function exec(load) { var loader = this; if (load.name == '@traceur') { curSystem = System; } // support sourceMappingURL (efficiently) var sourceMappingURL; var lastLineIndex = load.source.lastIndexOf('\n'); if (lastLineIndex != -1) { if (load.source.substr(lastLineIndex + 1, 21) == '//# sourceMappingURL=') { sourceMappingURL = load.source.substr(lastLineIndex + 22, load.source.length - lastLineIndex - 22); if (typeof toAbsoluteURL != 'undefined') sourceMappingURL = toAbsoluteURL(load.address, sourceMappingURL); } } __eval(load.source, load.address, sourceMappingURL); // traceur overwrites System and Module - write them back if (load.name == '@traceur') { loader.global.traceurSystem = loader.global.System; loader.global.System = curSystem; } } loader.__exec = exec; function dedupe(deps) { var newDeps = []; for (var i = 0, l = deps.length; i < l; i++) if (indexOf.call(newDeps, deps[i]) == -1) newDeps.push(deps[i]) return newDeps; } /* * There are two variations of System.register: * 1. System.register for ES6 conversion (2-3 params) - System.register([name, ]deps, declare) * see https://github.com/ModuleLoader/es6-module-loader/wiki/System.register-Explained * * 2. System.register for dynamic modules (3-4 params) - System.register([name, ]deps, executingRequire, execute) * the true or false statement * * this extension implements the linking algorithm for the two variations identical to the spec * allowing compiled ES6 circular references to work alongside AMD and CJS circular references. * */ // loader.register sets loader.defined for declarative modules var anonRegister; var calledRegister; function register(name, deps, declare, execute) { if (typeof name != 'string') { execute = declare; declare = deps; deps = name; name = null; } calledRegister = true; var register; // dynamic if (typeof declare == 'boolean') { register = { declarative: false, deps: deps, execute: execute, executingRequire: declare }; } else { // ES6 declarative register = { declarative: true, deps: deps, declare: declare }; } // named register if (name) { register.name = name; // we never overwrite an existing define if (!loader.defined[name]) loader.defined[name] = register; } // anonymous register else if (register.declarative) { if (anonRegister) throw new TypeError('Multiple anonymous System.register calls in the same module file.'); anonRegister = register; } } /* * Registry side table - loader.defined * Registry Entry Contains: * - name * - deps * - declare for declarative modules * - execute for dynamic modules, different to declarative execute on module * - executingRequire indicates require drives execution for circularity of dynamic modules * - declarative optional boolean indicating which of the above * * Can preload modules directly on System.defined['my/module'] = { deps, execute, executingRequire } * * Then the entry gets populated with derived information during processing: * - normalizedDeps derived from deps, created in instantiate * - groupIndex used by group linking algorithm * - evaluated indicating whether evaluation has happend * - module the module record object, containing: * - exports actual module exports * * Then for declarative only we track dynamic bindings with the records: * - name * - setters declarative setter functions * - exports actual module values * - dependencies, module records of dependencies * - importers, module records of dependents * * After linked and evaluated, entries are removed, declarative module records remain in separate * module binding table * */ function defineRegister(loader) { if (loader.register) return; loader.register = register; if (!loader.defined) loader.defined = {}; // script injection mode calls this function synchronously on load var onScriptLoad = loader.onScriptLoad; loader.onScriptLoad = function(load) { onScriptLoad(load); // anonymous define if (anonRegister) load.metadata.entry = anonRegister; if (calledRegister) { load.metadata.format = load.metadata.format || 'register'; load.metadata.registered = true; } } } defineRegister(loader); function buildGroups(entry, loader, groups) { groups[entry.groupIndex] = groups[entry.groupIndex] || []; if (indexOf.call(groups[entry.groupIndex], entry) != -1) return; groups[entry.groupIndex].push(entry); for (var i = 0, l = entry.normalizedDeps.length; i < l; i++) { var depName = entry.normalizedDeps[i]; var depEntry = loader.defined[depName]; // not in the registry means already linked / ES6 if (!depEntry || depEntry.evaluated) continue; // now we know the entry is in our unlinked linkage group var depGroupIndex = entry.groupIndex + (depEntry.declarative != entry.declarative); // the group index of an entry is always the maximum if (depEntry.groupIndex === undefined || depEntry.groupIndex < depGroupIndex) { // if already in a group, remove from the old group if (depEntry.groupIndex) { groups[depEntry.groupIndex].splice(indexOf.call(groups[depEntry.groupIndex], depEntry), 1); // if the old group is empty, then we have a mixed depndency cycle if (groups[depEntry.groupIndex].length == 0) throw new TypeError("Mixed dependency cycle detected"); } depEntry.groupIndex = depGroupIndex; } buildGroups(depEntry, loader, groups); } } function link(name, loader) { var startEntry = loader.defined[name]; startEntry.groupIndex = 0; var groups = []; buildGroups(startEntry, loader, groups); var curGroupDeclarative = !!startEntry.declarative == groups.length % 2; for (var i = groups.length - 1; i >= 0; i--) { var group = groups[i]; for (var j = 0; j < group.length; j++) { var entry = group[j]; // link each group if (curGroupDeclarative) linkDeclarativeModule(entry, loader); else linkDynamicModule(entry, loader); } curGroupDeclarative = !curGroupDeclarative; } } // module binding records var moduleRecords = {}; function getOrCreateModuleRecord(name) { return moduleRecords[name] || (moduleRecords[name] = { name: name, dependencies: [], exports: {}, // start from an empty module and extend importers: [] }) } function linkDeclarativeModule(entry, loader) { // only link if already not already started linking (stops at circular) if (entry.module) return; var module = entry.module = getOrCreateModuleRecord(entry.name); var exports = entry.module.exports; var declaration = entry.declare.call(loader.global, function(name, value) { module.locked = true; exports[name] = value; for (var i = 0, l = module.importers.length; i < l; i++) { var importerModule = module.importers[i]; if (!importerModule.locked) { var importerIndex = indexOf.call(importerModule.dependencies, module); importerModule.setters[importerIndex](exports); } } module.locked = false; return value; }); module.setters = declaration.setters; module.execute = declaration.execute; if (!module.setters || !module.execute) { throw new TypeError('Invalid System.register form for ' + entry.name); } // now link all the module dependencies for (var i = 0, l = entry.normalizedDeps.length; i < l; i++) { var depName = entry.normalizedDeps[i]; var depEntry = loader.defined[depName]; var depModule = moduleRecords[depName]; // work out how to set depExports based on scenarios... var depExports; if (depModule) { depExports = depModule.exports; } // dynamic, already linked in our registry else if (depEntry && !depEntry.declarative) { depExports = { 'default': depEntry.module.exports, '__useDefault': true }; } // in the loader registry else if (!depEntry) { depExports = loader.get(depName); } // we have an entry -> link else { linkDeclarativeModule(depEntry, loader); depModule = depEntry.module; depExports = depModule.exports; } // only declarative modules have dynamic bindings if (depModule && depModule.importers) { depModule.importers.push(module); module.dependencies.push(depModule); } else { module.dependencies.push(null); } // run the setter for this dependency if (module.setters[i]) module.setters[i](depExports); } } // An analog to loader.get covering execution of all three layers (real declarative, simulated declarative, simulated dynamic) function getModule(name, loader) { var exports; var entry = loader.defined[name]; if (!entry) { exports = loader.get(name); if (!exports) throw new Error('Unable to load dependency ' + name + '.'); } else { if (entry.declarative) ensureEvaluated(name, [], loader); else if (!entry.evaluated) linkDynamicModule(entry, loader); exports = entry.module.exports; } if ((!entry || entry.declarative) && exports && exports.__useDefault) return exports['default']; return exports; } function linkDynamicModule(entry, loader) { if (entry.module) return; var exports = {}; var module = entry.module = { exports: exports, id: entry.name }; // AMD requires execute the tree first if (!entry.executingRequire) { for (var i = 0, l = entry.normalizedDeps.length; i < l; i++) { var depName = entry.normalizedDeps[i]; var depEntry = loader.defined[depName]; if (depEntry) linkDynamicModule(depEntry, loader); } } // now execute entry.evaluated = true; var output = entry.execute.call(loader.global, function(name) { for (var i = 0, l = entry.deps.length; i < l; i++) { if (entry.deps[i] != name) continue; return getModule(entry.normalizedDeps[i], loader); } throw new TypeError('Module ' + name + ' not declared as a dependency.'); }, exports, module); if (output) module.exports = output; } /* * Given a module, and the list of modules for this current branch, * ensure that each of the dependencies of this module is evaluated * (unless one is a circular dependency already in the list of seen * modules, in which case we execute it) * * Then we evaluate the module itself depth-first left to right * execution to match ES6 modules */ function ensureEvaluated(moduleName, seen, loader) { var entry = loader.defined[moduleName]; // if already seen, that means it's an already-evaluated non circular dependency if (entry.evaluated || !entry.declarative) return; // this only applies to declarative modules which late-execute seen.push(moduleName); for (var i = 0, l = entry.normalizedDeps.length; i < l; i++) { var depName = entry.normalizedDeps[i]; if (indexOf.call(seen, depName) == -1) { if (!loader.defined[depName]) loader.get(depName); else ensureEvaluated(depName, seen, loader); } } if (entry.evaluated) return; entry.evaluated = true; entry.module.execute.call(loader.global); } var registerRegEx = /System\.register/; var loaderFetch = loader.fetch; loader.fetch = function(load) { var loader = this; defineRegister(loader); if (loader.defined[load.name]) { load.metadata.format = 'defined'; return ''; } anonRegister = null; calledRegister = false; // the above get picked up by onScriptLoad return loaderFetch.call(loader, load); } var loaderTranslate = loader.translate; loader.translate = function(load) { this.register = register; this.__exec = exec; load.metadata.deps = load.metadata.deps || []; // we run the meta detection here (register is after meta) return Promise.resolve(loaderTranslate.call(this, load)).then(function(source) { // dont run format detection for globals shimmed // ideally this should be in the global extension, but there is // currently no neat way to separate it if (load.metadata.init || load.metadata.exports) load.metadata.format = load.metadata.format || 'global'; // run detection for register format if (load.metadata.format == 'register' || !load.metadata.format && load.source.match(registerRegEx)) load.metadata.format = 'register'; return source; }); } var loaderInstantiate = loader.instantiate; loader.instantiate = function(load) { var loader = this; var entry; // first we check if this module has already been defined in the registry if (loader.defined[load.name]) { entry = loader.defined[load.name]; entry.deps = entry.deps.concat(load.metadata.deps); } // picked up already by a script injection else if (load.metadata.entry) entry = load.metadata.entry; // otherwise check if it is dynamic else if (load.metadata.execute) { entry = { declarative: false, deps: load.metadata.deps || [], execute: load.metadata.execute, executingRequire: load.metadata.executingRequire // NodeJS-style requires or not }; } // Contains System.register calls else if (load.metadata.format == 'register') { anonRegister = null; calledRegister = false; var System = loader.global.System = loader.global.System || loader; var curRegister = System.register; System.register = register; loader.__exec(load); System.register = curRegister; if (anonRegister) entry = anonRegister; if (!entry && System.defined[load.name]) entry = System.defined[load.name]; if (!calledRegister && !load.metadata.registered) throw new TypeError(load.name + ' detected as System.register but didn\'t execute.'); } // named bundles are just an empty module if (!entry && load.metadata.format != 'es6') return { deps: [], execute: function() { return loader.newModule({}); } }; // place this module onto defined for circular references if (entry) loader.defined[load.name] = entry; // no entry -> treat as ES6 else return loaderInstantiate.call(this, load); entry.deps = dedupe(entry.deps); entry.name = load.name; // first, normalize all dependencies var normalizePromises = []; for (var i = 0, l = entry.deps.length; i < l; i++) normalizePromises.push(Promise.resolve(loader.normalize(entry.deps[i], load.name))); return Promise.all(normalizePromises).then(function(normalizedDeps) { entry.normalizedDeps = normalizedDeps; return { deps: entry.deps, execute: function() { // recursively ensure that the module and all its // dependencies are linked (with dependency group handling) link(load.name, loader); // now handle dependency execution in correct order ensureEvaluated(load.name, [], loader); // remove from the registry loader.defined[load.name] = undefined; var module = loader.newModule(entry.declarative ? entry.module.exports : { 'default': entry.module.exports, '__useDefault': true }); // return the defined module object return module; } }; }); } } /* * SystemJS Core * Code should be vaguely readable * */ function core(loader) { /* __useDefault When a module object looks like: newModule({ __useDefault: true, default: 'some-module' }) Then importing that module provides the 'some-module' result directly instead of the full module. Useful for eg module.exports = function() {} */ var loaderImport = loader['import']; loader['import'] = function(name, options) { return loaderImport.call(this, name, options).then(function(module) { return module.__useDefault ? module['default'] : module; }); } // support the empty module, as a concept loader.set('@empty', loader.newModule({})); // include the node require since we're overriding it if (typeof require != 'undefined') loader._nodeRequire = require; /* Config Extends config merging one deep only loader.config({ some: 'random', config: 'here', deep: { config: { too: 'too' } } }); <=> loader.some = 'random'; loader.config = 'here' loader.deep = loader.deep || {}; loader.deep.config = { too: 'too' }; */ loader.config = function(cfg) { for (var c in cfg) { var v = cfg[c]; if (typeof v == 'object' && !(v instanceof Array)) { this[c] = this[c] || {}; for (var p in v) this[c][p] = v[p]; } else this[c] = v; } } // override locate to allow baseURL to be document-relative var baseURI; if (typeof window == 'undefined' && typeof WorkerGlobalScope == 'undefined') { baseURI = 'file:' + process.cwd() + '/'; } // Inside of a Web Worker else if(typeof window == 'undefined') { baseURI = loader.global.location.href; } else { baseURI = document.baseURI; if (!baseURI) { var bases = document.getElementsByTagName('base'); baseURI = bases[0] && bases[0].href || window.location.href; } } var loaderLocate = loader.locate; var normalizedBaseURL; loader.locate = function(load) { if (this.baseURL != normalizedBaseURL) { normalizedBaseURL = toAbsoluteURL(baseURI, this.baseURL); if (normalizedBaseURL.substr(normalizedBaseURL.length - 1, 1) != '/') normalizedBaseURL += '/'; this.baseURL = normalizedBaseURL; } return Promise.resolve(loaderLocate.call(this, load)); } // Traceur conveniences // good enough ES6 detection regex - format detections not designed to be accurate, but to handle the 99% use case var es6RegEx = /(^\s*|[}\);\n]\s*)(import\s+(['"]|(\*\s+as\s+)?[^"'\(\)\n;]+\s+from\s+['"]|\{)|export\s+\*\s+from\s+["']|export\s+(\{|default|function|class|var|const|let|async\s+function))/; var traceurRuntimeRegEx = /\$traceurRuntime/; var loaderTranslate = loader.translate; loader.translate = function(load) { var loader = this; if (load.name == '@traceur' || load.name == '@traceur-runtime') return loaderTranslate.call(loader, load); // detect ES6 else if (load.metadata.format == 'es6' || !load.metadata.format && load.source.match(es6RegEx)) { load.metadata.format = 'es6'; // dynamically load Traceur for ES6 if necessary if (!loader.global.traceur) { return loader['import']('@traceur').then(function() { return loaderTranslate.call(loader, load); }); } } // dynamicallly load Traceur runtime if necessary if (!loader.global.$traceurRuntime && load.source.match(traceurRuntimeRegEx)) { var System = $__global.System; return loader['import']('@traceur-runtime').then(function() { // traceur runtme annihilates System global $__global.System = System; return loaderTranslate.call(loader, load); }); } return loaderTranslate.call(loader, load); } // always load Traceur as a global var loaderInstantiate = loader.instantiate; loader.instantiate = function(load) { var loader = this; if (load.name == '@traceur' || load.name == '@traceur-runtime') { loader.__exec(load); return { deps: [], execute: function() { return loader.newModule({}); } }; } return loaderInstantiate.call(loader, load); } } /* SystemJS Global Format Supports metadata.deps metadata.init metadata.exports Also detects writes to the global object avoiding global collisions. See the SystemJS readme global support section for further information. */ function global(loader) { function readGlobalProperty(p, value) { var pParts = p.split('.'); while (pParts.length) value = value[pParts.shift()]; return value; } function createHelpers(loader) { if (loader.has('@@global-helpers')) return; var hasOwnProperty = loader.global.hasOwnProperty; var moduleGlobals = {}; var curGlobalObj; var ignoredGlobalProps; loader.set('@@global-helpers', loader.newModule({ prepareGlobal: function(moduleName, deps) { // first, we add all the dependency modules to the global for (var i = 0; i < deps.length; i++) { var moduleGlobal = moduleGlobals[deps[i]]; if (moduleGlobal) for (var m in moduleGlobal) loader.global[m] = moduleGlobal[m]; } // now store a complete copy of the global object // in order to detect changes curGlobalObj = {}; ignoredGlobalProps = ['indexedDB', 'sessionStorage', 'localStorage', 'clipboardData', 'frames', 'webkitStorageInfo', 'toolbar', 'statusbar', 'scrollbars', 'personalbar', 'menubar', 'locationbar', 'webkitIndexedDB' ]; for (var g in loader.global) { if (indexOf.call(ignoredGlobalProps, g) != -1) { continue; } if (!hasOwnProperty || loader.global.hasOwnProperty(g)) { try { curGlobalObj[g] = loader.global[g]; } catch (e) { ignoredGlobalProps.push(g); } } } }, retrieveGlobal: function(moduleName, exportName, init) { var singleGlobal; var multipleExports; var exports = {}; // run init if (init) { var depModules = []; for (var i = 0; i < deps.length; i++) depModules.push(require(deps[i])); singleGlobal = init.apply(loader.global, depModules); } // check for global changes, creating the globalObject for the module // if many globals, then a module object for those is created // if one global, then that is the module directly else if (exportName) { var firstPart = exportName.split('.')[0]; singleGlobal = readGlobalProperty(exportName, loader.global); exports[firstPart] = loader.global[firstPart]; } else { for (var g in loader.global) { if (indexOf.call(ignoredGlobalProps, g) != -1) continue; if ((!hasOwnProperty || loader.global.hasOwnProperty(g)) && g != loader.global && curGlobalObj[g] != loader.global[g]) { exports[g] = loader.global[g]; if (singleGlobal) { if (singleGlobal !== loader.global[g]) multipleExports = true; } else if (singleGlobal !== false) { singleGlobal = loader.global[g]; } } } } moduleGlobals[moduleName] = exports; return multipleExports ? exports : singleGlobal; } })); } createHelpers(loader); var loaderInstantiate = loader.instantiate; loader.instantiate = function(load) { var loader = this; createHelpers(loader); var exportName = load.metadata.exports; if (!load.metadata.format) load.metadata.format = 'global'; // global is a fallback module format if (load.metadata.format == 'global') { load.metadata.execute = function(require, exports, module) { loader.get('@@global-helpers').prepareGlobal(module.id, load.metadata.deps); if (exportName) load.source += '\nthis["' + exportName + '"] = ' + exportName + ';'; // disable AMD detection var define = loader.global.define; loader.global.define = undefined; // ensure no NodeJS environment detection loader.global.module = undefined; loader.global.exports = undefined; loader.__exec(load); loader.global.define = define; return loader.get('@@global-helpers').retrieveGlobal(module.id, exportName, load.metadata.init); } } return loaderInstantiate.call(loader, load); } } /* SystemJS CommonJS Format */ function cjs(loader) { // CJS Module Format // require('...') || exports[''] = ... || exports.asd = ... || module.exports = ... var cjsExportsRegEx = /(?:^\uFEFF?|[^$_a-zA-Z\xA0-\uFFFF.]|module\.)(exports\s*\[['"]|\exports\s*\.)|(?:^\uFEFF?|[^$_a-zA-Z\xA0-\uFFFF.])module\.exports\s*\=/; // RegEx adjusted from https://github.com/jbrantly/yabble/blob/master/lib/yabble.js#L339 var cjsRequireRegEx = /(?:^\uFEFF?|[^$_a-zA-Z\xA0-\uFFFF."'])require\s*\(\s*("[^"\\]*(?:\\.[^"\\]*)*"|'[^'\\]*(?:\\.[^'\\]*)*')\s*\)/g; var commentRegEx = /(\/\*([\s\S]*?)\*\/|([^:]|^)\/\/(.*)$)/mg; function getCJSDeps(source) { cjsRequireRegEx.lastIndex = 0; var deps = []; // remove comments from the source first, if not minified if (source.length / source.split('\n').length < 200) source = source.replace(commentRegEx, ''); var match; while (match = cjsRequireRegEx.exec(source)) deps.push(match[1].substr(1, match[1].length - 2)); return deps; } var loaderInstantiate = loader.instantiate; loader.instantiate = function(load) { if (!load.metadata.format) { cjsExportsRegEx.lastIndex = 0; cjsRequireRegEx.lastIndex = 0; if (cjsRequireRegEx.exec(load.source) || cjsExportsRegEx.exec(load.source)) load.metadata.format = 'cjs'; } if (load.metadata.format == 'cjs') { load.metadata.deps = load.metadata.deps ? load.metadata.deps.concat(getCJSDeps(load.source)) : load.metadata.deps; load.metadata.executingRequire = true; load.metadata.execute = function(require, exports, module) { var dirname = (load.address || '').split('/'); dirname.pop(); dirname = dirname.join('/'); // if on the server, remove the "file:" part from the dirname if (System._nodeRequire) dirname = dirname.substr(5); var globals = loader.global._g = { global: loader.global, exports: exports, module: module, require: require, __filename: System._nodeRequire ? load.address.substr(5) : load.address, __dirname: dirname }; var source = '(function(global, exports, module, require, __filename, __dirname) { ' + load.source + '\n}).call(_g.exports, _g.global, _g.exports, _g.module, _g.require, _g.__filename, _g.__dirname);'; // disable AMD detection var define = loader.global.define; loader.global.define = undefined; loader.__exec({ name: load.name, address: load.address, source: source }); loader.global.define = define; loader.global._g = undefined; } } return loaderInstantiate.call(this, load); }; } /* SystemJS AMD Format Provides the AMD module format definition at System.format.amd as well as a RequireJS-style require on System.require */ function amd(loader) { // by default we only enforce AMD noConflict mode in Node var isNode = typeof module != 'undefined' && module.exports; // AMD Module Format Detection RegEx // define([.., .., ..], ...) // define(varName); || define(function(require, exports) {}); || define({}) var amdRegEx = /(?:^\uFEFF?|[^$_a-zA-Z\xA0-\uFFFF.])define\s*\(\s*("[^"]+"\s*,\s*|'[^']+'\s*,\s*)?\s*(\[(\s*(("[^"]+"|'[^']+')\s*,|\/\/.*\r?\n|\/\*(.|\s)*?\*\/))*(\s*("[^"]+"|'[^']+')\s*,?)?(\s*(\/\/.*\r?\n|\/\*(.|\s)*?\*\/))*\s*\]|function\s*|{|[_$a-zA-Z\xA0-\uFFFF][_$a-zA-Z0-9\xA0-\uFFFF]*\))/; var commentRegEx = /(\/\*([\s\S]*?)\*\/|([^:]|^)\/\/(.*)$)/mg; var cjsRequirePre = "(?:^|[^$_a-zA-Z\\xA0-\\uFFFF.])"; var cjsRequirePost = "\\s*\\(\\s*(\"([^\"]+)\"|'([^']+)')\\s*\\)"; var fnBracketRegEx = /\(([^\)]*)\)/; var wsRegEx = /^\s+|\s+$/g; var requireRegExs = {}; function getCJSDeps(source, requireIndex) { // remove comments source = source.replace(commentRegEx, ''); // determine the require alias var params = source.match(fnBracketRegEx); var requireAlias = (params[1].split(',')[requireIndex] || 'require').replace(wsRegEx, ''); // find or generate the regex for this requireAlias var requireRegEx = requireRegExs[requireAlias] || (requireRegExs[requireAlias] = new RegExp(cjsRequirePre + requireAlias + cjsRequirePost, 'g')); requireRegEx.lastIndex = 0; var deps = []; var match; while (match = requireRegEx.exec(source)) deps.push(match[2] || match[3]); return deps; } /* AMD-compatible require To copy RequireJS, set window.require = window.requirejs = loader.amdRequire */ function require(names, callback, errback, referer) { // 'this' is bound to the loader var loader = this; // in amd, first arg can be a config object... we just ignore if (typeof names == 'object' && !(names instanceof Array)) return require.apply(null, Array.prototype.splice.call(arguments, 1, arguments.length - 1)); // amd require if (names instanceof Array) Promise.all(names.map(function(name) { return loader['import'](name, referer); })).then(function(modules) { if(callback) { callback.apply(null, modules); } }, errback); // commonjs require else if (typeof names == 'string') { var module = loader.get(names); return module.__useDefault ? module['default'] : module; } else throw new TypeError('Invalid require'); }; loader.amdRequire = require; function makeRequire(parentName, staticRequire, loader) { return function(names, callback, errback) { if (typeof names == 'string') return staticRequire(names); return require.call(loader, names, callback, errback, { name: parentName }); } } // run once per loader function generateDefine(loader) { // script injection mode calls this function synchronously on load var onScriptLoad = loader.onScriptLoad; loader.onScriptLoad = function(load) { onScriptLoad(load); if (anonDefine || defineBundle) { load.metadata.format = 'defined'; load.metadata.registered = true; } if (anonDefine) { load.metadata.deps = load.metadata.deps ? load.metadata.deps.concat(anonDefine.deps) : anonDefine.deps; load.metadata.execute = anonDefine.execute; } } function define(name, deps, factory) { if (typeof name != 'string') { factory = deps; deps = name; name = null; } if (!(deps instanceof Array)) { factory = deps; deps = ['require', 'exports', 'module']; } if (typeof factory != 'function') factory = (function(factory) { return function() { return factory; } })(factory); // in IE8, a trailing comma becomes a trailing undefined entry if (deps[deps.length - 1] === undefined) deps.pop(); // remove system dependencies var requireIndex, exportsIndex, moduleIndex; if ((requireIndex = indexOf.call(deps, 'require')) != -1) { deps.splice(requireIndex, 1); var factoryText = factory.toString(); deps = deps.concat(getCJSDeps(factoryText, requireIndex)); } if ((exportsIndex = indexOf.call(deps, 'exports')) != -1) deps.splice(exportsIndex, 1); if ((moduleIndex = indexOf.call(deps, 'module')) != -1) deps.splice(moduleIndex, 1); var define = { deps: deps, execute: function(require, exports, module) { var depValues = []; for (var i = 0; i < deps.length; i++) depValues.push(require(deps[i])); module.uri = loader.baseURL + module.id; module.config = function() {}; // add back in system dependencies if (moduleIndex != -1) depValues.splice(moduleIndex, 0, module); if (exportsIndex != -1) depValues.splice(exportsIndex, 0, exports); if (requireIndex != -1) depValues.splice(requireIndex, 0, makeRequire(module.id, require, loader)); var output = factory.apply(global, depValues); if (typeof output == 'undefined' && module) output = module.exports; if (typeof output != 'undefined') return output; } }; // anonymous define if (!name) { // already defined anonymously -> throw if (anonDefine) throw new TypeError('Multiple defines for anonymous module'); anonDefine = define; } // named define else { // if it has no dependencies and we don't have any other // defines, then let this be an anonymous define if (deps.length == 0 && !anonDefine && !defineBundle) anonDefine = define; // otherwise its a bundle only else anonDefine = null; // the above is just to support single modules of the form: // define('jquery') // still loading anonymously // because it is done widely enough to be useful // note this is now a bundle defineBundle = true; // define the module through the register registry loader.register(name, define.deps, false, define.execute); } }; define.amd = {}; loader.amdDefine = define; } var anonDefine; // set to true if the current module turns out to be a named define bundle var defineBundle; var oldModule, oldExports, oldDefine; // adds define as a global (potentially just temporarily) function createDefine(loader) { if (!loader.amdDefine) generateDefine(loader); anonDefine = null; defineBundle = null; // ensure no NodeJS environment detection var global = loader.global; oldModule = global.module; oldExports = global.exports; oldDefine = global.define; global.module = undefined; global.exports = undefined; if (global.define && global.define === loader.amdDefine) return; global.define = loader.amdDefine; } function removeDefine(loader) { var global = loader.global; global.define = oldDefine; global.module = oldModule; global.exports = oldExports; } generateDefine(loader); if (loader.scriptLoader) { var loaderFetch = loader.fetch; loader.fetch = function(load) { createDefine(this); return loaderFetch.call(this, load); } } var loaderInstantiate = loader.instantiate; loader.instantiate = function(load) { var loader = this; if (load.metadata.format == 'amd' || !load.metadata.format && load.source.match(amdRegEx)) { load.metadata.format = 'amd'; if (loader.execute !== false) { createDefine(loader); loader.__exec(load); removeDefine(loader); if (!anonDefine && !defineBundle && !isNode) throw new TypeError('AMD module ' + load.name + ' did not define'); } if (anonDefine) { load.metadata.deps = load.metadata.deps ? load.metadata.deps.concat(anonDefine.deps) : anonDefine.deps; load.metadata.execute = anonDefine.execute; } } return loaderInstantiate.call(loader, load); } } /* SystemJS map support Provides map configuration through System.map['jquery'] = 'some/module/map' As well as contextual map config through System.map['bootstrap'] = { jquery: 'some/module/map2' } Note that this applies for subpaths, just like RequireJS jquery -> 'some/module/map' jquery/path -> 'some/module/map/path' bootstrap -> 'bootstrap' Inside any module name of the form 'bootstrap' or 'bootstrap/*' jquery -> 'some/module/map2' jquery/p -> 'some/module/map2/p' Maps are carefully applied from most specific contextual map, to least specific global map */ function map(loader) { loader.map = loader.map || {}; // return if prefix parts (separated by '/') match the name // eg prefixMatch('jquery/some/thing', 'jquery') -> true // prefixMatch('jqueryhere/', 'jquery') -> false function prefixMatch(name, prefix) { if (name.length < prefix.length) return false; if (name.substr(0, prefix.length) != prefix) return false; if (name[prefix.length] && name[prefix.length] != '/') return false; return true; } // get the depth of a given path // eg pathLen('some/name') -> 2 function pathLen(name) { var len = 1; for (var i = 0, l = name.length; i < l; i++) if (name[i] === '/') len++; return len; } function doMap(name, matchLen, map) { return map + name.substr(matchLen); } // given a relative-resolved module name and normalized parent name, // apply the map configuration function applyMap(name, parentName, loader) { var curMatch, curMatchLength = 0; var curParent, curParentMatchLength = 0; var tmpParentLength, tmpPrefixLength; var subPath; var nameParts; // first find most specific contextual match if (parentName) { for (var p in loader.map) { var curMap = loader.map[p]; if (typeof curMap != 'object') continue; // most specific parent match wins first if (!prefixMatch(parentName, p)) continue; tmpParentLength = pathLen(p); if (tmpParentLength <= curParentMatchLength) continue; for (var q in curMap) { // most specific name match wins if (!prefixMatch(name, q)) continue; tmpPrefixLength = pathLen(q); if (tmpPrefixLength <= curMatchLength) continue; curMatch = q; curMatchLength = tmpPrefixLength; curParent = p; curParentMatchLength = tmpParentLength; } } } // if we found a contextual match, apply it now if (curMatch) return doMap(name, curMatch.length, loader.map[curParent][curMatch]); // now do the global map for (var p in loader.map) { var curMap = loader.map[p]; if (typeof curMap != 'string') continue; if (!prefixMatch(name, p)) continue; var tmpPrefixLength = pathLen(p); if (tmpPrefixLength <= curMatchLength) continue; curMatch = p; curMatchLength = tmpPrefixLength; } if (curMatch) return doMap(name, curMatch.length, loader.map[curMatch]); return name; } var loaderNormalize = loader.normalize; loader.normalize = function(name, parentName, parentAddress) { var loader = this; if (!loader.map) loader.map = {}; var isPackage = false; if (name.substr(name.length - 1, 1) == '/') { isPackage = true; name += '#'; } return Promise.resolve(loaderNormalize.call(loader, name, parentName, parentAddress)) .then(function(name) { name = applyMap(name, parentName, loader); // Normalize "module/" into "module/module" // Convenient for packages if (isPackage) { var nameParts = name.split('/'); nameParts.pop(); var pkgName = nameParts.pop(); nameParts.push(pkgName); nameParts.push(pkgName); name = nameParts.join('/'); } return name; }); } } /* SystemJS Plugin Support Supports plugin syntax with "!" The plugin name is loaded as a module itself, and can override standard loader hooks for the plugin resource. See the plugin section of the systemjs readme. */ function plugins(loader) { if (typeof indexOf == 'undefined') indexOf = Array.prototype.indexOf; var loaderNormalize = loader.normalize; loader.normalize = function(name, parentName, parentAddress) { var loader = this; // if parent is a plugin, normalize against the parent plugin argument only var parentPluginIndex; if (parentName && (parentPluginIndex = parentName.indexOf('!')) != -1) parentName = parentName.substr(0, parentPluginIndex); return Promise.resolve(loaderNormalize.call(loader, name, parentName, parentAddress)) .then(function(name) { // if this is a plugin, normalize the plugin name and the argument var pluginIndex = name.lastIndexOf('!'); if (pluginIndex != -1) { var argumentName = name.substr(0, pluginIndex); // plugin name is part after "!" or the extension itself var pluginName = name.substr(pluginIndex + 1) || argumentName.substr(argumentName.lastIndexOf('.') + 1); // normalize the plugin name relative to the same parent return new Promise(function(resolve) { resolve(loader.normalize(pluginName, parentName, parentAddress)); }) // normalize the plugin argument .then(function(_pluginName) { pluginName = _pluginName; return loader.normalize(argumentName, parentName, parentAddress); }) .then(function(argumentName) { return argumentName + '!' + pluginName; }); } // standard normalization return name; }); } var loaderLocate = loader.locate; loader.locate = function(load) { var loader = this; var name = load.name; // only fetch the plugin itself if this name isn't defined if (this.defined && this.defined[name]) return loaderLocate.call(this, load); // plugin var pluginIndex = name.lastIndexOf('!'); if (pluginIndex != -1) { var pluginName = name.substr(pluginIndex + 1); // the name to locate is the plugin argument only load.name = name.substr(0, pluginIndex); var pluginLoader = loader.pluginLoader || loader; // load the plugin module // NB ideally should use pluginLoader.load for normalized, // but not currently working for some reason return pluginLoader['import'](pluginName) .then(function() { var plugin = pluginLoader.get(pluginName); plugin = plugin['default'] || plugin; // allow plugins to opt-out of build if (plugin.build === false && loader.pluginLoader) load.metadata.build = false; // store the plugin module itself on the metadata load.metadata.plugin = plugin; load.metadata.pluginName = pluginName; load.metadata.pluginArgument = load.name; // run plugin locate if given if (plugin.locate) return plugin.locate.call(loader, load); // otherwise use standard locate without '.js' extension adding else return Promise.resolve(loader.locate(load)) .then(function(address) { return address.substr(0, address.length - 3); }); }); } return loaderLocate.call(this, load); } var loaderFetch = loader.fetch; loader.fetch = function(load) { var loader = this; if (load.metadata.build === false) return ''; else if (load.metadata.plugin && load.metadata.plugin.fetch && !load.metadata.pluginFetchCalled) { load.metadata.pluginFetchCalled = true; return load.metadata.plugin.fetch.call(loader, load, loaderFetch); } else return loaderFetch.call(loader, load); } var loaderTranslate = loader.translate; loader.translate = function(load) { var loader = this; if (load.metadata.plugin && load.metadata.plugin.translate) return Promise.resolve(load.metadata.plugin.translate.call(loader, load)).then(function(result) { if (result) load.source = result; return loaderTranslate.call(loader, load); }); else return loaderTranslate.call(loader, load); } var loaderInstantiate = loader.instantiate; loader.instantiate = function(load) { var loader = this; if (load.metadata.plugin && load.metadata.plugin.instantiate) return Promise.resolve(load.metadata.plugin.instantiate.call(loader, load)).then(function(result) { load.metadata.format = 'defined'; load.metadata.execute = function() { return result; }; return loaderInstantiate.call(loader, load); }); else if (load.metadata.plugin && load.metadata.plugin.build === false) { load.metadata.format = 'defined'; load.metadata.deps.push(load.metadata.pluginName); load.metadata.execute = function() { return loader.newModule({}); }; return loaderInstantiate.call(loader, load); } else return loaderInstantiate.call(loader, load); } }/* System bundles Allows a bundle module to be specified which will be dynamically loaded before trying to load a given module. For example: System.bundles['mybundle'] = ['jquery', 'bootstrap/js/bootstrap'] Will result in a load to "mybundle" whenever a load to "jquery" or "bootstrap/js/bootstrap" is made. In this way, the bundle becomes the request that provides the module */ function bundles(loader) { if (typeof indexOf == 'undefined') indexOf = Array.prototype.indexOf; // bundles support (just like RequireJS) // bundle name is module name of bundle itself // bundle is array of modules defined by the bundle // when a module in the bundle is requested, the bundle is loaded instead // of the form System.bundles['mybundle'] = ['jquery', 'bootstrap/js/bootstrap'] loader.bundles = loader.bundles || {}; var loaderFetch = loader.fetch; loader.fetch = function(load) { var loader = this; if (loader.trace) return loaderFetch.call(this, load); if (!loader.bundles) loader.bundles = {}; // if this module is in a bundle, load the bundle first then for (var b in loader.bundles) { if (indexOf.call(loader.bundles[b], load.name) == -1) continue; // we do manual normalization in case the bundle is mapped // this is so we can still know the normalized name is a bundle return Promise.resolve(loader.normalize(b)) .then(function(normalized) { loader.bundles[normalized] = loader.bundles[normalized] || loader.bundles[b]; // note this module is a bundle in the meta loader.meta = loader.meta || {}; loader.meta[normalized] = loader.meta[normalized] || {}; loader.meta[normalized].bundle = true; return loader.load(normalized); }) .then(function() { return ''; }); } return loaderFetch.call(this, load); } }/* SystemJS Semver Version Addon 1. Uses Semver convention for major and minor forms Supports requesting a module from a package that contains a version suffix with the following semver ranges: module - any version module@1 - major version 1, any minor (not prerelease) module@1.2 - minor version 1.2, any patch (not prerelease) module@1.2.3 - exact version It is assumed that these modules are provided by the server / file system. First checks the already-requested packages to see if there are any packages that would match the same package and version range. This provides a greedy algorithm as a simple fix for sharing version-managed dependencies as much as possible, which can later be optimized through version hint configuration created out of deeper version tree analysis. 2. Semver-compatibility syntax (caret operator - ^) Compatible version request support is then also provided for: module@^1.2.3 - module@1, >=1.2.3 module@^1.2 - module@1, >=1.2.0 module@^1 - module@1 module@^0.5.3 - module@0.5, >= 0.5.3 module@^0.0.1 - module@0.0.1 The ^ symbol is always normalized out to a normal version request. This provides comprehensive semver compatibility. 3. System.versions version hints and version report Note this addon should be provided after all other normalize overrides. The full list of versions can be found at System.versions providing an insight into any possible version forks. It is also possible to create version solution hints on the System global: System.versions = { jquery: ['1.9.2', '2.0.3'], bootstrap: '3.0.1' }; Versions can be an array or string for a single version. When a matching semver request is made (jquery@1.9, jquery@1, bootstrap@3) they will be converted to the latest version match contained here, if present. Prereleases in this versions list are also allowed to satisfy ranges when present. */ function versions(loader) { if (typeof indexOf == 'undefined') indexOf = Array.prototype.indexOf; var semverRegEx = /^(\d+)(?:\.(\d+)(?:\.(\d+)(?:-([\da-z-]+(?:\.[\da-z-]+)*)(?:\+([\da-z-]+(?:\.[\da-z-]+)*))?)?)?)?$/i; var numRegEx = /^\d+$/; function toInt(num) { return parseInt(num, 10); } function parseSemver(v) { var semver = v.match(semverRegEx); if (!semver) return { tag: v }; else return { major: toInt(semver[1]), minor: toInt(semver[2]), patch: toInt(semver[3]), pre: semver[4] && semver[4].split('.') }; } var parts = ['major', 'minor', 'patch']; function semverCompareParsed(v1, v2) { // not semvers - tags have equal precedence if (v1.tag && v2.tag) return 0; // semver beats non-semver if (v1.tag) return -1; if (v2.tag) return 1; // compare version numbers for (var i = 0; i < parts.length; i++) { var part = parts[i]; var part1 = v1[part]; var part2 = v2[part]; if (part1 == part2) continue; if (isNaN(part1)) return -1; if (isNaN(part2)) return 1; return part1 > part2 ? 1 : -1; } if (!v1.pre && !v2.pre) return 0; if (!v1.pre) return 1; if (!v2.pre) return -1; // prerelease comparison for (var i = 0, l = Math.min(v1.pre.length, v2.pre.length); i < l; i++) { if (v1.pre[i] == v2.pre[i]) continue; var isNum1 = v1.pre[i].match(numRegEx); var isNum2 = v2.pre[i].match(numRegEx); // numeric has lower precedence if (isNum1 && !isNum2) return -1; if (isNum2 && !isNum1) return 1; // compare parts if (isNum1 && isNum2) return toInt(v1.pre[i]) > toInt(v2.pre[i]) ? 1 : -1; else return v1.pre[i] > v2.pre[i] ? 1 : -1; } if (v1.pre.length == v2.pre.length) return 0; // more pre-release fields win if equal return v1.pre.length > v2.pre.length ? 1 : -1; } // match against a parsed range object // saves operation repetition // doesn't support tags // if not semver or fuzzy, assume exact function matchParsed(range, version) { var rangeVersion = range.version; if (rangeVersion.tag) return rangeVersion.tag == version.tag; // if the version is less than the range, it's not a match if (semverCompareParsed(rangeVersion, version) == 1) return false; // now we just have to check that the version isn't too high for the range if (isNaN(version.minor) || isNaN(version.patch)) return false; // if the version has a prerelease, ensure the range version has a prerelease in it // and that we match the range version up to the prerelease exactly if (version.pre) { if (!(rangeVersion.major == version.major && rangeVersion.minor == version.minor && rangeVersion.patch == version.patch)) return false; return range.semver || range.fuzzy || rangeVersion.pre.join('.') == version.pre.join('.'); } // check semver range if (range.semver) { // ^0 if (rangeVersion.major == 0 && isNaN(rangeVersion.minor)) return version.major < 1; // ^1.. else if (rangeVersion.major >= 1) return rangeVersion.major == version.major; // ^0.1, ^0.2 else if (rangeVersion.minor >= 1) return rangeVersion.minor == version.minor; // ^0.0.0 else return (rangeVersion.patch || 0) == version.patch; } // check fuzzy range if (range.fuzzy) return version.major == rangeVersion.major && version.minor < (rangeVersion.minor || 0) + 1; // exact match // eg 001.002.003 matches 1.2.3 return !rangeVersion.pre && rangeVersion.major == version.major && rangeVersion.minor == version.minor && rangeVersion.patch == version.patch; } /* * semver - is this a semver range * fuzzy - is this a fuzzy range * version - the parsed version object */ function parseRange(range) { var rangeObj = {}; ((rangeObj.semver = range.substr(0, 1) == '^') || (rangeObj.fuzzy = range.substr(0, 1) == '~') ) && (range = range.substr(1)); var rangeVersion = rangeObj.version = parseSemver(range); if (rangeVersion.tag) return rangeObj; // 0, 0.1 behave like ~0, ~0.1 if (!rangeObj.fuzzy && !rangeObj.semver && (isNaN(rangeVersion.minor) || isNaN(rangeVersion.patch))) rangeObj.fuzzy = true; // ~1, ~0 behave like ^1, ^0 if (rangeObj.fuzzy && isNaN(rangeVersion.minor)) { rangeObj.semver = true; rangeObj.fuzzy = false; } // ^0.0 behaves like ~0.0 if (rangeObj.semver && !isNaN(rangeVersion.minor) && isNaN(rangeVersion.patch)) { rangeObj.semver = false; rangeObj.fuzzy = true; } return rangeObj; } function semverCompare(v1, v2) { return semverCompareParsed(parseSemver(v1), parseSemver(v2)); } loader.versions = loader.versions || {}; var loaderNormalize = loader.normalize; // NOW use modified match algorithm if possible loader.normalize = function(name, parentName, parentAddress) { if (!this.versions) this.versions = {}; var packageVersions = this.versions; // strip the version before applying map config var stripVersion, stripSubPathLength; var pluginIndex = name.lastIndexOf('!'); var versionIndex = (pluginIndex == -1 ? name : name.substr(0, pluginIndex)).lastIndexOf('@'); if (versionIndex > 0) { var parts = name.substr(versionIndex + 1, name.length - versionIndex - 1).split('/'); stripVersion = parts[0]; stripSubPathLength = parts.length; name = name.substr(0, versionIndex) + name.substr(versionIndex + stripVersion.length + 1, name.length - versionIndex - stripVersion.length - 1); } // run all other normalizers first return Promise.resolve(loaderNormalize.call(this, name, parentName, parentAddress)).then(function(normalized) { var index = normalized.indexOf('@'); // if we stripped a version, and it still has no version, add it back if (stripVersion && (index == -1 || index == 0)) { var parts = normalized.split('/'); parts[parts.length - stripSubPathLength] += '@' + stripVersion; normalized = parts.join('/'); index = normalized.indexOf('@'); } // see if this module corresponds to a package already in our versioned packages list // no version specified - check against the list (given we don't know the package name) var nextChar, versions; if (index == -1 || index == 0) { for (var p in packageVersions) { versions = packageVersions[p]; if (normalized.substr(0, p.length) != p) continue; nextChar = normalized.substr(p.length, 1); if (nextChar && nextChar != '/') continue; // match -> take latest version return p + '@' + (typeof versions == 'string' ? versions : versions[versions.length - 1]) + normalized.substr(p.length); } return normalized; } // get the version info var packageName = normalized.substr(0, index); var range = normalized.substr(index + 1).split('/')[0]; var rangeLength = range.length; var parsedRange = parseRange(normalized.substr(index + 1).split('/')[0]); versions = packageVersions[normalized.substr(0, index)] || []; if (typeof versions == 'string') versions = [versions]; // find a match in our version list for (var i = versions.length - 1; i >= 0; i--) { if (matchParsed(parsedRange, parseSemver(versions[i]))) return packageName + '@' + versions[i] + normalized.substr(index + rangeLength + 1); } // no match found -> send a request to the server var versionRequest; if (parsedRange.semver) { versionRequest = parsedRange.version.major == 0 && !isNaN(parsedRange.version.minor) ? '0.' + parsedRange.version.minor : parsedRange.version.major; } else if (parsedRange.fuzzy) { versionRequest = parsedRange.version.major + '.' + parsedRange.version.minor; } else { versionRequest = range; versions.push(range); versions.sort(semverCompare); packageVersions[packageName] = versions.length == 1 ? versions[0] : versions; } return packageName + '@' + versionRequest + normalized.substr(index + rangeLength + 1); }); } } /* * Dependency Tree Cache * * Allows a build to pre-populate a dependency trace tree on the loader of * the expected dependency tree, to be loaded upfront when requesting the * module, avoinding the n round trips latency of module loading, where * n is the dependency tree depth. * * eg: * System.depCache = { * 'app': ['normalized', 'deps'], * 'normalized': ['another'], * 'deps': ['tree'] * }; * * System.import('app') * // simultaneously starts loading all of: * // 'normalized', 'deps', 'another', 'tree' * // before "app" source is even loaded */ function depCache(loader) { loader.depCache = loader.depCache || {}; loaderLocate = loader.locate; loader.locate = function(load) { var loader = this; if (!loader.depCache) loader.depCache = {}; // load direct deps, in turn will pick up their trace trees var deps = loader.depCache[load.name]; if (deps) for (var i = 0; i < deps.length; i++) loader.load(deps[i]); return loaderLocate.call(loader, load); } } meta(System); register(System); core(System); global(System); cjs(System); amd(System); map(System); plugins(System); bundles(System); versions(System); depCache(System); if (!System.paths['@traceur']) System.paths['@traceur'] = $__curScript && $__curScript.getAttribute('data-traceur-src') || ($__curScript && $__curScript.src ? $__curScript.src.substr(0, $__curScript.src.lastIndexOf('/') + 1) : System.baseURL + (System.baseURL.lastIndexOf('/') == System.baseURL.length - 1 ? '' : '/') ) + 'traceur.js'; if (!System.paths['@traceur-runtime']) System.paths['@traceur-runtime'] = $__curScript && $__curScript.getAttribute('data-traceur-runtime-src') || System.paths['@traceur'].replace(/\.js$/, '-runtime.js'); }; var $__curScript, __eval; (function() { var doEval; __eval = function(source, address, sourceMap) { source += '\n//# sourceURL=' + address + (sourceMap ? '\n//# sourceMappingURL=' + sourceMap : ''); try { doEval(source); } catch(e) { var msg = 'Error evaluating ' + address + '\n'; if (e instanceof Error) e.message = msg + e.message; else e = msg + e; throw e; } }; var isWorker = typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope; var isBrowser = typeof window != 'undefined'; if (isBrowser) { var head; var scripts = document.getElementsByTagName('script'); $__curScript = scripts[scripts.length - 1]; // globally scoped eval for the browser doEval = function(source) { if (!head) head = document.head || document.body || document.documentElement; var script = document.createElement('script'); script.text = source; var onerror = window.onerror; var e; window.onerror = function(_e) { e = _e; } head.appendChild(script); head.removeChild(script); window.onerror = onerror; if (e) throw e; } if (!$__global.System || !$__global.LoaderPolyfill) { // determine the current script path as the base path var curPath = $__curScript.src; var basePath = curPath.substr(0, curPath.lastIndexOf('/') + 1); document.write( '<' + 'script type="text/javascript" src="' + basePath + 'es6-module-loader.js" data-init="upgradeSystemLoader">' + '<' + '/script>' ); } else { $__global.upgradeSystemLoader(); } } else if(isWorker) { doEval = function(source) { try { eval(source); } catch(e) { throw e; } }; if (!$__global.System || !$__global.LoaderPolyfill) { var basePath = ''; try { throw new TypeError('Unable to get Worker base path.'); } catch(err) { var idx = err.stack.indexOf('at ') + 3; var withSystem = err.stack.substr(idx, err.stack.substr(idx).indexOf('\n')); basePath = withSystem.substr(0, withSystem.lastIndexOf('/') + 1); } importScripts(basePath + 'es6-module-loader.js'); } else { $__global.upgradeSystemLoader(); } } else { var es6ModuleLoader = require('es6-module-loader'); $__global.System = es6ModuleLoader.System; $__global.Loader = es6ModuleLoader.Loader; $__global.upgradeSystemLoader(); module.exports = $__global.System; // global scoped eval for node var vm = require('vm'); doEval = function(source, address, sourceMap) { vm.runInThisContext(source); } } })(); })(typeof window != 'undefined' ? window : (typeof WorkerGlobalScope != 'undefined' ? self : global));
var Ap = AccountsCommon.prototype; var defaultRateLimiterRuleId; // Removes default rate limiting rule Ap.removeDefaultRateLimit = function () { const resp = DDPRateLimiter.removeRule(defaultRateLimiterRuleId); defaultRateLimiterRuleId = null; return resp; } // Add a default rule of limiting logins, creating new users and password reset // to 5 times every 10 seconds per connection. Ap.addDefaultRateLimit = function () { if (!defaultRateLimiterRuleId) { defaultRateLimiterRuleId = DDPRateLimiter.addRule({ userId: null, clientAddress: null, type: 'method', name: function (name) { return _.contains(['login', 'createUser', 'resetPassword', 'forgotPassword'], name); }, connectionId: function (connectionId) { return true; } }, 5, 10000); } } Ap.addDefaultRateLimit();
/** * @preserve EventEmitter v1.1.2 * * Copyright 2011, Oliver Caldwell (flowdev.co.uk) * Dual licensed under the MIT or GPL Version 2 licenses. * https://github.com/Wolfy87/EventEmitter */ // Initialise the class function EventEmitter() { // Initialise the storage variables this._events = {}; this._listeners = []; this._maxListeners = 10; } /** * Converts an event name to a RegExp pattern * * @param {String} name Name of the event * * @return {String} RegExp pattern */ EventEmitter.prototype._convertNameToRegExp = function(name) { return name.replace(/\./g, '\\.').replace(/\*\\\./g, '[\\w\\-]+\\.').replace(/\*$/gi, '.+'); }; /** * Adds a listener for a specified event * * @param {String} name Name of the event * @param {Function} listener Run when the event is emitted * @param {Boolean} once If true, the listener will only be run once, use EventEmitter.once instead, this is mainly for internal use */ EventEmitter.prototype.addListener = function(name, listener, once) { // Grab the index of the listener var index = this._listeners.length; // Emit the newListener event this.emit('newListener', name, listener); // Add the listener this._listeners.push({ listener: listener, once: (once) ? true : false }); // Convert event name to RegExp name = this._convertNameToRegExp(name); // Add the event to the events object if required if(typeof this._events[name] === 'undefined') { this._events[name] = []; } // Add the listeners index to the event this._events[name].push(index); // Check if we have exceeded the max listeners if(this._events[name].length === this._maxListeners) { // We have, let the developer know console.log('Maximum number of listeners (' + this._maxListeners + ') reached for the "' + name + '" event!'); } }; /** * Adds a listener for a specified event (alias of EventEmitter.addListener) * * @param {String} name Name of the event * @param {Function} listener Run when the event is emitted * @param {Boolean} once If true, the listener will only be run once, use EventEmitter.once instead, this is mainly for internal use */ EventEmitter.prototype.on = EventEmitter.prototype.addListener; /** * Adds a listener for a specified event that will only be called once * * @param {String} name Name of the event * @param {Function} listener Run when the event is emitted */ EventEmitter.prototype.once = function(name, listener) { this.addListener(name, listener, true); }; /** * Removes a listener for a specified event * * @param {String} name Name of the event * @param {Function} listener Reference to the listener function */ EventEmitter.prototype.removeListener = function(name, listener) { // Initialise any required variables var i = null, indexes = null; // Convert event name to RegExp name = this._convertNameToRegExp(name); // Make sure the event exists if(this._events[name] instanceof Array) { // Grab the listeners indexes indexes = this._events[name]; // Loop through all of the indexes for(i = 0; i < indexes.length; i++) { // Check if we have found the listener if(this._listeners[indexes[i]].listener === listener) { // It is, remove it and return indexes.splice(i, 1); } } } }; /** * Removes all the listeners for a specified event * * @param {String} name Name of the event */ EventEmitter.prototype.removeAllListeners = function(name) { name = this._convertNameToRegExp(name); this._events[name] = []; }; /** * Sets the max number of listeners before a message is displayed * If it is set to 0 then there is no limit * * @param {Number} n Max number of listeners before a message is displayed */ EventEmitter.prototype.setMaxListeners = function(n) { this._maxListeners = n; }; /** * Returns an array of listeners for the specified event * * @param {String} name Name of the event * @param {Boolean} checkOnce Mainly for internal use, but if true, it will check if the once flag is set on the listener and remove it if it is * @returns {Array} An array of the assigned listeners */ EventEmitter.prototype.listeners = function(name, checkOnce) { // Initialise any required variables var eventRegExp = null, i = null, built = [], l = null; // Loop through each event RegExp for(eventRegExp in this._events) { // If the event RegExp matches the event name if(name.match(new RegExp('^'+eventRegExp+'$')) && this._events[eventRegExp] instanceof Array) { // Grab the listeners indexes indexes = this._events[eventRegExp]; // Loop through all of the indexes for(i = 0; i < indexes.length; i++) { // Grab the listener l = this._listeners[indexes[i]]; if(checkOnce) { if(l.once) { // Add it to the array built.push(l.listener); // Remove the reference this._events[eventRegExp].splice(i, 1); } else { // Add it to the array built.push(l.listener); } } else { // Add it to the array built.push(l.listener); } } } } // Return the found listeners return built; }; /** * Emits the specified event with optional arguments * * @param {String} name Name of the event to be emitted * @param {Mixed} An argument to be passed to the listeners, you can have as many of these as you want */ EventEmitter.prototype.emit = function(name) { // Initialise any required variables var i = null, args = Array.prototype.slice.call(arguments), listeners = this.listeners(name, true); // Check if there are no listeners for the event if(listeners.length === 0) { // If it is an error event, throw an exception // Otherwise, return false if(name === 'error') { throw 'unspecifiedErrorEvent'; } else { return false; } } // Splice out the first argument args.splice(0, 1); // Loop through the listeners for(i = 0; i < listeners.length; i++) { // Call the function listeners[i].apply(null, args); } return true; };
// Copyright 2015 The Closure Library Authors. 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 Utilities for working with promises. * Note that this file is written ES5-only. */ goog.module('goog.labs.promise'); var Promise = goog.require('goog.Promise'); /** * Executes an ES6 generator function that may yield Promises, blocking after * each Promise until it settles. Within the generator, the value of each * 'yield' expression becomes the resolved value of the yielded promise. * * If the generator function throws an exception or yields a rejected promise, * execution stops, and the promise returned by this function is rejected. * * A typical call uses generator function syntax: * * goog.labs.promise.run(function*() { * console.log('about to start waiting'); * while (needsToWait()) { * // Wait 10 seconds. * yield goog.Timer.promise(10000); * console.log('still waiting...'); * } * }).then(() => { * console.log('done waiting'); * }); * * This function can also be used to simplify asynchronous code: * * goog.labs.promise.run(function*()) { * var x = yield somethingThatReturnsAPromise(); * var y = yield somethingElseThatReturnsAPromise(); * return x + y; * }).then(sum => { * console.log('The sum is:', sum); * }); * * @param {function(this: CONTEXT):TYPE} generatorFunc A function which is * called immediately and returns a generator. * @param {CONTEXT=} opt_context The context in which generatorFunc should be * called. * @return {!goog.Promise<TYPE>} A promise that is resolved when the generator * returned from generatorFunc is exhausted, or rejected if an error occurs. * If the generator function returns, this promise resolves to the returned * value. * @template CONTEXT, TYPE */ exports.run = function(generatorFunc, opt_context) { var generator = generatorFunc.call(opt_context); /** * @param {*} previousResolvedValue * @param {boolean=} opt_isRejected */ function loop(previousResolvedValue, opt_isRejected) { var gen = opt_isRejected ? generator['throw'](previousResolvedValue) : generator.next(previousResolvedValue); if (!gen.done) { // Wrap gen.value in a promise in case it isn't a promise already. return Promise.resolve(gen.value).then( function(resolvedValue) { return loop(resolvedValue); }, function(rejectValue) { return loop(rejectValue, true); }); } return gen.value; } // Call loop() from then() to ensure exceptions are captured. return Promise.resolve().then(loop); };
// All properties we can use to start a query chain // from the `knex` object, e.g. `knex.select('*').from(...` module.exports = [ 'select', 'as', 'columns', 'column', 'from', 'into', 'table', 'distinct', 'join', 'innerJoin', 'leftJoin', 'leftOuterJoin', 'rightJoin', 'rightOuterJoin', 'outerJoin', 'fullOuterJoin', 'crossJoin', 'where', 'andWhere', 'orWhere', 'whereRaw', 'whereWrapped', 'orWhereRaw', 'whereExists', 'orWhereExists', 'whereNotExists', 'orWhereNotExists', 'whereIn', 'orWhereIn', 'whereNotIn', 'orWhereNotIn', 'whereNull', 'orWhereNull', 'whereNotNull', 'orWhereNotNull', 'whereBetween', 'whereNotBetween', 'orWhereBetween', 'orWhereNotBetween', 'groupBy', 'groupByRaw', 'orderBy', 'orderByRaw', 'union', 'unionAll', 'having', 'havingRaw', 'orHaving', 'orHavingRaw', 'offset', 'limit', 'count', 'min', 'max', 'sum', 'avg', 'increment', 'decrement', 'first', 'debug', 'pluck', 'insert', 'update', 'returning', 'del', 'delete', 'truncate', 'transacting', 'connection' ];
(function webpackUniversalModuleDefinition(root, factory) { if(typeof exports === 'object' && typeof module === 'object') module.exports = factory(); else if(typeof define === 'function' && define.amd) define([], factory); else if(typeof exports === 'object') exports["cellx"] = factory(); else root["cellx"] = factory(); })(this, function() { return /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) /******/ return installedModules[moduleId].exports; /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ exports: {}, /******/ id: moduleId, /******/ loaded: false /******/ }; /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ // Flag the module as loaded /******/ module.loaded = true; /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ // Load entry module and return exports /******/ return __webpack_require__(0); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(global) {var Map = __webpack_require__(1); var Symbol = __webpack_require__(2); var logError = __webpack_require__(7); var nextUID = __webpack_require__(3); var mixin = __webpack_require__(5); var createClass = __webpack_require__(4); var nextTick = __webpack_require__(8); var keys = __webpack_require__(6); var ErrorLogger = __webpack_require__(9); var EventEmitter = __webpack_require__(10); var ObservableMap = __webpack_require__(11); var ObservableList = __webpack_require__(14); var Cell = __webpack_require__(15); var KEY_UID = keys.UID; var KEY_CELLS = keys.CELLS; var hasOwn = Object.prototype.hasOwnProperty; var slice = Array.prototype.slice; ErrorLogger.setHandler(logError); /** * @typesign (value?, opts?: { * debugKey?: string, * owner?: Object, * validate?: (value, oldValue), * onChange?: (evt: cellx~Event) -> ?boolean, * onError?: (evt: cellx~Event) -> ?boolean * }) -> cellx; * * @typesign (pull: (push: (value), fail: (err), oldValue) -> *, opts?: { * debugKey?: string * owner?: Object, * validate?: (value, oldValue), * put?: (value, push: (value), fail: (err), oldValue), * reap?: (), * onChange?: (evt: cellx~Event) -> ?boolean, * onError?: (evt: cellx~Event) -> ?boolean * }) -> cellx; */ function cellx(value, opts) { if (!opts) { opts = {}; } var initialValue = value; function cx(value) { var owner = this; if (!owner || owner == global) { owner = cx; } if (!hasOwn.call(owner, KEY_CELLS)) { Object.defineProperty(owner, KEY_CELLS, { value: new Map() }); } var cell = owner[KEY_CELLS].get(cx); if (!cell) { if (value === 'dispose' && arguments.length >= 2) { return; } opts = Object.create(opts); opts.owner = owner; cell = new Cell(initialValue, opts); owner[KEY_CELLS].set(cx, cell); } switch (arguments.length) { case 0: { return cell.get(); } case 1: { cell.set(value); return value; } default: { switch (value) { case 'bind': { cx = cx.bind(owner); cx.constructor = cellx; return cx; } case 'unwrap': { return cell; } default: { var result = Cell.prototype[value].apply(cell, slice.call(arguments, 1)); return result === cell ? cx : result; } } } } } cx.constructor = cellx; if (opts.onChange || opts.onError) { cx.call(opts.owner || global); } return cx; } cellx.KEY_UID = KEY_UID; cellx.ErrorLogger = ErrorLogger; cellx.EventEmitter = EventEmitter; cellx.ObservableMap = ObservableMap; cellx.ObservableList = ObservableList; cellx.Cell = Cell; /** * @typesign ( * entries?: Object|Array<{ 0, 1 }>|cellx.ObservableMap, * opts?: { adoptsItemChanges?: boolean } * ) -> cellx.ObservableMap; * * @typesign ( * entries?: Object|Array<{ 0, 1 }>|cellx.ObservableMap, * adoptsItemChanges?: boolean * ) -> cellx.ObservableMap; */ function map(entries, opts) { return new ObservableMap(entries, typeof opts == 'boolean' ? { adoptsItemChanges: opts } : opts); } cellx.map = map; /** * @typesign (items?: Array|cellx.ObservableList, opts?: { * adoptsItemChanges?: boolean, * comparator?: (a, b) -> int, * sorted?: boolean * }) -> cellx.ObservableList; * * @typesign (items?: Array|cellx.ObservableList, adoptsItemChanges?: boolean) -> cellx.ObservableList; */ function list(items, opts) { return new ObservableList(items, typeof opts == 'boolean' ? { adoptsItemChanges: opts } : opts); } cellx.list = list; /** * @typesign (obj: cellx.EventEmitter, name: string, value) -> cellx.EventEmitter; */ function defineObservableProperty(obj, name, value) { var _name = '_' + name; obj[_name] = typeof value == 'function' && value.constructor == cellx ? value : cellx(value); Object.defineProperty(obj, name, { configurable: true, enumerable: true, get: function() { return this[_name](); }, set: function(value) { this[_name](value); } }); return obj; } /** * @typesign (obj: cellx.EventEmitter, props: Object) -> cellx.EventEmitter; */ function defineObservableProperties(obj, props) { Object.keys(props).forEach(function(name) { defineObservableProperty(obj, name, props[name]); }); return obj; } /** * @typesign (obj: cellx.EventEmitter, name: string, value) -> cellx.EventEmitter; * @typesign (obj: cellx.EventEmitter, props: Object) -> cellx.EventEmitter; */ function define(obj, name, value) { if (arguments.length == 3) { defineObservableProperty(obj, name, value); } else { defineObservableProperties(obj, name); } return obj; } cellx.define = define; cellx.js = { Symbol: Symbol, Map: Map }; cellx.utils = { logError: logError, nextUID: nextUID, mixin: mixin, createClass: createClass, nextTick: nextTick, defineObservableProperty: defineObservableProperty, defineObservableProperties: defineObservableProperties }; cellx.cellx = cellx; // for destructuring module.exports = cellx; /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()))) /***/ }, /* 1 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(global) {var Symbol = __webpack_require__(2); var nextUID = __webpack_require__(3); var createClass = __webpack_require__(4); var keys = __webpack_require__(6); var KEY_UID = keys.UID; var hasOwn = Object.prototype.hasOwnProperty; var Map = global.Map; if (!Map) { var entryStub = { value: void 0 }; Map = createClass({ constructor: function Map(entries) { this._entries = Object.create(null); this._objectStamps = {}; this._first = null; this._last = null; this.size = 0; if (entries) { for (var i = 0, l = entries.length; i < l; i++) { this.set(entries[i][0], entries[i][1]); } } }, has: function has(key) { return !!this._entries[this._getValueStamp(key)]; }, get: function get(key) { return (this._entries[this._getValueStamp(key)] || entryStub).value; }, set: function set(key, value) { var entries = this._entries; var keyStamp = this._getValueStamp(key); if (entries[keyStamp]) { entries[keyStamp].value = value; } else { var entry = entries[keyStamp] = { key: key, keyStamp: keyStamp, value: value, prev: this._last, next: null }; if (this.size++) { this._last.next = entry; } else { this._first = entry; } this._last = entry; } return this; }, delete: function _delete(key) { var keyStamp = this._getValueStamp(key); var entry = this._entries[keyStamp]; if (!entry) { return false; } if (--this.size) { var prev = entry.prev; var next = entry.next; if (prev) { prev.next = next; } else { this._first = next; } if (next) { next.prev = prev; } else { this._last = prev; } } else { this._first = null; this._last = null; } delete this._entries[keyStamp]; delete this._objectStamps[keyStamp]; return true; }, clear: function clear() { var entries = this._entries; for (var stamp in entries) { delete entries[stamp]; } this._objectStamps = {}; this._first = null; this._last = null; this.size = 0; }, _getValueStamp: function _getValueStamp(value) { switch (typeof value) { case 'undefined': { return 'undefined'; } case 'object': { if (value === null) { return 'null'; } break; } case 'boolean': { return '?' + value; } case 'number': { return '+' + value; } case 'string': { return ',' + value; } } return this._getObjectStamp(value); }, _getObjectStamp: function _getObjectStamp(obj) { if (!hasOwn.call(obj, KEY_UID)) { if (!Object.isExtensible(obj)) { var stamps = this._objectStamps; var stamp; for (stamp in stamps) { if (hasOwn.call(stamps, stamp) && stamps[stamp] == obj) { return stamp; } } stamp = nextUID(); stamps[stamp] = obj; return stamp; } Object.defineProperty(obj, KEY_UID, { value: nextUID() }); } return obj[KEY_UID]; }, forEach: function forEach(cb, context) { if (context == null) { context = global; } var entry = this._first; while (entry) { cb.call(context, entry.value, entry.key, this); do { entry = entry.next; } while (entry && !this._entries[entry.keyStamp]); } }, toString: function toString() { return '[object Map]'; } }); [ ['keys', function keys(entry) { return entry.key; }], ['values', function values(entry) { return entry.value; }], ['entries', function entries(entry) { return [entry.key, entry.value]; }] ].forEach(function(settings) { var getStepValue = settings[1]; Map.prototype[settings[0]] = function() { var entries = this._entries; var entry; var done = false; var map = this; return { next: function() { if (!done) { if (entry) { do { entry = entry.next; } while (entry && !entries[entry.keyStamp]); } else { entry = map._first; } if (entry) { return { value: getStepValue(entry), done: false }; } done = true; } return { value: void 0, done: true }; } }; }; }); } if (!Map.prototype[Symbol.iterator]) { Map.prototype[Symbol.iterator] = Map.prototype.entries; } module.exports = Map; /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()))) /***/ }, /* 2 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(global) {var nextUID = __webpack_require__(3); var Symbol = global.Symbol; if (!Symbol) { Symbol = function Symbol(key) { return '__' + key + '_' + Math.floor(Math.random() * 1e9) + '_' + nextUID() + '__'; }; Symbol.iterator = Symbol('iterator'); } module.exports = Symbol; /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()))) /***/ }, /* 3 */ /***/ function(module, exports) { var uidCounter = 0; /** * @typesign () -> string; */ function nextUID() { return String(++uidCounter); } module.exports = nextUID; /***/ }, /* 4 */ /***/ function(module, exports, __webpack_require__) { var mixin = __webpack_require__(5); var hasOwn = Object.prototype.hasOwnProperty; var extend; /** * @typesign (description: { * Extends?: Function, * Implements?: Array<Object|Function>, * Static?: Object, * constructor?: Function, * [key: string] * }) -> Function; */ function createClass(description) { var parent; if (description.Extends) { parent = description.Extends; delete description.Extends; } else { parent = Object; } var constr; if (hasOwn.call(description, 'constructor')) { constr = description.constructor; delete description.constructor; } else { constr = parent == Object ? function() {} : function() { return parent.apply(this, arguments); }; } var proto = constr.prototype = Object.create(parent.prototype); if (description.Implements) { description.Implements.forEach(function(implementation) { if (typeof implementation == 'function') { Object.keys(implementation).forEach(function(name) { Object.defineProperty(constr, name, Object.getOwnPropertyDescriptor(implementation, name)); }); mixin(proto, implementation.prototype); } else { mixin(proto, implementation); } }); delete description.Implements; } Object.keys(parent).forEach(function(name) { Object.defineProperty(constr, name, Object.getOwnPropertyDescriptor(parent, name)); }); if (description.Static) { mixin(constr, description.Static); delete description.Static; } if (constr.extend === void 0) { constr.extend = extend; } mixin(proto, description); Object.defineProperty(proto, 'constructor', { configurable: true, writable: true, value: constr }); return constr; } /** * @this {Function} * * @typesign (description: { * Implements?: Array<Object|Function>, * Static?: Object, * constructor?: Function, * [key: string] * }) -> Function; */ extend = function extend(description) { description.Extends = this; return createClass(description); }; module.exports = createClass; /***/ }, /* 5 */ /***/ function(module, exports) { /** * @typesign (target: Object, source: Object) -> Object; */ function mixin(target, source) { var names = Object.getOwnPropertyNames(source); for (var i = 0, l = names.length; i < l; i++) { var name = names[i]; Object.defineProperty(target, name, Object.getOwnPropertyDescriptor(source, name)); } return target; } module.exports = mixin; /***/ }, /* 6 */ /***/ function(module, exports, __webpack_require__) { var Symbol = __webpack_require__(2); var keys = { UID: Symbol('uid'), CELLS: Symbol('cells') }; module.exports = keys; /***/ }, /* 7 */ /***/ function(module, exports) { /* WEBPACK VAR INJECTION */(function(global) {function noop() {} var map = Array.prototype.map; /** * @typesign (...msg); */ function logError() { var console = global.console; (console && console.error || noop).call(console || global, map.call(arguments, function(part) { return part === Object(part) && part.stack || part; }).join(' ')); } module.exports = logError; /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()))) /***/ }, /* 8 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(global) {var ErrorLogger = __webpack_require__(9); /** * @typesign (cb: ()); */ var nextTick; if (global.process && process.toString() == '[object process]' && process.nextTick) { nextTick = process.nextTick; } else if (global.setImmediate) { nextTick = function nextTick(cb) { setImmediate(cb); }; } else if (global.Promise && Promise.toString().indexOf('[native code]') != -1) { var prm = Promise.resolve(); nextTick = function nextTick(cb) { prm.then(function() { cb(); }); }; } else { var queue; global.addEventListener('message', function() { if (queue) { var track = queue; queue = null; for (var i = 0, l = track.length; i < l; i++) { try { track[i](); } catch (err) { ErrorLogger.log(err); } } } }); nextTick = function nextTick(cb) { if (queue) { queue.push(cb); } else { queue = [cb]; postMessage('__tic__', '*'); } }; } module.exports = nextTick; /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()))) /***/ }, /* 9 */ /***/ function(module, exports) { var ErrorLogger = { _handler: null, /** * @typesign (handler: (...msg)); */ setHandler: function setHandler(handler) { this._handler = handler; }, /** * @typesign (...msg); */ log: function log() { this._handler.apply(this, arguments); } }; module.exports = ErrorLogger; /***/ }, /* 10 */ /***/ function(module, exports, __webpack_require__) { var Symbol = __webpack_require__(2); var createClass = __webpack_require__(4); var ErrorLogger = __webpack_require__(9); var hasOwn = Object.prototype.hasOwnProperty; var KEY_INNER = Symbol('inner'); /** * @typedef {{ * target?: Object, * type: string, * bubbles?: boolean, * isPropagationStopped?: boolean * }} cellx~Event */ /** * @class cellx.EventEmitter * @extends {Object} * @typesign new () -> cellx.EventEmitter; */ var EventEmitter = createClass({ Static: { KEY_INNER: KEY_INNER }, constructor: function EventEmitter() { /** * @type {Object<Array<{ * listener: (evt: cellx~Event) -> ?boolean, * context * }>>} */ this._events = Object.create(null); }, /** * @typesign ( * type: string, * listener: (evt: cellx~Event) -> ?boolean, * context? * ) -> cellx.EventEmitter; * * @typesign ( * listeners: Object<(evt: cellx~Event) -> ?boolean>, * context? * ) -> cellx.EventEmitter; */ on: function on(type, listener, context) { if (typeof type == 'object') { context = listener; var listeners = type; for (type in listeners) { if (hasOwn.call(listeners, type)) { this._on(type, listeners[type], context); } } } else { this._on(type, listener, context); } return this; }, /** * @typesign ( * type: string, * listener: (evt: cellx~Event) -> ?boolean, * context? * ) -> cellx.EventEmitter; * * @typesign ( * listeners: Object<(evt: cellx~Event) -> ?boolean>, * context? * ) -> cellx.EventEmitter; * * @typesign () -> cellx.EventEmitter; */ off: function off(type, listener, context) { if (type) { if (typeof type == 'object') { context = listener; var listeners = type; for (type in listeners) { if (hasOwn.call(listeners, type)) { this._off(type, listeners[type], context); } } } else { this._off(type, listener, context); } } else if (this._events) { this._events = Object.create(null); } return this; }, /** * @typesign ( * type: string, * listener: (evt: cellx~Event) -> ?boolean, * context? * ); */ _on: function _on(type, listener, context) { var index = type.indexOf(':'); if (index != -1) { this['_' + type.slice(index + 1)]('on', type.slice(0, index), listener, context); } else { var events = (this._events || (this._events = Object.create(null)))[type]; if (!events) { events = this._events[type] = []; } events.push({ listener: listener, context: context == null ? this : context }); } }, /** * @typesign ( * type: string, * listener: (evt: cellx~Event) -> ?boolean, * context? * ); */ _off: function _off(type, listener, context) { var index = type.indexOf(':'); if (index != -1) { this['_' + type.slice(index + 1)]('off', type.slice(0, index), listener, context); } else { var events = this._events && this._events[type]; if (!events) { return; } if (context == null) { context = this; } for (var i = events.length; i;) { var evt = events[--i]; if ((evt.listener == listener || evt.listener[KEY_INNER] === listener) && evt.context === context) { events.splice(i, 1); break; } } if (!events.length) { delete this._events[type]; } } }, /** * @typesign ( * type: string, * listener: (evt: cellx~Event) -> ?boolean, * context? * ) -> cellx.EventEmitter; */ once: function once(type, listener, context) { function wrapper() { this._off(type, wrapper, context); return listener.apply(this, arguments); } wrapper[KEY_INNER] = listener; this._on(type, wrapper, context); return this; }, /** * @typesign (evt: cellx~Event) -> cellx~Event; * @typesign (type: string) -> cellx~Event; */ emit: function emit(evt) { if (typeof evt == 'string') { evt = { target: this, type: evt }; } else if (!evt.target) { evt.target = this; } else if (evt.target != this) { throw new TypeError('Event cannot be emitted on this object'); } this._handleEvent(evt); return evt; }, /** * @typesign (evt: cellx~Event); * * For override: * @example * function View(el) { * this.element = el; * el._view = this; * } * * View.prototype = Object.create(EventEmitter.prototype); * View.prototype.constructor = View; * * View.prototype.getParent = function() { * var node = this.element; * * while (node = node.parentNode) { * if (node._view) { * return node._view; * } * } * * return null; * }; * * View.prototype._handleEvent = function(evt) { * EventEmitter.prototype._handleEvent.call(this, evt); * * if (evt.bubbles !== false && !evt.isPropagationStopped) { * var parent = this.getParent(); * * if (parent) { * parent._handleEvent(evt); * } * } * }; */ _handleEvent: function _handleEvent(evt) { var events = this._events && this._events[evt.type]; if (events) { events = events.slice(); for (var i = 0, l = events.length; i < l; i++) { try { if (events[i].listener.call(events[i].context, evt) === false) { evt.isPropagationStopped = true; } } catch (err) { this._logError(err); } } } }, /** * @typesign (...msg); */ _logError: function _logError() { ErrorLogger.log.apply(ErrorLogger, arguments); } }); module.exports = EventEmitter; /***/ }, /* 11 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(global) {var Map = __webpack_require__(1); var Symbol = __webpack_require__(2); var is = __webpack_require__(12); var EventEmitter = __webpack_require__(10); var ObservableCollectionMixin = __webpack_require__(13); var hasOwn = Object.prototype.hasOwnProperty; var isArray = Array.isArray; /** * @class cellx.ObservableMap * @extends {cellx.EventEmitter} * @implements {ObservableCollectionMixin} * * @typesign new (entries?: Object|cellx.ObservableMap|Map|Array<{ 0, 1 }>, opts?: { * adoptsItemChanges?: boolean * }) -> cellx.ObservableMap; */ var ObservableMap = EventEmitter.extend({ Implements: [ObservableCollectionMixin], constructor: function ObservableMap(entries, opts) { EventEmitter.call(this); ObservableCollectionMixin.call(this); this._entries = new Map(); this.size = 0; /** * @type {boolean} */ this.adoptsItemChanges = !opts || opts.adoptsItemChanges !== false; if (entries) { var mapEntries = this._entries; if (entries instanceof ObservableMap || entries instanceof Map) { entries._entries.forEach(function(value, key) { mapEntries.set(key, value); this._registerValue(value); }, this); } else if (isArray(entries)) { for (var i = 0, l = entries.length; i < l; i++) { var entry = entries[i]; mapEntries.set(entry[0], entry[1]); this._registerValue(entry[1]); } } else { for (var key in entries) { if (hasOwn.call(entries, key)) { mapEntries.set(key, entries[key]); this._registerValue(entries[key]); } } } this.size = mapEntries.size; } }, /** * @typesign (key) -> boolean; */ has: function has(key) { return this._entries.has(key); }, /** * @typesign (value) -> boolean; */ contains: function contains(value) { return this._valueCounts.has(value); }, /** * @typesign (key) -> *; */ get: function get(key) { return this._entries.get(key); }, /** * @typesign (key, value) -> cellx.ObservableMap; */ set: function set(key, value) { var entries = this._entries; var hasKey = entries.has(key); var oldValue; if (hasKey) { oldValue = entries.get(key); if (is(oldValue, value)) { return this; } this._unregisterValue(oldValue); } entries.set(key, value); this._registerValue(value); if (!hasKey) { this.size++; } this.emit({ type: 'change', subtype: hasKey ? 'update' : 'add', key: key, oldValue: oldValue, value: value }); return this; }, /** * @typesign (key) -> boolean; */ delete: function _delete(key) { var entries = this._entries; if (!entries.has(key)) { return false; } var value = entries.get(key); entries.delete(key); this._unregisterValue(value); this.size--; this.emit({ type: 'change', subtype: 'delete', key: key, oldValue: value, value: void 0 }); return true; }, /** * @typesign () -> cellx.ObservableMap; */ clear: function clear() { if (!this.size) { return this; } if (this.adoptsItemChanges) { this._valueCounts.forEach(function(value) { if (value instanceof EventEmitter) { value.off('change', this._onItemChange, this); } }, this); } this._entries.clear(); this._valueCounts.clear(); this.size = 0; this.emit({ type: 'change', subtype: 'clear' }); return this; }, /** * @typesign ( * cb: (value, key, map: cellx.ObservableMap), * context? * ); */ forEach: function forEach(cb, context) { if (context == null) { context = global; } this._entries.forEach(function(value, key) { cb.call(context, value, key, this); }, this); }, /** * @typesign () -> { next: () -> { value, done: boolean } }; */ keys: function keys() { return this._entries.keys(); }, /** * @typesign () -> { next: () -> { value, done: boolean } }; */ values: function values() { return this._entries.values(); }, /** * @typesign () -> { next: () -> { value: { 0, 1 }, done: boolean } }; */ entries: function entries() { return this._entries.entries(); }, /** * @typesign () -> cellx.ObservableMap; */ clone: function clone() { return new this.constructor(this, { adoptsItemChanges: this.adoptsItemChanges }); } }); ObservableMap.prototype[Symbol.iterator] = ObservableMap.prototype.entries; module.exports = ObservableMap; /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()))) /***/ }, /* 12 */ /***/ function(module, exports) { /** * @typesign (a, b) -> boolean; */ var is = Object.is || function is(a, b) { if (a === 0 && b === 0) { return 1 / a == 1 / b; } return a === b || (a != a && b != b); }; module.exports = is; /***/ }, /* 13 */ /***/ function(module, exports, __webpack_require__) { var Map = __webpack_require__(1); var EventEmitter = __webpack_require__(10); var ObservableCollectionMixin = EventEmitter.extend({ constructor: function ObservableCollectionMixin() { /** * @type {Map<*, uint>} */ this._valueCounts = new Map(); }, /** * @typesign (evt: cellx~Event); */ _onItemChange: function _onItemChange(evt) { this._handleEvent(evt); }, /** * @typesign (value); */ _registerValue: function _registerValue(value) { var valueCounts = this._valueCounts; var valueCount = valueCounts.get(value); if (valueCount) { valueCounts.set(value, valueCount + 1); } else { valueCounts.set(value, 1); if (this.adoptsItemChanges && value instanceof EventEmitter) { value.on('change', this._onItemChange, this); } } }, /** * @typesign (value); */ _unregisterValue: function _unregisterValue(value) { var valueCounts = this._valueCounts; var valueCount = valueCounts.get(value); if (valueCount > 1) { valueCounts.set(value, valueCount - 1); } else { valueCounts.delete(value); if (this.adoptsItemChanges && value instanceof EventEmitter) { value.off('change', this._onItemChange, this); } } } }); module.exports = ObservableCollectionMixin; /***/ }, /* 14 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(global) {var Symbol = __webpack_require__(2); var is = __webpack_require__(12); var EventEmitter = __webpack_require__(10); var ObservableCollectionMixin = __webpack_require__(13); var push = Array.prototype.push; var splice = Array.prototype.splice; /** * @typesign (a, b) -> -1|1|0; */ function defaultComparator(a, b) { if (a < b) { return -1; } if (a > b) { return 1; } return 0; } /** * @typesign (list: cellx.ObservableList, items: Array); */ function addRange(list, items) { var listItems = list._items; if (list.sorted) { var comparator = list.comparator; for (var i = 0, l = items.length; i < l; i++) { var item = items[i]; var low = 0; var high = listItems.length; while (low != high) { var mid = (low + high) >> 1; if (comparator(item, listItems[mid]) < 0) { high = mid; } else { low = mid + 1; } } listItems.splice(low, 0, item); list._registerValue(item); } } else { push.apply(listItems, items); for (var j = items.length; j;) { list._registerValue(items[--j]); } } list.length = listItems.length; } /** * @class cellx.ObservableList * @extends {cellx.EventEmitter} * @implements {ObservableCollectionMixin} * * @typesign new (items?: Array|cellx.ObservableList, opts?: { * adoptsItemChanges?: boolean, * comparator?: (a, b) -> int, * sorted?: boolean * }) -> cellx.ObservableList; */ var ObservableList = EventEmitter.extend({ Implements: [ObservableCollectionMixin], constructor: function ObservableList(items, opts) { EventEmitter.call(this); ObservableCollectionMixin.call(this); if (!opts) { opts = {}; } this._items = []; this.length = 0; /** * @type {boolean} */ this.adoptsItemChanges = opts.adoptsItemChanges !== false; /** * @type {?(a, b) -> int} */ this.comparator = null; this.sorted = false; if (opts.sorted || (opts.comparator && opts.sorted !== false)) { this.comparator = opts.comparator || defaultComparator; this.sorted = true; } if (items) { addRange(this, items instanceof ObservableList ? items._items : items); } }, /** * @typesign (index: int, allowedEndIndex?: boolean) -> ?uint; */ _validateIndex: function _validateIndex(index, allowedEndIndex) { if (index === void 0) { return index; } if (index < 0) { index += this.length; if (index < 0) { throw new RangeError('Index out of valid range'); } } else if (index >= (this.length + (allowedEndIndex ? 1 : 0))) { throw new RangeError('Index out of valid range'); } return index; }, /** * @typesign (value) -> boolean; */ contains: function contains(value) { return this._valueCounts.has(value); }, /** * @typesign (value, fromIndex?: int) -> int; */ indexOf: function indexOf(value, fromIndex) { return this._items.indexOf(value, this._validateIndex(fromIndex)); }, /** * @typesign (value, fromIndex?: int) -> int; */ lastIndexOf: function lastIndexOf(value, fromIndex) { return this._items.lastIndexOf(value, fromIndex === void 0 ? -1 : this._validateIndex(fromIndex)); }, /** * @typesign (index: int) -> *; */ get: function get(index) { return this._items[this._validateIndex(index)]; }, /** * @typesign (index?: int, count?: uint) -> Array; */ getRange: function getRange(index, count) { index = this._validateIndex(index || 0, true); var items = this._items; if (count === void 0) { return items.slice(index); } if (index + count > items.length) { throw new RangeError('Sum of "index" and "count" out of valid range'); } return items.slice(index, index + count); }, /** * @typesign (index: int, value) -> cellx.ObservableList; */ set: function set(index, value) { if (this.sorted) { throw new TypeError('Cannot set to sorted list'); } index = this._validateIndex(index); var items = this._items; if (is(items[index], value)) { return this; } this._unregisterValue(items[index]); items[index] = value; this._registerValue(value); this.emit('change'); return this; }, /** * @typesign (index: int, items: Array) -> cellx.ObservableList; */ setRange: function setRange(index, items) { if (this.sorted) { throw new TypeError('Cannot set to sorted list'); } index = this._validateIndex(index); var itemCount = items.length; if (!itemCount) { return this; } if (index + itemCount > this.length) { throw new RangeError('Sum of "index" and "items.length" out of valid range'); } var listItems = this._items; var changed = false; for (var i = index + itemCount; i > index;) { var item = items[--i - index]; if (!is(listItems[i], item)) { this._unregisterValue(listItems[i]); listItems[i] = item; this._registerValue(item); changed = true; } } if (changed) { this.emit('change'); } return this; }, /** * @typesign (item) -> cellx.ObservableList; */ add: function add(item) { this.addRange([item]); return this; }, /** * @typesign (items: Array) -> cellx.ObservableList; */ addRange: function _addRange(items) { if (!items.length) { return this; } addRange(this, items); this.emit('change'); return this; }, /** * @typesign (index: int, item) -> cellx.ObservableList; */ insert: function insert(index, item) { this.insertRange(index, [item]); return this; }, /** * @typesign (index: int, items: Array) -> cellx.ObservableList; */ insertRange: function insertRange(index, items) { if (this.sorted) { throw new TypeError('Cannot insert to sorted list'); } index = this._validateIndex(index, true); var itemCount = items.length; if (!itemCount) { return this; } splice.apply(this._items, [index, 0].concat(items)); for (var i = itemCount; i;) { this._registerValue(items[--i]); } this.length += itemCount; this.emit('change'); return this; }, /** * @typesign (item, fromIndex?: int) -> boolean; */ remove: function remove(item, fromIndex) { var index = this._items.indexOf(item, this._validateIndex(fromIndex)); if (index == -1) { return false; } this._items.splice(index, 1); this._unregisterValue(item); this.length--; this.emit('change'); return true; }, /** * @typesign (item, fromIndex?: int) -> boolean; */ removeAll: function removeAll(item, fromIndex) { var items = this._items; var index = this._validateIndex(fromIndex); var changed = false; while ((index = items.indexOf(item, index)) != -1) { items.splice(index, 1); this._unregisterValue(item); changed = true; } if (!changed) { return false; } this.length = items.length; this.emit('change'); return true; }, /** * @typesign (index: int) -> *; */ removeAt: function removeAt(index) { var removedItem = this._items.splice(this._validateIndex(index), 1)[0]; this._unregisterValue(removedItem); this.length--; this.emit('change'); return removedItem; }, /** * @typesign (index?: int, count?: uint) -> Array; */ removeRange: function removeRange(index, count) { index = this._validateIndex(index || 0, true); var items = this._items; if (count === void 0) { count = items.length - index; } else if (index + count > items.length) { throw new RangeError('Sum of "index" and "count" out of valid range'); } if (!count) { return []; } for (var i = index + count; i > index;) { this._unregisterValue(items[--i]); } var removedItems = items.splice(index, count); this.length -= count; this.emit('change'); return removedItems; }, /** * @typesign () -> cellx.ObservableList; */ clear: function clear() { if (this.length) { if (this.adoptsItemChanges) { this._valueCounts.forEach(function(value) { if (value instanceof EventEmitter) { value.off('change', this._onItemChange, this); } }, this); } this._items.length = 0; this._valueCounts.clear(); this.length = 0; this.emit('change'); } return this; }, /** * @typesign (separator?: string) -> string; */ join: function join(separator) { return this._items.join(separator); }, /** * @typesign ( * cb: (item, index: uint, list: cellx.ObservableList), * context? * ); */ forEach: null, /** * @typesign ( * cb: (item, index: uint, list: cellx.ObservableList) -> *, * context? * ) -> Array; */ map: null, /** * @typesign ( * cb: (item, index: uint, list: cellx.ObservableList) -> ?boolean, * context? * ) -> Array; */ filter: null, /** * @typesign ( * cb: (item, index: uint, list: cellx.ObservableList) -> ?boolean, * context? * ) -> *; */ find: function(cb, context) { if (context == null) { context = this; } var items = this._items; for (var i = 0, l = items.length; i < l; i++) { var item = items[i]; if (cb.call(context, item, i, this)) { return item; } } }, /** * @typesign ( * cb: (item, index: uint, list: cellx.ObservableList) -> ?boolean, * context? * ) -> int; */ findIndex: function(cb, context) { if (context == null) { context = this; } var items = this._items; for (var i = 0, l = items.length; i < l; i++) { var item = items[i]; if (cb.call(context, item, i, this)) { return i; } } return -1; }, /** * @typesign ( * cb: (item, index: uint, list: cellx.ObservableList) -> ?boolean, * context? * ) -> boolean; */ every: null, /** * @typesign ( * cb: (item, index: uint, list: cellx.ObservableList) -> ?boolean, * context? * ) -> boolean; */ some: null, /** * @typesign ( * cb: (accumulator, item, index: uint, list: cellx.ObservableList) -> *, * initialValue? * ) -> *; */ reduce: null, /** * @typesign ( * cb: (accumulator, item, index: uint, list: cellx.ObservableList) -> *, * initialValue? * ) -> *; */ reduceRight: null, /** * @typesign () -> cellx.ObservableList; */ clone: function clone() { return new this.constructor(this, { adoptsItemChanges: this.adoptsItemChanges, comparator: this.comparator, sorted: this.sorted }); }, /** * @typesign () -> Array; */ toArray: function toArray() { return this._items.slice(); }, /** * @typesign () -> string; */ toString: function toString() { return this._items.join(); } }); ['forEach', 'map', 'filter', 'every', 'some'].forEach(function(name) { ObservableList.prototype[name] = function(cb, context) { context = arguments.length >= 2 ? context : global; return this._items[name](function(item, index) { return cb.call(context, item, index, this); }, this); }; }); ['reduce', 'reduceRight'].forEach(function(name) { ObservableList.prototype[name] = function(cb, initialValue) { var list = this; var items = this._items; var wrappedCallback = function(accumulator, item, index) { return cb(accumulator, item, index, list); }; return arguments.length >= 2 ? items[name](wrappedCallback, initialValue) : items[name](wrappedCallback); }; }); [ ['keys', function keys(index) { return index; }], ['values', function values(index, item) { return item; }], ['entries', function entries(index, item) { return [index, item]; }] ].forEach(function(settings) { var getStepValue = settings[1]; ObservableList.prototype[settings[0]] = function() { var items = this._items; var index = 0; var done = false; return { next: function() { if (!done) { if (index < items.length) { return { value: getStepValue(index, items[index++]), done: false }; } done = true; } return { value: void 0, done: true }; } }; }; }); ObservableList.prototype[Symbol.iterator] = ObservableList.prototype.values; module.exports = ObservableList; /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()))) /***/ }, /* 15 */ /***/ function(module, exports, __webpack_require__) { var is = __webpack_require__(12); var nextTick = __webpack_require__(8); var EventEmitter = __webpack_require__(10); var slice = Array.prototype.slice; var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || 0x1fffffffffffff; var KEY_INNER = EventEmitter.KEY_INNER; var pushingIndexCounter = 0; var releasePlan = []; var releasePlanIndex = MAX_SAFE_INTEGER; var releasePlanToIndex = -1; var releasePlanned = false; var currentlyRelease = false; var releaseVersion = 1; function release() { if (!releasePlanned) { return; } releasePlanned = false; currentlyRelease = true; var queue = releasePlan[releasePlanIndex]; for (;;) { var cell = (queue || []).shift(); if (!cell) { queue = releasePlan[++releasePlanIndex]; continue; } var oldReleasePlanIndex = releasePlanIndex; var level = cell._level; var changeEvent = cell._changeEvent; if (!changeEvent) { if (level > releasePlanIndex || cell._levelInRelease == -1) { if (!queue.length) { if (++releasePlanIndex > releasePlanToIndex) { break; } queue = releasePlan[releasePlanIndex]; } continue; } cell.pull(); level = cell._level; changeEvent = cell._changeEvent; if (releasePlanIndex == oldReleasePlanIndex) { if (level > releasePlanIndex) { if (!queue.length) { queue = releasePlan[++releasePlanIndex]; } continue; } } else { if (changeEvent) { queue.unshift(cell); } else if (level <= oldReleasePlanIndex) { cell._levelInRelease = -1; } queue = releasePlan[releasePlanIndex]; continue; } } cell._levelInRelease = -1; if (changeEvent) { cell._fixedValue = cell._value; cell._changeEvent = null; if (cell._events.change) { cell._handleEvent(changeEvent); } var pushingIndex = cell._pushingIndex; var slaves = cell._slaves; for (var i = 0, l = slaves.length; i < l; i++) { var slave = slaves[i]; if (slave._level <= level) { slave._level = level + 1; } if (pushingIndex > slave._pushingIndex) { slave._pushingIndex = pushingIndex; slave._changeEvent = null; slave._addToRelease(); } } } if (releasePlanIndex == oldReleasePlanIndex) { if (queue.length) { continue; } if (++releasePlanIndex > releasePlanToIndex) { break; } } queue = releasePlan[releasePlanIndex]; } releasePlanIndex = MAX_SAFE_INTEGER; releasePlanToIndex = -1; currentlyRelease = false; releaseVersion++; } var currentCell = null; var error = { original: null }; /** * @typesign (value); */ function defaultPut(value) { this.push(value); } /** * @class cellx.Cell * @extends {cellx.EventEmitter} * * @example * var a = new Cell(1); * var b = new Cell(2); * var c = new Cell(function() { * return a.get() + b.get(); * }); * * c.on('change', function() { * console.log('c = ' + c.get()); * }); * * console.log(c.get()); * // => 3 * * a.set(5); * b.set(10); * // => 'c = 15' * * @typesign new (value?, opts?: { * debugKey?: string, * owner?: Object, * validate?: (value, oldValue), * onChange?: (evt: cellx~Event) -> ?boolean, * onError?: (evt: cellx~Event) -> ?boolean * }) -> cellx.Cell; * * @typesign new (pull: (push: (value), fail: (err), oldValue) -> *, opts?: { * debugKey?: string, * owner?: Object, * validate?: (value, oldValue), * put?: (value, push: (value), fail: (err), oldValue), * reap?: (), * onChange?: (evt: cellx~Event) -> ?boolean, * onError?: (evt: cellx~Event) -> ?boolean * }) -> cellx.Cell; */ var Cell = EventEmitter.extend({ constructor: function Cell(value, opts) { EventEmitter.call(this); if (!opts) { opts = {}; } var cell = this; this.debugKey = opts.debugKey || void 0; this.owner = opts.owner || this; this._pull = typeof value == 'function' ? value : null; this._validate = opts.validate || null; this._put = opts.put || defaultPut; var push = this.push; var fail = this.fail; this.push = function(value) { push.call(cell, value); }; this.fail = function(err) { fail.call(cell, err); }; this._onFulfilled = this._onRejected = null; this._reap = opts.reap || null; if (this._pull) { this.initialValue = this._fixedValue = this._value = void 0; } else { if (this._validate) { this._validate.call(this.owner, value, void 0); } this.initialValue = this._fixedValue = this._value = value; if (value instanceof EventEmitter) { value.on('change', this._onValueChange, this); } } this._error = null; this._errorCell = null; this._pushingIndex = 0; this._version = 0; this._inited = false; this._currentlyPulls = false; this._active = false; this._hasFollowers = false; /** * Ведущие ячейки. * @type {?Array<cellx.Cell>} */ this._masters = null; /** * Ведомые ячейки. * @type {Array<cellx.Cell>} */ this._slaves = []; this._level = 0; this._levelInRelease = -1; this._pending = this._fulfilled = this._rejected = false; this._changeEvent = null; this._canCancelChange = true; this._lastErrorEvent = null; if (opts.onChange) { this.on('change', opts.onChange); } if (opts.onError) { this.on('error', opts.onError); } }, /** * @override */ on: function on(type, listener, context) { if (releasePlanned) { release(); } this._activate(); EventEmitter.prototype.on.call(this, type, listener, context); this._hasFollowers = true; return this; }, /** * @override */ off: function off(type, listener, context) { if (releasePlanned) { release(); } EventEmitter.prototype.off.call(this, type, listener, context); if (!this._slaves.length && !this._events.change && !this._events.error) { this._hasFollowers = false; this._deactivate(); } return this; }, /** * @override */ _on: function _on(type, listener, context) { EventEmitter.prototype._on.call(this, type, listener, context == null ? this.owner : context); }, /** * @override */ _off: function _off(type, listener, context) { EventEmitter.prototype._off.call(this, type, listener, context == null ? this.owner : context); }, /** * @typesign ( * listener: (evt: cellx~Event) -> ?boolean, * context? * ) -> cellx.Cell; */ addChangeListener: function addChangeListener(listener, context) { return this.on('change', listener, context); }, /** * @typesign ( * listener: (evt: cellx~Event) -> ?boolean, * context? * ) -> cellx.Cell; */ removeChangeListener: function removeChangeListener(listener, context) { return this.off('change', listener, context); }, /** * @typesign ( * listener: (evt: cellx~Event) -> ?boolean, * context? * ) -> cellx.Cell; */ addErrorListener: function addErrorListener(listener, context) { return this.on('error', listener, context); }, /** * @typesign ( * listener: (evt: cellx~Event) -> ?boolean, * context? * ) -> cellx.Cell; */ removeErrorListener: function removeErrorListener(listener, context) { return this.off('error', listener, context); }, /** * @typesign ( * listener: (err: ?Error, evt: cellx~Event) -> ?boolean, * context? * ) -> cellx.Cell; */ subscribe: function subscribe(listener, context) { function wrapper(evt) { return listener.call(this, evt.error || null, evt); } wrapper[KEY_INNER] = listener; return this .on('change', wrapper, context) .on('error', wrapper, context); }, /** * @typesign ( * listener: (err: ?Error, evt: cellx~Event) -> ?boolean, * context? * ) -> cellx.Cell; */ unsubscribe: function unsubscribe(listener, context) { return this .off('change', listener, context) .off('error', listener, context); }, /** * @typesign (slave: cellx.Cell); */ _registerSlave: function _registerSlave(slave) { this._activate(); this._slaves.push(slave); this._hasFollowers = true; }, /** * @typesign (slave: cellx.Cell); */ _unregisterSlave: function _unregisterSlave(slave) { this._slaves.splice(this._slaves.indexOf(slave), 1); if (!this._slaves.length && !this._events.change && !this._events.error) { this._hasFollowers = false; this._deactivate(); } }, /** * @typesign (); */ _activate: function _activate() { if (!this._pull || this._active || this._inited && !this._masters) { return; } if (this._version < releaseVersion) { var value = this._tryPull(); if (value === error) { this._fail(error.original, true); } else { this._push(value, true); } } var masters = this._masters; if (masters) { for (var i = masters.length; i;) { masters[--i]._registerSlave(this); } this._active = true; } }, /** * @typesign (); */ _deactivate: function _deactivate() { if (!this._active) { return; } var masters = this._masters; for (var i = masters.length; i;) { masters[--i]._unregisterSlave(this); } this._active = false; if (this._reap) { this._reap.call(this.owner); } }, /** * @typesign (); */ _addToRelease: function _addToRelease() { var level = this._level; if (level <= this._levelInRelease) { return; } (releasePlan[level] || (releasePlan[level] = [])).push(this); if (releasePlanIndex > level) { releasePlanIndex = level; } if (releasePlanToIndex < level) { releasePlanToIndex = level; } this._levelInRelease = level; if (!releasePlanned && !currentlyRelease) { releasePlanned = true; nextTick(release); } }, /** * @typesign (evt: cellx~Event); */ _onValueChange: function _onValueChange(evt) { if (this._changeEvent) { evt.prev = this._changeEvent; this._changeEvent = evt; if (this._value === this._fixedValue) { this._canCancelChange = false; } } else { evt.prev = null; this._changeEvent = evt; this._canCancelChange = false; this._addToRelease(); } }, /** * @typesign () -> cellx.Cell; */ pull: function pull() { if (!this._pull) { return this; } if (releasePlanned) { release(); } var hasFollowers = this._hasFollowers; var oldMasters; var oldLevel; if (hasFollowers) { oldMasters = this._masters || []; oldLevel = this._level; } this._pending = true; this._fulfilled = this._rejected = false; var value = this._tryPull(); if (hasFollowers) { var masters = this._masters || []; var masterCount = masters.length; var notFoundMasterCount = 0; for (var i = masterCount; i;) { var master = masters[--i]; if (oldMasters.indexOf(master) == -1) { master._registerSlave(this); notFoundMasterCount++; } } if (masterCount - notFoundMasterCount < oldMasters.length) { for (var j = oldMasters.length; j;) { var oldMaster = oldMasters[--j]; if (masters.indexOf(oldMaster) == -1) { oldMaster._unregisterSlave(this); } } } this._active = !!masterCount; if (currentlyRelease && this._level > oldLevel) { this._addToRelease(); return this; } } if (value === error) { this._fail(error.original, true); } else { this._push(value, true); } return this; }, /** * @typesign () -> *; */ _tryPull: function _tryPull() { if (this._currentlyPulls) { throw new TypeError('Circular pulling detected'); } var prevCell = currentCell; currentCell = this; this._currentlyPulls = true; this._masters = null; this._level = 0; try { var value = this._pull.call(this.owner, this.push, this.fail, this._value); if (this._validate) { this._validate.call(this.owner, value); } return value; } catch (err) { error.original = err; return error; } finally { currentCell = prevCell; this._version = releaseVersion + currentlyRelease; this._inited = true; this._currentlyPulls = false; } }, /** * @typesign () -> *; */ get: function get() { if (releasePlanned && this._pull) { release(); } if (this._pull && !this._active && this._version < releaseVersion && (!this._inited || this._masters)) { var value = this._tryPull(); if (this._hasFollowers) { var masters = this._masters; if (masters) { for (var i = masters.length; i;) { masters[--i]._registerSlave(this); } this._active = true; } } if (value === error) { this._fail(error.original, true); } else { this._push(value, true); } } if (currentCell) { var currentCellMasters = currentCell._masters; var level = this._level; if (currentCellMasters) { if (currentCellMasters.indexOf(this) == -1) { currentCellMasters.push(this); if (currentCell._level <= level) { currentCell._level = level + 1; } } } else { currentCell._masters = [this]; currentCell._level = level + 1; } } return this._value; }, /** * @typesign (value) -> cellx.Cell; */ set: function set(value) { var oldValue = this._value; if (this._validate) { this._validate.call(this.owner, value, oldValue); } this._put(value, this.push, this.fail, oldValue); return this; }, /** * @typesign (value) -> cellx.Cell; */ push: function push(value) { this._push(value, false); return this; }, /** * @typesign (value, afterPull: boolean = false); */ _push: function _push(value, afterPull) { if (!afterPull && this._validate) { this._validate.call(this.owner, value, this._value); } this._setError(null); if (!afterPull) { this._pushingIndex = ++pushingIndexCounter; } var oldValue = this._value; if (is(value, oldValue)) { return; } this._value = value; if (oldValue instanceof EventEmitter) { oldValue.off('change', this._onValueChange, this); } if (value instanceof EventEmitter) { value.on('change', this._onValueChange, this); } if (this._hasFollowers) { if (this._changeEvent) { if (is(value, this._fixedValue) && this._canCancelChange) { this._levelInRelease = -1; this._changeEvent = null; } else { this._changeEvent = { target: this, type: 'change', oldValue: oldValue, value: value, prev: this._changeEvent }; } } else { this._changeEvent = { target: this, type: 'change', oldValue: oldValue, value: value, prev: null }; this._canCancelChange = true; this._addToRelease(); } } else { if (!currentlyRelease && !afterPull) { releaseVersion++; } this._fixedValue = value; } if (!afterPull && this._pending) { this._pending = false; this._fulfilled = true; if (this._onFulfilled) { this._onFulfilled(value); } } }, /** * @typesign (err) -> cellx.Cell; */ fail: function fail(err) { this._fail(err, false); return this; }, /** * @typesign (err, afterPull: boolean = false); */ _fail: function _fail(err, afterPull) { this._logError(err); if (!(err instanceof Error)) { err = new Error(String(err)); } if (!afterPull && this._pending) { this._pending = false; this._rejected = true; if (this._onRejected) { this._onRejected(err); } } this._handleErrorEvent({ type: 'error', error: err }); }, /** * @typesign (evt: cellx~Event{ error: Error }); */ _handleErrorEvent: function _handleErrorEvent(evt) { if (this._lastErrorEvent === evt) { return; } this._setError(evt.error); this._lastErrorEvent = evt; this._handleEvent(evt); var slaves = this._slaves; for (var i = 0, l = slaves.length; i < l; i++) { slaves[i]._handleErrorEvent(evt); } }, /** * @typesign () -> ?Error; */ getError: function getError() { return (this._errorCell || (this._errorCell = new Cell(this._error))).get(); }, /** * @typesign (err: ?Error); */ _setError: function _setError(err) { if (this._error === err) { return; } this._error = err; if (this._errorCell) { this._errorCell.set(err); } if (!err) { var slaves = this._slaves; for (var i = 0, l = slaves.length; i < l; i++) { slaves[i]._setError(err); } } }, /** * @typesign (onFulfilled?: (value) -> *, onRejected?: (err) -> *) -> Promise; */ then: function then(onFulfilled, onRejected) { if (releasePlanned) { release(); } if (this._fulfilled) { return Promise.resolve(this._value).then(onFulfilled); } if (this._rejected) { return Promise.reject(this._error).catch(onRejected); } var cell = this; var promise = new Promise(function(resolve, reject) { cell._onFulfilled = function onFulfilled(value) { cell._onFulfilled = cell._onRejected = null; resolve(value); }; cell._onRejected = function onRejected(err) { cell._onFulfilled = cell._onRejected = null; reject(err); }; }).then(onFulfilled, onRejected); if (!this._pending) { this.pull(); } return promise; }, /** * @typesign (onRejected: (err) -> *) -> Promise; */ catch: function _catch(onRejected) { return this.then(null, onRejected); }, /** * @override */ _logError: function _logError() { var msg = slice.call(arguments); if (this.debugKey) { msg.unshift('[' + this.debugKey + ']'); } EventEmitter.prototype._logError.apply(this, msg); }, /** * @typesign () -> cellx.Cell; */ dispose: function dispose() { if (releasePlanned) { release(); } this._dispose(); return this; }, /** * @typesign (); */ _dispose: function _dispose() { var slaves = this._slaves; for (var i = 0, l = slaves.length; i < l; i++) { slaves[i]._dispose(); } this.off(); } }); module.exports = Cell; /***/ } /******/ ]) }); ;
/* @preserve * The MIT License (MIT) * * Copyright (c) 2013-2015 Petka Antonov * * 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. * */ /** * bluebird build version 3.3.3 * Features enabled: core, race, call_get, generators, map, nodeify, promisify, props, reduce, settle, some, using, timers, filter, any, each */ !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.Promise=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 _dereq_=="function"&&_dereq_;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 _dereq_=="function"&&_dereq_;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise) { var SomePromiseArray = Promise._SomePromiseArray; function any(promises) { var ret = new SomePromiseArray(promises); var promise = ret.promise(); ret.setHowMany(1); ret.setUnwrap(); ret.init(); return promise; } Promise.any = function (promises) { return any(promises); }; Promise.prototype.any = function () { return any(this); }; }; },{}],2:[function(_dereq_,module,exports){ "use strict"; var firstLineError; try {throw new Error(); } catch (e) {firstLineError = e;} var schedule = _dereq_("./schedule"); var Queue = _dereq_("./queue"); var util = _dereq_("./util"); function Async() { this._isTickUsed = false; this._lateQueue = new Queue(16); this._normalQueue = new Queue(16); this._haveDrainedQueues = false; this._trampolineEnabled = true; var self = this; this.drainQueues = function () { self._drainQueues(); }; this._schedule = schedule; } Async.prototype.enableTrampoline = function() { this._trampolineEnabled = true; }; Async.prototype.disableTrampolineIfNecessary = function() { if (util.hasDevTools) { this._trampolineEnabled = false; } }; Async.prototype.haveItemsQueued = function () { return this._isTickUsed || this._haveDrainedQueues; }; Async.prototype.fatalError = function(e, isNode) { if (isNode) { process.stderr.write("Fatal " + (e instanceof Error ? e.stack : e) + "\n"); process.exit(2); } else { this.throwLater(e); } }; Async.prototype.throwLater = function(fn, arg) { if (arguments.length === 1) { arg = fn; fn = function () { throw arg; }; } if (typeof setTimeout !== "undefined") { setTimeout(function() { fn(arg); }, 0); } else try { this._schedule(function() { fn(arg); }); } catch (e) { throw new Error("No async scheduler available\u000a\u000a See http://goo.gl/MqrFmX\u000a"); } }; function AsyncInvokeLater(fn, receiver, arg) { this._lateQueue.push(fn, receiver, arg); this._queueTick(); } function AsyncInvoke(fn, receiver, arg) { this._normalQueue.push(fn, receiver, arg); this._queueTick(); } function AsyncSettlePromises(promise) { this._normalQueue._pushOne(promise); this._queueTick(); } if (!util.hasDevTools) { Async.prototype.invokeLater = AsyncInvokeLater; Async.prototype.invoke = AsyncInvoke; Async.prototype.settlePromises = AsyncSettlePromises; } else { Async.prototype.invokeLater = function (fn, receiver, arg) { if (this._trampolineEnabled) { AsyncInvokeLater.call(this, fn, receiver, arg); } else { this._schedule(function() { setTimeout(function() { fn.call(receiver, arg); }, 100); }); } }; Async.prototype.invoke = function (fn, receiver, arg) { if (this._trampolineEnabled) { AsyncInvoke.call(this, fn, receiver, arg); } else { this._schedule(function() { fn.call(receiver, arg); }); } }; Async.prototype.settlePromises = function(promise) { if (this._trampolineEnabled) { AsyncSettlePromises.call(this, promise); } else { this._schedule(function() { promise._settlePromises(); }); } }; } Async.prototype.invokeFirst = function (fn, receiver, arg) { this._normalQueue.unshift(fn, receiver, arg); this._queueTick(); }; Async.prototype._drainQueue = function(queue) { while (queue.length() > 0) { var fn = queue.shift(); if (typeof fn !== "function") { fn._settlePromises(); continue; } var receiver = queue.shift(); var arg = queue.shift(); fn.call(receiver, arg); } }; Async.prototype._drainQueues = function () { this._drainQueue(this._normalQueue); this._reset(); this._haveDrainedQueues = true; this._drainQueue(this._lateQueue); }; Async.prototype._queueTick = function () { if (!this._isTickUsed) { this._isTickUsed = true; this._schedule(this.drainQueues); } }; Async.prototype._reset = function () { this._isTickUsed = false; }; module.exports = Async; module.exports.firstLineError = firstLineError; },{"./queue":26,"./schedule":29,"./util":36}],3:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise, INTERNAL, tryConvertToPromise, debug) { var calledBind = false; var rejectThis = function(_, e) { this._reject(e); }; var targetRejected = function(e, context) { context.promiseRejectionQueued = true; context.bindingPromise._then(rejectThis, rejectThis, null, this, e); }; var bindingResolved = function(thisArg, context) { if (((this._bitField & 50397184) === 0)) { this._resolveCallback(context.target); } }; var bindingRejected = function(e, context) { if (!context.promiseRejectionQueued) this._reject(e); }; Promise.prototype.bind = function (thisArg) { if (!calledBind) { calledBind = true; Promise.prototype._propagateFrom = debug.propagateFromFunction(); Promise.prototype._boundValue = debug.boundValueFunction(); } var maybePromise = tryConvertToPromise(thisArg); var ret = new Promise(INTERNAL); ret._propagateFrom(this, 1); var target = this._target(); ret._setBoundTo(maybePromise); if (maybePromise instanceof Promise) { var context = { promiseRejectionQueued: false, promise: ret, target: target, bindingPromise: maybePromise }; target._then(INTERNAL, targetRejected, undefined, ret, context); maybePromise._then( bindingResolved, bindingRejected, undefined, ret, context); ret._setOnCancel(maybePromise); } else { ret._resolveCallback(target); } return ret; }; Promise.prototype._setBoundTo = function (obj) { if (obj !== undefined) { this._bitField = this._bitField | 2097152; this._boundTo = obj; } else { this._bitField = this._bitField & (~2097152); } }; Promise.prototype._isBound = function () { return (this._bitField & 2097152) === 2097152; }; Promise.bind = function (thisArg, value) { return Promise.resolve(value).bind(thisArg); }; }; },{}],4:[function(_dereq_,module,exports){ "use strict"; var old; if (typeof Promise !== "undefined") old = Promise; function noConflict() { try { if (Promise === bluebird) Promise = old; } catch (e) {} return bluebird; } var bluebird = _dereq_("./promise")(); bluebird.noConflict = noConflict; module.exports = bluebird; },{"./promise":22}],5:[function(_dereq_,module,exports){ "use strict"; var cr = Object.create; if (cr) { var callerCache = cr(null); var getterCache = cr(null); callerCache[" size"] = getterCache[" size"] = 0; } module.exports = function(Promise) { var util = _dereq_("./util"); var canEvaluate = util.canEvaluate; var isIdentifier = util.isIdentifier; var getMethodCaller; var getGetter; if (!true) { var makeMethodCaller = function (methodName) { return new Function("ensureMethod", " \n\ return function(obj) { \n\ 'use strict' \n\ var len = this.length; \n\ ensureMethod(obj, 'methodName'); \n\ switch(len) { \n\ case 1: return obj.methodName(this[0]); \n\ case 2: return obj.methodName(this[0], this[1]); \n\ case 3: return obj.methodName(this[0], this[1], this[2]); \n\ case 0: return obj.methodName(); \n\ default: \n\ return obj.methodName.apply(obj, this); \n\ } \n\ }; \n\ ".replace(/methodName/g, methodName))(ensureMethod); }; var makeGetter = function (propertyName) { return new Function("obj", " \n\ 'use strict'; \n\ return obj.propertyName; \n\ ".replace("propertyName", propertyName)); }; var getCompiled = function(name, compiler, cache) { var ret = cache[name]; if (typeof ret !== "function") { if (!isIdentifier(name)) { return null; } ret = compiler(name); cache[name] = ret; cache[" size"]++; if (cache[" size"] > 512) { var keys = Object.keys(cache); for (var i = 0; i < 256; ++i) delete cache[keys[i]]; cache[" size"] = keys.length - 256; } } return ret; }; getMethodCaller = function(name) { return getCompiled(name, makeMethodCaller, callerCache); }; getGetter = function(name) { return getCompiled(name, makeGetter, getterCache); }; } function ensureMethod(obj, methodName) { var fn; if (obj != null) fn = obj[methodName]; if (typeof fn !== "function") { var message = "Object " + util.classString(obj) + " has no method '" + util.toString(methodName) + "'"; throw new Promise.TypeError(message); } return fn; } function caller(obj) { var methodName = this.pop(); var fn = ensureMethod(obj, methodName); return fn.apply(obj, this); } Promise.prototype.call = function (methodName) { var args = [].slice.call(arguments, 1);; if (!true) { if (canEvaluate) { var maybeCaller = getMethodCaller(methodName); if (maybeCaller !== null) { return this._then( maybeCaller, undefined, undefined, args, undefined); } } } args.push(methodName); return this._then(caller, undefined, undefined, args, undefined); }; function namedGetter(obj) { return obj[this]; } function indexedGetter(obj) { var index = +this; if (index < 0) index = Math.max(0, index + obj.length); return obj[index]; } Promise.prototype.get = function (propertyName) { var isIndex = (typeof propertyName === "number"); var getter; if (!isIndex) { if (canEvaluate) { var maybeGetter = getGetter(propertyName); getter = maybeGetter !== null ? maybeGetter : namedGetter; } else { getter = namedGetter; } } else { getter = indexedGetter; } return this._then(getter, undefined, undefined, propertyName, undefined); }; }; },{"./util":36}],6:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise, PromiseArray, apiRejection, debug) { var util = _dereq_("./util"); var tryCatch = util.tryCatch; var errorObj = util.errorObj; var async = Promise._async; Promise.prototype["break"] = Promise.prototype.cancel = function() { if (!debug.cancellation()) return this._warn("cancellation is disabled"); var promise = this; var child = promise; while (promise.isCancellable()) { if (!promise._cancelBy(child)) { if (child._isFollowing()) { child._followee().cancel(); } else { child._cancelBranched(); } break; } var parent = promise._cancellationParent; if (parent == null || !parent.isCancellable()) { if (promise._isFollowing()) { promise._followee().cancel(); } else { promise._cancelBranched(); } break; } else { if (promise._isFollowing()) promise._followee().cancel(); child = promise; promise = parent; } } }; Promise.prototype._branchHasCancelled = function() { this._branchesRemainingToCancel--; }; Promise.prototype._enoughBranchesHaveCancelled = function() { return this._branchesRemainingToCancel === undefined || this._branchesRemainingToCancel <= 0; }; Promise.prototype._cancelBy = function(canceller) { if (canceller === this) { this._branchesRemainingToCancel = 0; this._invokeOnCancel(); return true; } else { this._branchHasCancelled(); if (this._enoughBranchesHaveCancelled()) { this._invokeOnCancel(); return true; } } return false; }; Promise.prototype._cancelBranched = function() { if (this._enoughBranchesHaveCancelled()) { this._cancel(); } }; Promise.prototype._cancel = function() { if (!this.isCancellable()) return; this._setCancelled(); async.invoke(this._cancelPromises, this, undefined); }; Promise.prototype._cancelPromises = function() { if (this._length() > 0) this._settlePromises(); }; Promise.prototype._unsetOnCancel = function() { this._onCancelField = undefined; }; Promise.prototype.isCancellable = function() { return this.isPending() && !this.isCancelled(); }; Promise.prototype._doInvokeOnCancel = function(onCancelCallback, internalOnly) { if (util.isArray(onCancelCallback)) { for (var i = 0; i < onCancelCallback.length; ++i) { this._doInvokeOnCancel(onCancelCallback[i], internalOnly); } } else if (onCancelCallback !== undefined) { if (typeof onCancelCallback === "function") { if (!internalOnly) { var e = tryCatch(onCancelCallback).call(this._boundValue()); if (e === errorObj) { this._attachExtraTrace(e.e); async.throwLater(e.e); } } } else { onCancelCallback._resultCancelled(this); } } }; Promise.prototype._invokeOnCancel = function() { var onCancelCallback = this._onCancel(); this._unsetOnCancel(); async.invoke(this._doInvokeOnCancel, this, onCancelCallback); }; Promise.prototype._invokeInternalOnCancel = function() { if (this.isCancellable()) { this._doInvokeOnCancel(this._onCancel(), true); this._unsetOnCancel(); } }; Promise.prototype._resultCancelled = function() { this.cancel(); }; }; },{"./util":36}],7:[function(_dereq_,module,exports){ "use strict"; module.exports = function(NEXT_FILTER) { var util = _dereq_("./util"); var getKeys = _dereq_("./es5").keys; var tryCatch = util.tryCatch; var errorObj = util.errorObj; function catchFilter(instances, cb, promise) { return function(e) { var boundTo = promise._boundValue(); predicateLoop: for (var i = 0; i < instances.length; ++i) { var item = instances[i]; if (item === Error || (item != null && item.prototype instanceof Error)) { if (e instanceof item) { return tryCatch(cb).call(boundTo, e); } } else if (typeof item === "function") { var matchesPredicate = tryCatch(item).call(boundTo, e); if (matchesPredicate === errorObj) { return matchesPredicate; } else if (matchesPredicate) { return tryCatch(cb).call(boundTo, e); } } else if (util.isObject(e)) { var keys = getKeys(item); for (var j = 0; j < keys.length; ++j) { var key = keys[j]; if (item[key] != e[key]) { continue predicateLoop; } } return tryCatch(cb).call(boundTo, e); } } return NEXT_FILTER; }; } return catchFilter; }; },{"./es5":13,"./util":36}],8:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise) { var longStackTraces = false; var contextStack = []; Promise.prototype._promiseCreated = function() {}; Promise.prototype._pushContext = function() {}; Promise.prototype._popContext = function() {return null;}; Promise._peekContext = Promise.prototype._peekContext = function() {}; function Context() { this._trace = new Context.CapturedTrace(peekContext()); } Context.prototype._pushContext = function () { if (this._trace !== undefined) { this._trace._promiseCreated = null; contextStack.push(this._trace); } }; Context.prototype._popContext = function () { if (this._trace !== undefined) { var trace = contextStack.pop(); var ret = trace._promiseCreated; trace._promiseCreated = null; return ret; } return null; }; function createContext() { if (longStackTraces) return new Context(); } function peekContext() { var lastIndex = contextStack.length - 1; if (lastIndex >= 0) { return contextStack[lastIndex]; } return undefined; } Context.CapturedTrace = null; Context.create = createContext; Context.deactivateLongStackTraces = function() {}; Context.activateLongStackTraces = function() { var Promise_pushContext = Promise.prototype._pushContext; var Promise_popContext = Promise.prototype._popContext; var Promise_PeekContext = Promise._peekContext; var Promise_peekContext = Promise.prototype._peekContext; var Promise_promiseCreated = Promise.prototype._promiseCreated; Context.deactivateLongStackTraces = function() { Promise.prototype._pushContext = Promise_pushContext; Promise.prototype._popContext = Promise_popContext; Promise._peekContext = Promise_PeekContext; Promise.prototype._peekContext = Promise_peekContext; Promise.prototype._promiseCreated = Promise_promiseCreated; longStackTraces = false; }; longStackTraces = true; Promise.prototype._pushContext = Context.prototype._pushContext; Promise.prototype._popContext = Context.prototype._popContext; Promise._peekContext = Promise.prototype._peekContext = peekContext; Promise.prototype._promiseCreated = function() { var ctx = this._peekContext(); if (ctx && ctx._promiseCreated == null) ctx._promiseCreated = this; }; }; return Context; }; },{}],9:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise, Context) { var getDomain = Promise._getDomain; var async = Promise._async; var Warning = _dereq_("./errors").Warning; var util = _dereq_("./util"); var canAttachTrace = util.canAttachTrace; var unhandledRejectionHandled; var possiblyUnhandledRejection; var bluebirdFramePattern = /[\\\/]bluebird[\\\/]js[\\\/](release|debug|instrumented)/; var stackFramePattern = null; var formatStack = null; var indentStackFrames = false; var printWarning; var debugging = !!(util.env("BLUEBIRD_DEBUG") != 0 && (true || util.env("BLUEBIRD_DEBUG") || util.env("NODE_ENV") === "development")); var warnings = !!(util.env("BLUEBIRD_WARNINGS") != 0 && (debugging || util.env("BLUEBIRD_WARNINGS"))); var longStackTraces = !!(util.env("BLUEBIRD_LONG_STACK_TRACES") != 0 && (debugging || util.env("BLUEBIRD_LONG_STACK_TRACES"))); var wForgottenReturn = util.env("BLUEBIRD_W_FORGOTTEN_RETURN") != 0 && (warnings || !!util.env("BLUEBIRD_W_FORGOTTEN_RETURN")); Promise.prototype.suppressUnhandledRejections = function() { var target = this._target(); target._bitField = ((target._bitField & (~1048576)) | 524288); }; Promise.prototype._ensurePossibleRejectionHandled = function () { if ((this._bitField & 524288) !== 0) return; this._setRejectionIsUnhandled(); async.invokeLater(this._notifyUnhandledRejection, this, undefined); }; Promise.prototype._notifyUnhandledRejectionIsHandled = function () { fireRejectionEvent("rejectionHandled", unhandledRejectionHandled, undefined, this); }; Promise.prototype._setReturnedNonUndefined = function() { this._bitField = this._bitField | 268435456; }; Promise.prototype._returnedNonUndefined = function() { return (this._bitField & 268435456) !== 0; }; Promise.prototype._notifyUnhandledRejection = function () { if (this._isRejectionUnhandled()) { var reason = this._settledValue(); this._setUnhandledRejectionIsNotified(); fireRejectionEvent("unhandledRejection", possiblyUnhandledRejection, reason, this); } }; Promise.prototype._setUnhandledRejectionIsNotified = function () { this._bitField = this._bitField | 262144; }; Promise.prototype._unsetUnhandledRejectionIsNotified = function () { this._bitField = this._bitField & (~262144); }; Promise.prototype._isUnhandledRejectionNotified = function () { return (this._bitField & 262144) > 0; }; Promise.prototype._setRejectionIsUnhandled = function () { this._bitField = this._bitField | 1048576; }; Promise.prototype._unsetRejectionIsUnhandled = function () { this._bitField = this._bitField & (~1048576); if (this._isUnhandledRejectionNotified()) { this._unsetUnhandledRejectionIsNotified(); this._notifyUnhandledRejectionIsHandled(); } }; Promise.prototype._isRejectionUnhandled = function () { return (this._bitField & 1048576) > 0; }; Promise.prototype._warn = function(message, shouldUseOwnTrace, promise) { return warn(message, shouldUseOwnTrace, promise || this); }; Promise.onPossiblyUnhandledRejection = function (fn) { var domain = getDomain(); possiblyUnhandledRejection = typeof fn === "function" ? (domain === null ? fn : domain.bind(fn)) : undefined; }; Promise.onUnhandledRejectionHandled = function (fn) { var domain = getDomain(); unhandledRejectionHandled = typeof fn === "function" ? (domain === null ? fn : domain.bind(fn)) : undefined; }; var disableLongStackTraces = function() {}; Promise.longStackTraces = function () { if (async.haveItemsQueued() && !config.longStackTraces) { throw new Error("cannot enable long stack traces after promises have been created\u000a\u000a See http://goo.gl/MqrFmX\u000a"); } if (!config.longStackTraces && longStackTracesIsSupported()) { var Promise_captureStackTrace = Promise.prototype._captureStackTrace; var Promise_attachExtraTrace = Promise.prototype._attachExtraTrace; config.longStackTraces = true; disableLongStackTraces = function() { if (async.haveItemsQueued() && !config.longStackTraces) { throw new Error("cannot enable long stack traces after promises have been created\u000a\u000a See http://goo.gl/MqrFmX\u000a"); } Promise.prototype._captureStackTrace = Promise_captureStackTrace; Promise.prototype._attachExtraTrace = Promise_attachExtraTrace; Context.deactivateLongStackTraces(); async.enableTrampoline(); config.longStackTraces = false; }; Promise.prototype._captureStackTrace = longStackTracesCaptureStackTrace; Promise.prototype._attachExtraTrace = longStackTracesAttachExtraTrace; Context.activateLongStackTraces(); async.disableTrampolineIfNecessary(); } }; Promise.hasLongStackTraces = function () { return config.longStackTraces && longStackTracesIsSupported(); }; var fireDomEvent = (function() { try { var event = document.createEvent("CustomEvent"); event.initCustomEvent("testingtheevent", false, true, {}); util.global.dispatchEvent(event); return function(name, event) { var domEvent = document.createEvent("CustomEvent"); domEvent.initCustomEvent(name.toLowerCase(), false, true, event); return !util.global.dispatchEvent(domEvent); }; } catch (e) {} return function() { return false; }; })(); var fireGlobalEvent = (function() { if (util.isNode) { return function() { return process.emit.apply(process, arguments); }; } else { if (!util.global) { return function() { return false; }; } return function(name) { var methodName = "on" + name.toLowerCase(); var method = util.global[methodName]; if (!method) return false; method.apply(util.global, [].slice.call(arguments, 1)); return true; }; } })(); function generatePromiseLifecycleEventObject(name, promise) { return {promise: promise}; } var eventToObjectGenerator = { promiseCreated: generatePromiseLifecycleEventObject, promiseFulfilled: generatePromiseLifecycleEventObject, promiseRejected: generatePromiseLifecycleEventObject, promiseResolved: generatePromiseLifecycleEventObject, promiseCancelled: generatePromiseLifecycleEventObject, promiseChained: function(name, promise, child) { return {promise: promise, child: child}; }, warning: function(name, warning) { return {warning: warning}; }, unhandledRejection: function (name, reason, promise) { return {reason: reason, promise: promise}; }, rejectionHandled: generatePromiseLifecycleEventObject }; var activeFireEvent = function (name) { var globalEventFired = false; try { globalEventFired = fireGlobalEvent.apply(null, arguments); } catch (e) { async.throwLater(e); globalEventFired = true; } var domEventFired = false; try { domEventFired = fireDomEvent(name, eventToObjectGenerator[name].apply(null, arguments)); } catch (e) { async.throwLater(e); domEventFired = true; } return domEventFired || globalEventFired; }; Promise.config = function(opts) { opts = Object(opts); if ("longStackTraces" in opts) { if (opts.longStackTraces) { Promise.longStackTraces(); } else if (!opts.longStackTraces && Promise.hasLongStackTraces()) { disableLongStackTraces(); } } if ("warnings" in opts) { var warningsOption = opts.warnings; config.warnings = !!warningsOption; wForgottenReturn = config.warnings; if (util.isObject(warningsOption)) { if ("wForgottenReturn" in warningsOption) { wForgottenReturn = !!warningsOption.wForgottenReturn; } } } if ("cancellation" in opts && opts.cancellation && !config.cancellation) { if (async.haveItemsQueued()) { throw new Error( "cannot enable cancellation after promises are in use"); } Promise.prototype._clearCancellationData = cancellationClearCancellationData; Promise.prototype._propagateFrom = cancellationPropagateFrom; Promise.prototype._onCancel = cancellationOnCancel; Promise.prototype._setOnCancel = cancellationSetOnCancel; Promise.prototype._attachCancellationCallback = cancellationAttachCancellationCallback; Promise.prototype._execute = cancellationExecute; propagateFromFunction = cancellationPropagateFrom; config.cancellation = true; } if ("monitoring" in opts) { if (opts.monitoring && !config.monitoring) { config.monitoring = true; Promise.prototype._fireEvent = activeFireEvent; } else if (!opts.monitoring && config.monitoring) { config.monitoring = false; Promise.prototype._fireEvent = defaultFireEvent; } } }; function defaultFireEvent() { return false; } Promise.prototype._fireEvent = defaultFireEvent; Promise.prototype._execute = function(executor, resolve, reject) { try { executor(resolve, reject); } catch (e) { return e; } }; Promise.prototype._onCancel = function () {}; Promise.prototype._setOnCancel = function (handler) { ; }; Promise.prototype._attachCancellationCallback = function(onCancel) { ; }; Promise.prototype._captureStackTrace = function () {}; Promise.prototype._attachExtraTrace = function () {}; Promise.prototype._clearCancellationData = function() {}; Promise.prototype._propagateFrom = function (parent, flags) { ; ; }; function cancellationExecute(executor, resolve, reject) { var promise = this; try { executor(resolve, reject, function(onCancel) { if (typeof onCancel !== "function") { throw new TypeError("onCancel must be a function, got: " + util.toString(onCancel)); } promise._attachCancellationCallback(onCancel); }); } catch (e) { return e; } } function cancellationAttachCancellationCallback(onCancel) { if (!this.isCancellable()) return this; var previousOnCancel = this._onCancel(); if (previousOnCancel !== undefined) { if (util.isArray(previousOnCancel)) { previousOnCancel.push(onCancel); } else { this._setOnCancel([previousOnCancel, onCancel]); } } else { this._setOnCancel(onCancel); } } function cancellationOnCancel() { return this._onCancelField; } function cancellationSetOnCancel(onCancel) { this._onCancelField = onCancel; } function cancellationClearCancellationData() { this._cancellationParent = undefined; this._onCancelField = undefined; } function cancellationPropagateFrom(parent, flags) { if ((flags & 1) !== 0) { this._cancellationParent = parent; var branchesRemainingToCancel = parent._branchesRemainingToCancel; if (branchesRemainingToCancel === undefined) { branchesRemainingToCancel = 0; } parent._branchesRemainingToCancel = branchesRemainingToCancel + 1; } if ((flags & 2) !== 0 && parent._isBound()) { this._setBoundTo(parent._boundTo); } } function bindingPropagateFrom(parent, flags) { if ((flags & 2) !== 0 && parent._isBound()) { this._setBoundTo(parent._boundTo); } } var propagateFromFunction = bindingPropagateFrom; function boundValueFunction() { var ret = this._boundTo; if (ret !== undefined) { if (ret instanceof Promise) { if (ret.isFulfilled()) { return ret.value(); } else { return undefined; } } } return ret; } function longStackTracesCaptureStackTrace() { this._trace = new CapturedTrace(this._peekContext()); } function longStackTracesAttachExtraTrace(error, ignoreSelf) { if (canAttachTrace(error)) { var trace = this._trace; if (trace !== undefined) { if (ignoreSelf) trace = trace._parent; } if (trace !== undefined) { trace.attachExtraTrace(error); } else if (!error.__stackCleaned__) { var parsed = parseStackAndMessage(error); util.notEnumerableProp(error, "stack", parsed.message + "\n" + parsed.stack.join("\n")); util.notEnumerableProp(error, "__stackCleaned__", true); } } } function checkForgottenReturns(returnValue, promiseCreated, name, promise, parent) { if (returnValue === undefined && promiseCreated !== null && wForgottenReturn) { if (parent !== undefined && parent._returnedNonUndefined()) return; if (name) name = name + " "; var msg = "a promise was created in a " + name + "handler but was not returned from it"; promise._warn(msg, true, promiseCreated); } } function deprecated(name, replacement) { var message = name + " is deprecated and will be removed in a future version."; if (replacement) message += " Use " + replacement + " instead."; return warn(message); } function warn(message, shouldUseOwnTrace, promise) { if (!config.warnings) return; var warning = new Warning(message); var ctx; if (shouldUseOwnTrace) { promise._attachExtraTrace(warning); } else if (config.longStackTraces && (ctx = Promise._peekContext())) { ctx.attachExtraTrace(warning); } else { var parsed = parseStackAndMessage(warning); warning.stack = parsed.message + "\n" + parsed.stack.join("\n"); } if (!activeFireEvent("warning", warning)) { formatAndLogError(warning, "", true); } } function reconstructStack(message, stacks) { for (var i = 0; i < stacks.length - 1; ++i) { stacks[i].push("From previous event:"); stacks[i] = stacks[i].join("\n"); } if (i < stacks.length) { stacks[i] = stacks[i].join("\n"); } return message + "\n" + stacks.join("\n"); } function removeDuplicateOrEmptyJumps(stacks) { for (var i = 0; i < stacks.length; ++i) { if (stacks[i].length === 0 || ((i + 1 < stacks.length) && stacks[i][0] === stacks[i+1][0])) { stacks.splice(i, 1); i--; } } } function removeCommonRoots(stacks) { var current = stacks[0]; for (var i = 1; i < stacks.length; ++i) { var prev = stacks[i]; var currentLastIndex = current.length - 1; var currentLastLine = current[currentLastIndex]; var commonRootMeetPoint = -1; for (var j = prev.length - 1; j >= 0; --j) { if (prev[j] === currentLastLine) { commonRootMeetPoint = j; break; } } for (var j = commonRootMeetPoint; j >= 0; --j) { var line = prev[j]; if (current[currentLastIndex] === line) { current.pop(); currentLastIndex--; } else { break; } } current = prev; } } function cleanStack(stack) { var ret = []; for (var i = 0; i < stack.length; ++i) { var line = stack[i]; var isTraceLine = " (No stack trace)" === line || stackFramePattern.test(line); var isInternalFrame = isTraceLine && shouldIgnore(line); if (isTraceLine && !isInternalFrame) { if (indentStackFrames && line.charAt(0) !== " ") { line = " " + line; } ret.push(line); } } return ret; } function stackFramesAsArray(error) { var stack = error.stack.replace(/\s+$/g, "").split("\n"); for (var i = 0; i < stack.length; ++i) { var line = stack[i]; if (" (No stack trace)" === line || stackFramePattern.test(line)) { break; } } if (i > 0) { stack = stack.slice(i); } return stack; } function parseStackAndMessage(error) { var stack = error.stack; var message = error.toString(); stack = typeof stack === "string" && stack.length > 0 ? stackFramesAsArray(error) : [" (No stack trace)"]; return { message: message, stack: cleanStack(stack) }; } function formatAndLogError(error, title, isSoft) { if (typeof console !== "undefined") { var message; if (util.isObject(error)) { var stack = error.stack; message = title + formatStack(stack, error); } else { message = title + String(error); } if (typeof printWarning === "function") { printWarning(message, isSoft); } else if (typeof console.log === "function" || typeof console.log === "object") { console.log(message); } } } function fireRejectionEvent(name, localHandler, reason, promise) { var localEventFired = false; try { if (typeof localHandler === "function") { localEventFired = true; if (name === "rejectionHandled") { localHandler(promise); } else { localHandler(reason, promise); } } } catch (e) { async.throwLater(e); } if (name === "unhandledRejection") { if (!activeFireEvent(name, reason, promise) && !localEventFired) { formatAndLogError(reason, "Unhandled rejection "); } } else { activeFireEvent(name, promise); } } function formatNonError(obj) { var str; if (typeof obj === "function") { str = "[function " + (obj.name || "anonymous") + "]"; } else { str = obj && typeof obj.toString === "function" ? obj.toString() : util.toString(obj); var ruselessToString = /\[object [a-zA-Z0-9$_]+\]/; if (ruselessToString.test(str)) { try { var newStr = JSON.stringify(obj); str = newStr; } catch(e) { } } if (str.length === 0) { str = "(empty array)"; } } return ("(<" + snip(str) + ">, no stack trace)"); } function snip(str) { var maxChars = 41; if (str.length < maxChars) { return str; } return str.substr(0, maxChars - 3) + "..."; } function longStackTracesIsSupported() { return typeof captureStackTrace === "function"; } var shouldIgnore = function() { return false; }; var parseLineInfoRegex = /[\/<\(]([^:\/]+):(\d+):(?:\d+)\)?\s*$/; function parseLineInfo(line) { var matches = line.match(parseLineInfoRegex); if (matches) { return { fileName: matches[1], line: parseInt(matches[2], 10) }; } } function setBounds(firstLineError, lastLineError) { if (!longStackTracesIsSupported()) return; var firstStackLines = firstLineError.stack.split("\n"); var lastStackLines = lastLineError.stack.split("\n"); var firstIndex = -1; var lastIndex = -1; var firstFileName; var lastFileName; for (var i = 0; i < firstStackLines.length; ++i) { var result = parseLineInfo(firstStackLines[i]); if (result) { firstFileName = result.fileName; firstIndex = result.line; break; } } for (var i = 0; i < lastStackLines.length; ++i) { var result = parseLineInfo(lastStackLines[i]); if (result) { lastFileName = result.fileName; lastIndex = result.line; break; } } if (firstIndex < 0 || lastIndex < 0 || !firstFileName || !lastFileName || firstFileName !== lastFileName || firstIndex >= lastIndex) { return; } shouldIgnore = function(line) { if (bluebirdFramePattern.test(line)) return true; var info = parseLineInfo(line); if (info) { if (info.fileName === firstFileName && (firstIndex <= info.line && info.line <= lastIndex)) { return true; } } return false; }; } function CapturedTrace(parent) { this._parent = parent; this._promisesCreated = 0; var length = this._length = 1 + (parent === undefined ? 0 : parent._length); captureStackTrace(this, CapturedTrace); if (length > 32) this.uncycle(); } util.inherits(CapturedTrace, Error); Context.CapturedTrace = CapturedTrace; CapturedTrace.prototype.uncycle = function() { var length = this._length; if (length < 2) return; var nodes = []; var stackToIndex = {}; for (var i = 0, node = this; node !== undefined; ++i) { nodes.push(node); node = node._parent; } length = this._length = i; for (var i = length - 1; i >= 0; --i) { var stack = nodes[i].stack; if (stackToIndex[stack] === undefined) { stackToIndex[stack] = i; } } for (var i = 0; i < length; ++i) { var currentStack = nodes[i].stack; var index = stackToIndex[currentStack]; if (index !== undefined && index !== i) { if (index > 0) { nodes[index - 1]._parent = undefined; nodes[index - 1]._length = 1; } nodes[i]._parent = undefined; nodes[i]._length = 1; var cycleEdgeNode = i > 0 ? nodes[i - 1] : this; if (index < length - 1) { cycleEdgeNode._parent = nodes[index + 1]; cycleEdgeNode._parent.uncycle(); cycleEdgeNode._length = cycleEdgeNode._parent._length + 1; } else { cycleEdgeNode._parent = undefined; cycleEdgeNode._length = 1; } var currentChildLength = cycleEdgeNode._length + 1; for (var j = i - 2; j >= 0; --j) { nodes[j]._length = currentChildLength; currentChildLength++; } return; } } }; CapturedTrace.prototype.attachExtraTrace = function(error) { if (error.__stackCleaned__) return; this.uncycle(); var parsed = parseStackAndMessage(error); var message = parsed.message; var stacks = [parsed.stack]; var trace = this; while (trace !== undefined) { stacks.push(cleanStack(trace.stack.split("\n"))); trace = trace._parent; } removeCommonRoots(stacks); removeDuplicateOrEmptyJumps(stacks); util.notEnumerableProp(error, "stack", reconstructStack(message, stacks)); util.notEnumerableProp(error, "__stackCleaned__", true); }; var captureStackTrace = (function stackDetection() { var v8stackFramePattern = /^\s*at\s*/; var v8stackFormatter = function(stack, error) { if (typeof stack === "string") return stack; if (error.name !== undefined && error.message !== undefined) { return error.toString(); } return formatNonError(error); }; if (typeof Error.stackTraceLimit === "number" && typeof Error.captureStackTrace === "function") { Error.stackTraceLimit += 6; stackFramePattern = v8stackFramePattern; formatStack = v8stackFormatter; var captureStackTrace = Error.captureStackTrace; shouldIgnore = function(line) { return bluebirdFramePattern.test(line); }; return function(receiver, ignoreUntil) { Error.stackTraceLimit += 6; captureStackTrace(receiver, ignoreUntil); Error.stackTraceLimit -= 6; }; } var err = new Error(); if (typeof err.stack === "string" && err.stack.split("\n")[0].indexOf("stackDetection@") >= 0) { stackFramePattern = /@/; formatStack = v8stackFormatter; indentStackFrames = true; return function captureStackTrace(o) { o.stack = new Error().stack; }; } var hasStackAfterThrow; try { throw new Error(); } catch(e) { hasStackAfterThrow = ("stack" in e); } if (!("stack" in err) && hasStackAfterThrow && typeof Error.stackTraceLimit === "number") { stackFramePattern = v8stackFramePattern; formatStack = v8stackFormatter; return function captureStackTrace(o) { Error.stackTraceLimit += 6; try { throw new Error(); } catch(e) { o.stack = e.stack; } Error.stackTraceLimit -= 6; }; } formatStack = function(stack, error) { if (typeof stack === "string") return stack; if ((typeof error === "object" || typeof error === "function") && error.name !== undefined && error.message !== undefined) { return error.toString(); } return formatNonError(error); }; return null; })([]); if (typeof console !== "undefined" && typeof console.warn !== "undefined") { printWarning = function (message) { console.warn(message); }; if (util.isNode && process.stderr.isTTY) { printWarning = function(message, isSoft) { var color = isSoft ? "\u001b[33m" : "\u001b[31m"; console.warn(color + message + "\u001b[0m\n"); }; } else if (!util.isNode && typeof (new Error().stack) === "string") { printWarning = function(message, isSoft) { console.warn("%c" + message, isSoft ? "color: darkorange" : "color: red"); }; } } var config = { warnings: warnings, longStackTraces: false, cancellation: false, monitoring: false }; if (longStackTraces) Promise.longStackTraces(); return { longStackTraces: function() { return config.longStackTraces; }, warnings: function() { return config.warnings; }, cancellation: function() { return config.cancellation; }, monitoring: function() { return config.monitoring; }, propagateFromFunction: function() { return propagateFromFunction; }, boundValueFunction: function() { return boundValueFunction; }, checkForgottenReturns: checkForgottenReturns, setBounds: setBounds, warn: warn, deprecated: deprecated, CapturedTrace: CapturedTrace, fireDomEvent: fireDomEvent, fireGlobalEvent: fireGlobalEvent }; }; },{"./errors":12,"./util":36}],10:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise) { function returner() { return this.value; } function thrower() { throw this.reason; } Promise.prototype["return"] = Promise.prototype.thenReturn = function (value) { if (value instanceof Promise) value.suppressUnhandledRejections(); return this._then( returner, undefined, undefined, {value: value}, undefined); }; Promise.prototype["throw"] = Promise.prototype.thenThrow = function (reason) { return this._then( thrower, undefined, undefined, {reason: reason}, undefined); }; Promise.prototype.catchThrow = function (reason) { if (arguments.length <= 1) { return this._then( undefined, thrower, undefined, {reason: reason}, undefined); } else { var _reason = arguments[1]; var handler = function() {throw _reason;}; return this.caught(reason, handler); } }; Promise.prototype.catchReturn = function (value) { if (arguments.length <= 1) { if (value instanceof Promise) value.suppressUnhandledRejections(); return this._then( undefined, returner, undefined, {value: value}, undefined); } else { var _value = arguments[1]; if (_value instanceof Promise) _value.suppressUnhandledRejections(); var handler = function() {return _value;}; return this.caught(value, handler); } }; }; },{}],11:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise, INTERNAL) { var PromiseReduce = Promise.reduce; var PromiseAll = Promise.all; function promiseAllThis() { return PromiseAll(this); } function PromiseMapSeries(promises, fn) { return PromiseReduce(promises, fn, INTERNAL, INTERNAL); } Promise.prototype.each = function (fn) { return this.mapSeries(fn) ._then(promiseAllThis, undefined, undefined, this, undefined); }; Promise.prototype.mapSeries = function (fn) { return PromiseReduce(this, fn, INTERNAL, INTERNAL); }; Promise.each = function (promises, fn) { return PromiseMapSeries(promises, fn) ._then(promiseAllThis, undefined, undefined, promises, undefined); }; Promise.mapSeries = PromiseMapSeries; }; },{}],12:[function(_dereq_,module,exports){ "use strict"; var es5 = _dereq_("./es5"); var Objectfreeze = es5.freeze; var util = _dereq_("./util"); var inherits = util.inherits; var notEnumerableProp = util.notEnumerableProp; function subError(nameProperty, defaultMessage) { function SubError(message) { if (!(this instanceof SubError)) return new SubError(message); notEnumerableProp(this, "message", typeof message === "string" ? message : defaultMessage); notEnumerableProp(this, "name", nameProperty); if (Error.captureStackTrace) { Error.captureStackTrace(this, this.constructor); } else { Error.call(this); } } inherits(SubError, Error); return SubError; } var _TypeError, _RangeError; var Warning = subError("Warning", "warning"); var CancellationError = subError("CancellationError", "cancellation error"); var TimeoutError = subError("TimeoutError", "timeout error"); var AggregateError = subError("AggregateError", "aggregate error"); try { _TypeError = TypeError; _RangeError = RangeError; } catch(e) { _TypeError = subError("TypeError", "type error"); _RangeError = subError("RangeError", "range error"); } var methods = ("join pop push shift unshift slice filter forEach some " + "every map indexOf lastIndexOf reduce reduceRight sort reverse").split(" "); for (var i = 0; i < methods.length; ++i) { if (typeof Array.prototype[methods[i]] === "function") { AggregateError.prototype[methods[i]] = Array.prototype[methods[i]]; } } es5.defineProperty(AggregateError.prototype, "length", { value: 0, configurable: false, writable: true, enumerable: true }); AggregateError.prototype["isOperational"] = true; var level = 0; AggregateError.prototype.toString = function() { var indent = Array(level * 4 + 1).join(" "); var ret = "\n" + indent + "AggregateError of:" + "\n"; level++; indent = Array(level * 4 + 1).join(" "); for (var i = 0; i < this.length; ++i) { var str = this[i] === this ? "[Circular AggregateError]" : this[i] + ""; var lines = str.split("\n"); for (var j = 0; j < lines.length; ++j) { lines[j] = indent + lines[j]; } str = lines.join("\n"); ret += str + "\n"; } level--; return ret; }; function OperationalError(message) { if (!(this instanceof OperationalError)) return new OperationalError(message); notEnumerableProp(this, "name", "OperationalError"); notEnumerableProp(this, "message", message); this.cause = message; this["isOperational"] = true; if (message instanceof Error) { notEnumerableProp(this, "message", message.message); notEnumerableProp(this, "stack", message.stack); } else if (Error.captureStackTrace) { Error.captureStackTrace(this, this.constructor); } } inherits(OperationalError, Error); var errorTypes = Error["__BluebirdErrorTypes__"]; if (!errorTypes) { errorTypes = Objectfreeze({ CancellationError: CancellationError, TimeoutError: TimeoutError, OperationalError: OperationalError, RejectionError: OperationalError, AggregateError: AggregateError }); es5.defineProperty(Error, "__BluebirdErrorTypes__", { value: errorTypes, writable: false, enumerable: false, configurable: false }); } module.exports = { Error: Error, TypeError: _TypeError, RangeError: _RangeError, CancellationError: errorTypes.CancellationError, OperationalError: errorTypes.OperationalError, TimeoutError: errorTypes.TimeoutError, AggregateError: errorTypes.AggregateError, Warning: Warning }; },{"./es5":13,"./util":36}],13:[function(_dereq_,module,exports){ var isES5 = (function(){ "use strict"; return this === undefined; })(); if (isES5) { module.exports = { freeze: Object.freeze, defineProperty: Object.defineProperty, getDescriptor: Object.getOwnPropertyDescriptor, keys: Object.keys, names: Object.getOwnPropertyNames, getPrototypeOf: Object.getPrototypeOf, isArray: Array.isArray, isES5: isES5, propertyIsWritable: function(obj, prop) { var descriptor = Object.getOwnPropertyDescriptor(obj, prop); return !!(!descriptor || descriptor.writable || descriptor.set); } }; } else { var has = {}.hasOwnProperty; var str = {}.toString; var proto = {}.constructor.prototype; var ObjectKeys = function (o) { var ret = []; for (var key in o) { if (has.call(o, key)) { ret.push(key); } } return ret; }; var ObjectGetDescriptor = function(o, key) { return {value: o[key]}; }; var ObjectDefineProperty = function (o, key, desc) { o[key] = desc.value; return o; }; var ObjectFreeze = function (obj) { return obj; }; var ObjectGetPrototypeOf = function (obj) { try { return Object(obj).constructor.prototype; } catch (e) { return proto; } }; var ArrayIsArray = function (obj) { try { return str.call(obj) === "[object Array]"; } catch(e) { return false; } }; module.exports = { isArray: ArrayIsArray, keys: ObjectKeys, names: ObjectKeys, defineProperty: ObjectDefineProperty, getDescriptor: ObjectGetDescriptor, freeze: ObjectFreeze, getPrototypeOf: ObjectGetPrototypeOf, isES5: isES5, propertyIsWritable: function() { return true; } }; } },{}],14:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise, INTERNAL) { var PromiseMap = Promise.map; Promise.prototype.filter = function (fn, options) { return PromiseMap(this, fn, options, INTERNAL); }; Promise.filter = function (promises, fn, options) { return PromiseMap(promises, fn, options, INTERNAL); }; }; },{}],15:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise, tryConvertToPromise) { var util = _dereq_("./util"); var CancellationError = Promise.CancellationError; var errorObj = util.errorObj; function PassThroughHandlerContext(promise, type, handler) { this.promise = promise; this.type = type; this.handler = handler; this.called = false; this.cancelPromise = null; } PassThroughHandlerContext.prototype.isFinallyHandler = function() { return this.type === 0; }; function FinallyHandlerCancelReaction(finallyHandler) { this.finallyHandler = finallyHandler; } FinallyHandlerCancelReaction.prototype._resultCancelled = function() { checkCancel(this.finallyHandler); }; function checkCancel(ctx, reason) { if (ctx.cancelPromise != null) { if (arguments.length > 1) { ctx.cancelPromise._reject(reason); } else { ctx.cancelPromise._cancel(); } ctx.cancelPromise = null; return true; } return false; } function succeed() { return finallyHandler.call(this, this.promise._target()._settledValue()); } function fail(reason) { if (checkCancel(this, reason)) return; errorObj.e = reason; return errorObj; } function finallyHandler(reasonOrValue) { var promise = this.promise; var handler = this.handler; if (!this.called) { this.called = true; var ret = this.isFinallyHandler() ? handler.call(promise._boundValue()) : handler.call(promise._boundValue(), reasonOrValue); if (ret !== undefined) { promise._setReturnedNonUndefined(); var maybePromise = tryConvertToPromise(ret, promise); if (maybePromise instanceof Promise) { if (this.cancelPromise != null) { if (maybePromise.isCancelled()) { var reason = new CancellationError("late cancellation observer"); promise._attachExtraTrace(reason); errorObj.e = reason; return errorObj; } else if (maybePromise.isPending()) { maybePromise._attachCancellationCallback( new FinallyHandlerCancelReaction(this)); } } return maybePromise._then( succeed, fail, undefined, this, undefined); } } } if (promise.isRejected()) { checkCancel(this); errorObj.e = reasonOrValue; return errorObj; } else { checkCancel(this); return reasonOrValue; } } Promise.prototype._passThrough = function(handler, type, success, fail) { if (typeof handler !== "function") return this.then(); return this._then(success, fail, undefined, new PassThroughHandlerContext(this, type, handler), undefined); }; Promise.prototype.lastly = Promise.prototype["finally"] = function (handler) { return this._passThrough(handler, 0, finallyHandler, finallyHandler); }; Promise.prototype.tap = function (handler) { return this._passThrough(handler, 1, finallyHandler); }; return PassThroughHandlerContext; }; },{"./util":36}],16:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise, apiRejection, INTERNAL, tryConvertToPromise, Proxyable, debug) { var errors = _dereq_("./errors"); var TypeError = errors.TypeError; var util = _dereq_("./util"); var errorObj = util.errorObj; var tryCatch = util.tryCatch; var yieldHandlers = []; function promiseFromYieldHandler(value, yieldHandlers, traceParent) { for (var i = 0; i < yieldHandlers.length; ++i) { traceParent._pushContext(); var result = tryCatch(yieldHandlers[i])(value); traceParent._popContext(); if (result === errorObj) { traceParent._pushContext(); var ret = Promise.reject(errorObj.e); traceParent._popContext(); return ret; } var maybePromise = tryConvertToPromise(result, traceParent); if (maybePromise instanceof Promise) return maybePromise; } return null; } function PromiseSpawn(generatorFunction, receiver, yieldHandler, stack) { var promise = this._promise = new Promise(INTERNAL); promise._captureStackTrace(); promise._setOnCancel(this); this._stack = stack; this._generatorFunction = generatorFunction; this._receiver = receiver; this._generator = undefined; this._yieldHandlers = typeof yieldHandler === "function" ? [yieldHandler].concat(yieldHandlers) : yieldHandlers; this._yieldedPromise = null; } util.inherits(PromiseSpawn, Proxyable); PromiseSpawn.prototype._isResolved = function() { return this._promise === null; }; PromiseSpawn.prototype._cleanup = function() { this._promise = this._generator = null; }; PromiseSpawn.prototype._promiseCancelled = function() { if (this._isResolved()) return; var implementsReturn = typeof this._generator["return"] !== "undefined"; var result; if (!implementsReturn) { var reason = new Promise.CancellationError( "generator .return() sentinel"); Promise.coroutine.returnSentinel = reason; this._promise._attachExtraTrace(reason); this._promise._pushContext(); result = tryCatch(this._generator["throw"]).call(this._generator, reason); this._promise._popContext(); if (result === errorObj && result.e === reason) { result = null; } } else { this._promise._pushContext(); result = tryCatch(this._generator["return"]).call(this._generator, undefined); this._promise._popContext(); } var promise = this._promise; this._cleanup(); if (result === errorObj) { promise._rejectCallback(result.e, false); } else { promise.cancel(); } }; PromiseSpawn.prototype._promiseFulfilled = function(value) { this._yieldedPromise = null; this._promise._pushContext(); var result = tryCatch(this._generator.next).call(this._generator, value); this._promise._popContext(); this._continue(result); }; PromiseSpawn.prototype._promiseRejected = function(reason) { this._yieldedPromise = null; this._promise._attachExtraTrace(reason); this._promise._pushContext(); var result = tryCatch(this._generator["throw"]) .call(this._generator, reason); this._promise._popContext(); this._continue(result); }; PromiseSpawn.prototype._resultCancelled = function() { if (this._yieldedPromise instanceof Promise) { var promise = this._yieldedPromise; this._yieldedPromise = null; promise.cancel(); } }; PromiseSpawn.prototype.promise = function () { return this._promise; }; PromiseSpawn.prototype._run = function () { this._generator = this._generatorFunction.call(this._receiver); this._receiver = this._generatorFunction = undefined; this._promiseFulfilled(undefined); }; PromiseSpawn.prototype._continue = function (result) { var promise = this._promise; if (result === errorObj) { this._cleanup(); return promise._rejectCallback(result.e, false); } var value = result.value; if (result.done === true) { this._cleanup(); return promise._resolveCallback(value); } else { var maybePromise = tryConvertToPromise(value, this._promise); if (!(maybePromise instanceof Promise)) { maybePromise = promiseFromYieldHandler(maybePromise, this._yieldHandlers, this._promise); if (maybePromise === null) { this._promiseRejected( new TypeError( "A value %s was yielded that could not be treated as a promise\u000a\u000a See http://goo.gl/MqrFmX\u000a\u000a".replace("%s", value) + "From coroutine:\u000a" + this._stack.split("\n").slice(1, -7).join("\n") ) ); return; } } maybePromise = maybePromise._target(); var bitField = maybePromise._bitField; ; if (((bitField & 50397184) === 0)) { this._yieldedPromise = maybePromise; maybePromise._proxy(this, null); } else if (((bitField & 33554432) !== 0)) { this._promiseFulfilled(maybePromise._value()); } else if (((bitField & 16777216) !== 0)) { this._promiseRejected(maybePromise._reason()); } else { this._promiseCancelled(); } } }; Promise.coroutine = function (generatorFunction, options) { if (typeof generatorFunction !== "function") { throw new TypeError("generatorFunction must be a function\u000a\u000a See http://goo.gl/MqrFmX\u000a"); } var yieldHandler = Object(options).yieldHandler; var PromiseSpawn$ = PromiseSpawn; var stack = new Error().stack; return function () { var generator = generatorFunction.apply(this, arguments); var spawn = new PromiseSpawn$(undefined, undefined, yieldHandler, stack); var ret = spawn.promise(); spawn._generator = generator; spawn._promiseFulfilled(undefined); return ret; }; }; Promise.coroutine.addYieldHandler = function(fn) { if (typeof fn !== "function") { throw new TypeError("expecting a function but got " + util.classString(fn)); } yieldHandlers.push(fn); }; Promise.spawn = function (generatorFunction) { debug.deprecated("Promise.spawn()", "Promise.coroutine()"); if (typeof generatorFunction !== "function") { return apiRejection("generatorFunction must be a function\u000a\u000a See http://goo.gl/MqrFmX\u000a"); } var spawn = new PromiseSpawn(generatorFunction, this); var ret = spawn.promise(); spawn._run(Promise.spawn); return ret; }; }; },{"./errors":12,"./util":36}],17:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise, PromiseArray, tryConvertToPromise, INTERNAL) { var util = _dereq_("./util"); var canEvaluate = util.canEvaluate; var tryCatch = util.tryCatch; var errorObj = util.errorObj; var reject; if (!true) { if (canEvaluate) { var thenCallback = function(i) { return new Function("value", "holder", " \n\ 'use strict'; \n\ holder.pIndex = value; \n\ holder.checkFulfillment(this); \n\ ".replace(/Index/g, i)); }; var promiseSetter = function(i) { return new Function("promise", "holder", " \n\ 'use strict'; \n\ holder.pIndex = promise; \n\ ".replace(/Index/g, i)); }; var generateHolderClass = function(total) { var props = new Array(total); for (var i = 0; i < props.length; ++i) { props[i] = "this.p" + (i+1); } var assignment = props.join(" = ") + " = null;"; var cancellationCode= "var promise;\n" + props.map(function(prop) { return " \n\ promise = " + prop + "; \n\ if (promise instanceof Promise) { \n\ promise.cancel(); \n\ } \n\ "; }).join("\n"); var passedArguments = props.join(", "); var name = "Holder$" + total; var code = "return function(tryCatch, errorObj, Promise) { \n\ 'use strict'; \n\ function [TheName](fn) { \n\ [TheProperties] \n\ this.fn = fn; \n\ this.now = 0; \n\ } \n\ [TheName].prototype.checkFulfillment = function(promise) { \n\ var now = ++this.now; \n\ if (now === [TheTotal]) { \n\ promise._pushContext(); \n\ var callback = this.fn; \n\ var ret = tryCatch(callback)([ThePassedArguments]); \n\ promise._popContext(); \n\ if (ret === errorObj) { \n\ promise._rejectCallback(ret.e, false); \n\ } else { \n\ promise._resolveCallback(ret); \n\ } \n\ } \n\ }; \n\ \n\ [TheName].prototype._resultCancelled = function() { \n\ [CancellationCode] \n\ }; \n\ \n\ return [TheName]; \n\ }(tryCatch, errorObj, Promise); \n\ "; code = code.replace(/\[TheName\]/g, name) .replace(/\[TheTotal\]/g, total) .replace(/\[ThePassedArguments\]/g, passedArguments) .replace(/\[TheProperties\]/g, assignment) .replace(/\[CancellationCode\]/g, cancellationCode); return new Function("tryCatch", "errorObj", "Promise", code) (tryCatch, errorObj, Promise); }; var holderClasses = []; var thenCallbacks = []; var promiseSetters = []; for (var i = 0; i < 8; ++i) { holderClasses.push(generateHolderClass(i + 1)); thenCallbacks.push(thenCallback(i + 1)); promiseSetters.push(promiseSetter(i + 1)); } reject = function (reason) { this._reject(reason); }; }} Promise.join = function () { var last = arguments.length - 1; var fn; if (last > 0 && typeof arguments[last] === "function") { fn = arguments[last]; if (!true) { if (last <= 8 && canEvaluate) { var ret = new Promise(INTERNAL); ret._captureStackTrace(); var HolderClass = holderClasses[last - 1]; var holder = new HolderClass(fn); var callbacks = thenCallbacks; for (var i = 0; i < last; ++i) { var maybePromise = tryConvertToPromise(arguments[i], ret); if (maybePromise instanceof Promise) { maybePromise = maybePromise._target(); var bitField = maybePromise._bitField; ; if (((bitField & 50397184) === 0)) { maybePromise._then(callbacks[i], reject, undefined, ret, holder); promiseSetters[i](maybePromise, holder); } else if (((bitField & 33554432) !== 0)) { callbacks[i].call(ret, maybePromise._value(), holder); } else if (((bitField & 16777216) !== 0)) { ret._reject(maybePromise._reason()); } else { ret._cancel(); } } else { callbacks[i].call(ret, maybePromise, holder); } } if (!ret._isFateSealed()) { ret._setAsyncGuaranteed(); ret._setOnCancel(holder); } return ret; } } } var args = [].slice.call(arguments);; if (fn) args.pop(); var ret = new PromiseArray(args).promise(); return fn !== undefined ? ret.spread(fn) : ret; }; }; },{"./util":36}],18:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL, debug) { var getDomain = Promise._getDomain; var util = _dereq_("./util"); var tryCatch = util.tryCatch; var errorObj = util.errorObj; var EMPTY_ARRAY = []; function MappingPromiseArray(promises, fn, limit, _filter) { this.constructor$(promises); this._promise._captureStackTrace(); var domain = getDomain(); this._callback = domain === null ? fn : domain.bind(fn); this._preservedValues = _filter === INTERNAL ? new Array(this.length()) : null; this._limit = limit; this._inFlight = 0; this._queue = limit >= 1 ? [] : EMPTY_ARRAY; this._init$(undefined, -2); } util.inherits(MappingPromiseArray, PromiseArray); MappingPromiseArray.prototype._init = function () {}; MappingPromiseArray.prototype._promiseFulfilled = function (value, index) { var values = this._values; var length = this.length(); var preservedValues = this._preservedValues; var limit = this._limit; if (index < 0) { index = (index * -1) - 1; values[index] = value; if (limit >= 1) { this._inFlight--; this._drainQueue(); if (this._isResolved()) return true; } } else { if (limit >= 1 && this._inFlight >= limit) { values[index] = value; this._queue.push(index); return false; } if (preservedValues !== null) preservedValues[index] = value; var promise = this._promise; var callback = this._callback; var receiver = promise._boundValue(); promise._pushContext(); var ret = tryCatch(callback).call(receiver, value, index, length); var promiseCreated = promise._popContext(); debug.checkForgottenReturns( ret, promiseCreated, preservedValues !== null ? "Promise.filter" : "Promise.map", promise ); if (ret === errorObj) { this._reject(ret.e); return true; } var maybePromise = tryConvertToPromise(ret, this._promise); if (maybePromise instanceof Promise) { maybePromise = maybePromise._target(); var bitField = maybePromise._bitField; ; if (((bitField & 50397184) === 0)) { if (limit >= 1) this._inFlight++; values[index] = maybePromise; maybePromise._proxy(this, (index + 1) * -1); return false; } else if (((bitField & 33554432) !== 0)) { ret = maybePromise._value(); } else if (((bitField & 16777216) !== 0)) { this._reject(maybePromise._reason()); return true; } else { this._cancel(); return true; } } values[index] = ret; } var totalResolved = ++this._totalResolved; if (totalResolved >= length) { if (preservedValues !== null) { this._filter(values, preservedValues); } else { this._resolve(values); } return true; } return false; }; MappingPromiseArray.prototype._drainQueue = function () { var queue = this._queue; var limit = this._limit; var values = this._values; while (queue.length > 0 && this._inFlight < limit) { if (this._isResolved()) return; var index = queue.pop(); this._promiseFulfilled(values[index], index); } }; MappingPromiseArray.prototype._filter = function (booleans, values) { var len = values.length; var ret = new Array(len); var j = 0; for (var i = 0; i < len; ++i) { if (booleans[i]) ret[j++] = values[i]; } ret.length = j; this._resolve(ret); }; MappingPromiseArray.prototype.preservedValues = function () { return this._preservedValues; }; function map(promises, fn, options, _filter) { if (typeof fn !== "function") { return apiRejection("expecting a function but got " + util.classString(fn)); } var limit = typeof options === "object" && options !== null ? options.concurrency : 0; limit = typeof limit === "number" && isFinite(limit) && limit >= 1 ? limit : 0; return new MappingPromiseArray(promises, fn, limit, _filter).promise(); } Promise.prototype.map = function (fn, options) { return map(this, fn, options, null); }; Promise.map = function (promises, fn, options, _filter) { return map(promises, fn, options, _filter); }; }; },{"./util":36}],19:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise, INTERNAL, tryConvertToPromise, apiRejection, debug) { var util = _dereq_("./util"); var tryCatch = util.tryCatch; Promise.method = function (fn) { if (typeof fn !== "function") { throw new Promise.TypeError("expecting a function but got " + util.classString(fn)); } return function () { var ret = new Promise(INTERNAL); ret._captureStackTrace(); ret._pushContext(); var value = tryCatch(fn).apply(this, arguments); var promiseCreated = ret._popContext(); debug.checkForgottenReturns( value, promiseCreated, "Promise.method", ret); ret._resolveFromSyncValue(value); return ret; }; }; Promise.attempt = Promise["try"] = function (fn) { if (typeof fn !== "function") { return apiRejection("expecting a function but got " + util.classString(fn)); } var ret = new Promise(INTERNAL); ret._captureStackTrace(); ret._pushContext(); var value; if (arguments.length > 1) { debug.deprecated("calling Promise.try with more than 1 argument"); var arg = arguments[1]; var ctx = arguments[2]; value = util.isArray(arg) ? tryCatch(fn).apply(ctx, arg) : tryCatch(fn).call(ctx, arg); } else { value = tryCatch(fn)(); } var promiseCreated = ret._popContext(); debug.checkForgottenReturns( value, promiseCreated, "Promise.try", ret); ret._resolveFromSyncValue(value); return ret; }; Promise.prototype._resolveFromSyncValue = function (value) { if (value === util.errorObj) { this._rejectCallback(value.e, false); } else { this._resolveCallback(value, true); } }; }; },{"./util":36}],20:[function(_dereq_,module,exports){ "use strict"; var util = _dereq_("./util"); var maybeWrapAsError = util.maybeWrapAsError; var errors = _dereq_("./errors"); var OperationalError = errors.OperationalError; var es5 = _dereq_("./es5"); function isUntypedError(obj) { return obj instanceof Error && es5.getPrototypeOf(obj) === Error.prototype; } var rErrorKey = /^(?:name|message|stack|cause)$/; function wrapAsOperationalError(obj) { var ret; if (isUntypedError(obj)) { ret = new OperationalError(obj); ret.name = obj.name; ret.message = obj.message; ret.stack = obj.stack; var keys = es5.keys(obj); for (var i = 0; i < keys.length; ++i) { var key = keys[i]; if (!rErrorKey.test(key)) { ret[key] = obj[key]; } } return ret; } util.markAsOriginatingFromRejection(obj); return obj; } function nodebackForPromise(promise, multiArgs) { return function(err, value) { if (promise === null) return; if (err) { var wrapped = wrapAsOperationalError(maybeWrapAsError(err)); promise._attachExtraTrace(wrapped); promise._reject(wrapped); } else if (!multiArgs) { promise._fulfill(value); } else { var args = [].slice.call(arguments, 1);; promise._fulfill(args); } promise = null; }; } module.exports = nodebackForPromise; },{"./errors":12,"./es5":13,"./util":36}],21:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise) { var util = _dereq_("./util"); var async = Promise._async; var tryCatch = util.tryCatch; var errorObj = util.errorObj; function spreadAdapter(val, nodeback) { var promise = this; if (!util.isArray(val)) return successAdapter.call(promise, val, nodeback); var ret = tryCatch(nodeback).apply(promise._boundValue(), [null].concat(val)); if (ret === errorObj) { async.throwLater(ret.e); } } function successAdapter(val, nodeback) { var promise = this; var receiver = promise._boundValue(); var ret = val === undefined ? tryCatch(nodeback).call(receiver, null) : tryCatch(nodeback).call(receiver, null, val); if (ret === errorObj) { async.throwLater(ret.e); } } function errorAdapter(reason, nodeback) { var promise = this; if (!reason) { var newReason = new Error(reason + ""); newReason.cause = reason; reason = newReason; } var ret = tryCatch(nodeback).call(promise._boundValue(), reason); if (ret === errorObj) { async.throwLater(ret.e); } } Promise.prototype.asCallback = Promise.prototype.nodeify = function (nodeback, options) { if (typeof nodeback == "function") { var adapter = successAdapter; if (options !== undefined && Object(options).spread) { adapter = spreadAdapter; } this._then( adapter, errorAdapter, undefined, this, nodeback ); } return this; }; }; },{"./util":36}],22:[function(_dereq_,module,exports){ "use strict"; module.exports = function() { var makeSelfResolutionError = function () { return new TypeError("circular promise resolution chain\u000a\u000a See http://goo.gl/MqrFmX\u000a"); }; var reflectHandler = function() { return new Promise.PromiseInspection(this._target()); }; var apiRejection = function(msg) { return Promise.reject(new TypeError(msg)); }; function Proxyable() {} var UNDEFINED_BINDING = {}; var util = _dereq_("./util"); var getDomain; if (util.isNode) { getDomain = function() { var ret = process.domain; if (ret === undefined) ret = null; return ret; }; } else { getDomain = function() { return null; }; } util.notEnumerableProp(Promise, "_getDomain", getDomain); var es5 = _dereq_("./es5"); var Async = _dereq_("./async"); var async = new Async(); es5.defineProperty(Promise, "_async", {value: async}); var errors = _dereq_("./errors"); var TypeError = Promise.TypeError = errors.TypeError; Promise.RangeError = errors.RangeError; var CancellationError = Promise.CancellationError = errors.CancellationError; Promise.TimeoutError = errors.TimeoutError; Promise.OperationalError = errors.OperationalError; Promise.RejectionError = errors.OperationalError; Promise.AggregateError = errors.AggregateError; var INTERNAL = function(){}; var APPLY = {}; var NEXT_FILTER = {}; var tryConvertToPromise = _dereq_("./thenables")(Promise, INTERNAL); var PromiseArray = _dereq_("./promise_array")(Promise, INTERNAL, tryConvertToPromise, apiRejection, Proxyable); var Context = _dereq_("./context")(Promise); /*jshint unused:false*/ var createContext = Context.create; var debug = _dereq_("./debuggability")(Promise, Context); var CapturedTrace = debug.CapturedTrace; var PassThroughHandlerContext = _dereq_("./finally")(Promise, tryConvertToPromise); var catchFilter = _dereq_("./catch_filter")(NEXT_FILTER); var nodebackForPromise = _dereq_("./nodeback"); var errorObj = util.errorObj; var tryCatch = util.tryCatch; function check(self, executor) { if (typeof executor !== "function") { throw new TypeError("expecting a function but got " + util.classString(executor)); } if (self.constructor !== Promise) { throw new TypeError("the promise constructor cannot be invoked directly\u000a\u000a See http://goo.gl/MqrFmX\u000a"); } } function Promise(executor) { this._bitField = 0; this._fulfillmentHandler0 = undefined; this._rejectionHandler0 = undefined; this._promise0 = undefined; this._receiver0 = undefined; if (executor !== INTERNAL) { check(this, executor); this._resolveFromExecutor(executor); } this._promiseCreated(); this._fireEvent("promiseCreated", this); } Promise.prototype.toString = function () { return "[object Promise]"; }; Promise.prototype.caught = Promise.prototype["catch"] = function (fn) { var len = arguments.length; if (len > 1) { var catchInstances = new Array(len - 1), j = 0, i; for (i = 0; i < len - 1; ++i) { var item = arguments[i]; if (util.isObject(item)) { catchInstances[j++] = item; } else { return apiRejection("expecting an object but got " + util.classString(item)); } } catchInstances.length = j; fn = arguments[i]; return this.then(undefined, catchFilter(catchInstances, fn, this)); } return this.then(undefined, fn); }; Promise.prototype.reflect = function () { return this._then(reflectHandler, reflectHandler, undefined, this, undefined); }; Promise.prototype.then = function (didFulfill, didReject) { if (debug.warnings() && arguments.length > 0 && typeof didFulfill !== "function" && typeof didReject !== "function") { var msg = ".then() only accepts functions but was passed: " + util.classString(didFulfill); if (arguments.length > 1) { msg += ", " + util.classString(didReject); } this._warn(msg); } return this._then(didFulfill, didReject, undefined, undefined, undefined); }; Promise.prototype.done = function (didFulfill, didReject) { var promise = this._then(didFulfill, didReject, undefined, undefined, undefined); promise._setIsFinal(); }; Promise.prototype.spread = function (fn) { if (typeof fn !== "function") { return apiRejection("expecting a function but got " + util.classString(fn)); } return this.all()._then(fn, undefined, undefined, APPLY, undefined); }; Promise.prototype.toJSON = function () { var ret = { isFulfilled: false, isRejected: false, fulfillmentValue: undefined, rejectionReason: undefined }; if (this.isFulfilled()) { ret.fulfillmentValue = this.value(); ret.isFulfilled = true; } else if (this.isRejected()) { ret.rejectionReason = this.reason(); ret.isRejected = true; } return ret; }; Promise.prototype.all = function () { if (arguments.length > 0) { this._warn(".all() was passed arguments but it does not take any"); } return new PromiseArray(this).promise(); }; Promise.prototype.error = function (fn) { return this.caught(util.originatesFromRejection, fn); }; Promise.is = function (val) { return val instanceof Promise; }; Promise.fromNode = Promise.fromCallback = function(fn) { var ret = new Promise(INTERNAL); ret._captureStackTrace(); var multiArgs = arguments.length > 1 ? !!Object(arguments[1]).multiArgs : false; var result = tryCatch(fn)(nodebackForPromise(ret, multiArgs)); if (result === errorObj) { ret._rejectCallback(result.e, true); } if (!ret._isFateSealed()) ret._setAsyncGuaranteed(); return ret; }; Promise.all = function (promises) { return new PromiseArray(promises).promise(); }; Promise.cast = function (obj) { var ret = tryConvertToPromise(obj); if (!(ret instanceof Promise)) { ret = new Promise(INTERNAL); ret._captureStackTrace(); ret._setFulfilled(); ret._rejectionHandler0 = obj; } return ret; }; Promise.resolve = Promise.fulfilled = Promise.cast; Promise.reject = Promise.rejected = function (reason) { var ret = new Promise(INTERNAL); ret._captureStackTrace(); ret._rejectCallback(reason, true); return ret; }; Promise.setScheduler = function(fn) { if (typeof fn !== "function") { throw new TypeError("expecting a function but got " + util.classString(fn)); } var prev = async._schedule; async._schedule = fn; return prev; }; Promise.prototype._then = function ( didFulfill, didReject, _, receiver, internalData ) { var haveInternalData = internalData !== undefined; var promise = haveInternalData ? internalData : new Promise(INTERNAL); var target = this._target(); var bitField = target._bitField; if (!haveInternalData) { promise._propagateFrom(this, 3); promise._captureStackTrace(); if (receiver === undefined && ((this._bitField & 2097152) !== 0)) { if (!((bitField & 50397184) === 0)) { receiver = this._boundValue(); } else { receiver = target === this ? undefined : this._boundTo; } } this._fireEvent("promiseChained", this, promise); } var domain = getDomain(); if (!((bitField & 50397184) === 0)) { var handler, value, settler = target._settlePromiseCtx; if (((bitField & 33554432) !== 0)) { value = target._rejectionHandler0; handler = didFulfill; } else if (((bitField & 16777216) !== 0)) { value = target._fulfillmentHandler0; handler = didReject; target._unsetRejectionIsUnhandled(); } else { settler = target._settlePromiseLateCancellationObserver; value = new CancellationError("late cancellation observer"); target._attachExtraTrace(value); handler = didReject; } async.invoke(settler, target, { handler: domain === null ? handler : (typeof handler === "function" && domain.bind(handler)), promise: promise, receiver: receiver, value: value }); } else { target._addCallbacks(didFulfill, didReject, promise, receiver, domain); } return promise; }; Promise.prototype._length = function () { return this._bitField & 65535; }; Promise.prototype._isFateSealed = function () { return (this._bitField & 117506048) !== 0; }; Promise.prototype._isFollowing = function () { return (this._bitField & 67108864) === 67108864; }; Promise.prototype._setLength = function (len) { this._bitField = (this._bitField & -65536) | (len & 65535); }; Promise.prototype._setFulfilled = function () { this._bitField = this._bitField | 33554432; this._fireEvent("promiseFulfilled", this); }; Promise.prototype._setRejected = function () { this._bitField = this._bitField | 16777216; this._fireEvent("promiseRejected", this); }; Promise.prototype._setFollowing = function () { this._bitField = this._bitField | 67108864; this._fireEvent("promiseResolved", this); }; Promise.prototype._setIsFinal = function () { this._bitField = this._bitField | 4194304; }; Promise.prototype._isFinal = function () { return (this._bitField & 4194304) > 0; }; Promise.prototype._unsetCancelled = function() { this._bitField = this._bitField & (~65536); }; Promise.prototype._setCancelled = function() { this._bitField = this._bitField | 65536; this._fireEvent("promiseCancelled", this); }; Promise.prototype._setAsyncGuaranteed = function() { this._bitField = this._bitField | 134217728; }; Promise.prototype._receiverAt = function (index) { var ret = index === 0 ? this._receiver0 : this[ index * 4 - 4 + 3]; if (ret === UNDEFINED_BINDING) { return undefined; } else if (ret === undefined && this._isBound()) { return this._boundValue(); } return ret; }; Promise.prototype._promiseAt = function (index) { return this[ index * 4 - 4 + 2]; }; Promise.prototype._fulfillmentHandlerAt = function (index) { return this[ index * 4 - 4 + 0]; }; Promise.prototype._rejectionHandlerAt = function (index) { return this[ index * 4 - 4 + 1]; }; Promise.prototype._boundValue = function() {}; Promise.prototype._migrateCallback0 = function (follower) { var bitField = follower._bitField; var fulfill = follower._fulfillmentHandler0; var reject = follower._rejectionHandler0; var promise = follower._promise0; var receiver = follower._receiverAt(0); if (receiver === undefined) receiver = UNDEFINED_BINDING; this._addCallbacks(fulfill, reject, promise, receiver, null); }; Promise.prototype._migrateCallbackAt = function (follower, index) { var fulfill = follower._fulfillmentHandlerAt(index); var reject = follower._rejectionHandlerAt(index); var promise = follower._promiseAt(index); var receiver = follower._receiverAt(index); if (receiver === undefined) receiver = UNDEFINED_BINDING; this._addCallbacks(fulfill, reject, promise, receiver, null); }; Promise.prototype._addCallbacks = function ( fulfill, reject, promise, receiver, domain ) { var index = this._length(); if (index >= 65535 - 4) { index = 0; this._setLength(0); } if (index === 0) { this._promise0 = promise; this._receiver0 = receiver; if (typeof fulfill === "function") { this._fulfillmentHandler0 = domain === null ? fulfill : domain.bind(fulfill); } if (typeof reject === "function") { this._rejectionHandler0 = domain === null ? reject : domain.bind(reject); } } else { var base = index * 4 - 4; this[base + 2] = promise; this[base + 3] = receiver; if (typeof fulfill === "function") { this[base + 0] = domain === null ? fulfill : domain.bind(fulfill); } if (typeof reject === "function") { this[base + 1] = domain === null ? reject : domain.bind(reject); } } this._setLength(index + 1); return index; }; Promise.prototype._proxy = function (proxyable, arg) { this._addCallbacks(undefined, undefined, arg, proxyable, null); }; Promise.prototype._resolveCallback = function(value, shouldBind) { if (((this._bitField & 117506048) !== 0)) return; if (value === this) return this._rejectCallback(makeSelfResolutionError(), false); var maybePromise = tryConvertToPromise(value, this); if (!(maybePromise instanceof Promise)) return this._fulfill(value); if (shouldBind) this._propagateFrom(maybePromise, 2); var promise = maybePromise._target(); if (promise === this) { this._reject(makeSelfResolutionError()); return; } var bitField = promise._bitField; if (((bitField & 50397184) === 0)) { var len = this._length(); if (len > 0) promise._migrateCallback0(this); for (var i = 1; i < len; ++i) { promise._migrateCallbackAt(this, i); } this._setFollowing(); this._setLength(0); this._setFollowee(promise); } else if (((bitField & 33554432) !== 0)) { this._fulfill(promise._value()); } else if (((bitField & 16777216) !== 0)) { this._reject(promise._reason()); } else { var reason = new CancellationError("late cancellation observer"); promise._attachExtraTrace(reason); this._reject(reason); } }; Promise.prototype._rejectCallback = function(reason, synchronous, ignoreNonErrorWarnings) { var trace = util.ensureErrorObject(reason); var hasStack = trace === reason; if (!hasStack && !ignoreNonErrorWarnings && debug.warnings()) { var message = "a promise was rejected with a non-error: " + util.classString(reason); this._warn(message, true); } this._attachExtraTrace(trace, synchronous ? hasStack : false); this._reject(reason); }; Promise.prototype._resolveFromExecutor = function (executor) { var promise = this; this._captureStackTrace(); this._pushContext(); var synchronous = true; var r = this._execute(executor, function(value) { promise._resolveCallback(value); }, function (reason) { promise._rejectCallback(reason, synchronous); }); synchronous = false; this._popContext(); if (r !== undefined) { promise._rejectCallback(r, true); } }; Promise.prototype._settlePromiseFromHandler = function ( handler, receiver, value, promise ) { var bitField = promise._bitField; if (((bitField & 65536) !== 0)) return; promise._pushContext(); var x; if (receiver === APPLY) { if (!value || typeof value.length !== "number") { x = errorObj; x.e = new TypeError("cannot .spread() a non-array: " + util.classString(value)); } else { x = tryCatch(handler).apply(this._boundValue(), value); } } else { x = tryCatch(handler).call(receiver, value); } var promiseCreated = promise._popContext(); bitField = promise._bitField; if (((bitField & 65536) !== 0)) return; if (x === NEXT_FILTER) { promise._reject(value); } else if (x === errorObj) { promise._rejectCallback(x.e, false); } else { debug.checkForgottenReturns(x, promiseCreated, "", promise, this); promise._resolveCallback(x); } }; Promise.prototype._target = function() { var ret = this; while (ret._isFollowing()) ret = ret._followee(); return ret; }; Promise.prototype._followee = function() { return this._rejectionHandler0; }; Promise.prototype._setFollowee = function(promise) { this._rejectionHandler0 = promise; }; Promise.prototype._settlePromise = function(promise, handler, receiver, value) { var isPromise = promise instanceof Promise; var bitField = this._bitField; var asyncGuaranteed = ((bitField & 134217728) !== 0); if (((bitField & 65536) !== 0)) { if (isPromise) promise._invokeInternalOnCancel(); if (receiver instanceof PassThroughHandlerContext && receiver.isFinallyHandler()) { receiver.cancelPromise = promise; if (tryCatch(handler).call(receiver, value) === errorObj) { promise._reject(errorObj.e); } } else if (handler === reflectHandler) { promise._fulfill(reflectHandler.call(receiver)); } else if (receiver instanceof Proxyable) { receiver._promiseCancelled(promise); } else if (isPromise || promise instanceof PromiseArray) { promise._cancel(); } else { receiver.cancel(); } } else if (typeof handler === "function") { if (!isPromise) { handler.call(receiver, value, promise); } else { if (asyncGuaranteed) promise._setAsyncGuaranteed(); this._settlePromiseFromHandler(handler, receiver, value, promise); } } else if (receiver instanceof Proxyable) { if (!receiver._isResolved()) { if (((bitField & 33554432) !== 0)) { receiver._promiseFulfilled(value, promise); } else { receiver._promiseRejected(value, promise); } } } else if (isPromise) { if (asyncGuaranteed) promise._setAsyncGuaranteed(); if (((bitField & 33554432) !== 0)) { promise._fulfill(value); } else { promise._reject(value); } } }; Promise.prototype._settlePromiseLateCancellationObserver = function(ctx) { var handler = ctx.handler; var promise = ctx.promise; var receiver = ctx.receiver; var value = ctx.value; if (typeof handler === "function") { if (!(promise instanceof Promise)) { handler.call(receiver, value, promise); } else { this._settlePromiseFromHandler(handler, receiver, value, promise); } } else if (promise instanceof Promise) { promise._reject(value); } }; Promise.prototype._settlePromiseCtx = function(ctx) { this._settlePromise(ctx.promise, ctx.handler, ctx.receiver, ctx.value); }; Promise.prototype._settlePromise0 = function(handler, value, bitField) { var promise = this._promise0; var receiver = this._receiverAt(0); this._promise0 = undefined; this._receiver0 = undefined; this._settlePromise(promise, handler, receiver, value); }; Promise.prototype._clearCallbackDataAtIndex = function(index) { var base = index * 4 - 4; this[base + 2] = this[base + 3] = this[base + 0] = this[base + 1] = undefined; }; Promise.prototype._fulfill = function (value) { var bitField = this._bitField; if (((bitField & 117506048) >>> 16)) return; if (value === this) { var err = makeSelfResolutionError(); this._attachExtraTrace(err); return this._reject(err); } this._setFulfilled(); this._rejectionHandler0 = value; if ((bitField & 65535) > 0) { if (((bitField & 134217728) !== 0)) { this._settlePromises(); } else { async.settlePromises(this); } } }; Promise.prototype._reject = function (reason) { var bitField = this._bitField; if (((bitField & 117506048) >>> 16)) return; this._setRejected(); this._fulfillmentHandler0 = reason; if (this._isFinal()) { return async.fatalError(reason, util.isNode); } if ((bitField & 65535) > 0) { async.settlePromises(this); } else { this._ensurePossibleRejectionHandled(); } }; Promise.prototype._fulfillPromises = function (len, value) { for (var i = 1; i < len; i++) { var handler = this._fulfillmentHandlerAt(i); var promise = this._promiseAt(i); var receiver = this._receiverAt(i); this._clearCallbackDataAtIndex(i); this._settlePromise(promise, handler, receiver, value); } }; Promise.prototype._rejectPromises = function (len, reason) { for (var i = 1; i < len; i++) { var handler = this._rejectionHandlerAt(i); var promise = this._promiseAt(i); var receiver = this._receiverAt(i); this._clearCallbackDataAtIndex(i); this._settlePromise(promise, handler, receiver, reason); } }; Promise.prototype._settlePromises = function () { var bitField = this._bitField; var len = (bitField & 65535); if (len > 0) { if (((bitField & 16842752) !== 0)) { var reason = this._fulfillmentHandler0; this._settlePromise0(this._rejectionHandler0, reason, bitField); this._rejectPromises(len, reason); } else { var value = this._rejectionHandler0; this._settlePromise0(this._fulfillmentHandler0, value, bitField); this._fulfillPromises(len, value); } this._setLength(0); } this._clearCancellationData(); }; Promise.prototype._settledValue = function() { var bitField = this._bitField; if (((bitField & 33554432) !== 0)) { return this._rejectionHandler0; } else if (((bitField & 16777216) !== 0)) { return this._fulfillmentHandler0; } }; function deferResolve(v) {this.promise._resolveCallback(v);} function deferReject(v) {this.promise._rejectCallback(v, false);} Promise.defer = Promise.pending = function() { debug.deprecated("Promise.defer", "new Promise"); var promise = new Promise(INTERNAL); return { promise: promise, resolve: deferResolve, reject: deferReject }; }; util.notEnumerableProp(Promise, "_makeSelfResolutionError", makeSelfResolutionError); _dereq_("./method")(Promise, INTERNAL, tryConvertToPromise, apiRejection, debug); _dereq_("./bind")(Promise, INTERNAL, tryConvertToPromise, debug); _dereq_("./cancel")(Promise, PromiseArray, apiRejection, debug); _dereq_("./direct_resolve")(Promise); _dereq_("./synchronous_inspection")(Promise); _dereq_("./join")( Promise, PromiseArray, tryConvertToPromise, INTERNAL, debug); Promise.Promise = Promise; _dereq_('./map.js')(Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL, debug); _dereq_('./using.js')(Promise, apiRejection, tryConvertToPromise, createContext, INTERNAL, debug); _dereq_('./timers.js')(Promise, INTERNAL, debug); _dereq_('./generators.js')(Promise, apiRejection, INTERNAL, tryConvertToPromise, Proxyable, debug); _dereq_('./nodeify.js')(Promise); _dereq_('./call_get.js')(Promise); _dereq_('./props.js')(Promise, PromiseArray, tryConvertToPromise, apiRejection); _dereq_('./race.js')(Promise, INTERNAL, tryConvertToPromise, apiRejection); _dereq_('./reduce.js')(Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL, debug); _dereq_('./settle.js')(Promise, PromiseArray, debug); _dereq_('./some.js')(Promise, PromiseArray, apiRejection); _dereq_('./promisify.js')(Promise, INTERNAL); _dereq_('./any.js')(Promise); _dereq_('./each.js')(Promise, INTERNAL); _dereq_('./filter.js')(Promise, INTERNAL); util.toFastProperties(Promise); util.toFastProperties(Promise.prototype); function fillTypes(value) { var p = new Promise(INTERNAL); p._fulfillmentHandler0 = value; p._rejectionHandler0 = value; p._promise0 = value; p._receiver0 = value; } // Complete slack tracking, opt out of field-type tracking and // stabilize map fillTypes({a: 1}); fillTypes({b: 2}); fillTypes({c: 3}); fillTypes(1); fillTypes(function(){}); fillTypes(undefined); fillTypes(false); fillTypes(new Promise(INTERNAL)); debug.setBounds(Async.firstLineError, util.lastLineError); return Promise; }; },{"./any.js":1,"./async":2,"./bind":3,"./call_get.js":5,"./cancel":6,"./catch_filter":7,"./context":8,"./debuggability":9,"./direct_resolve":10,"./each.js":11,"./errors":12,"./es5":13,"./filter.js":14,"./finally":15,"./generators.js":16,"./join":17,"./map.js":18,"./method":19,"./nodeback":20,"./nodeify.js":21,"./promise_array":23,"./promisify.js":24,"./props.js":25,"./race.js":27,"./reduce.js":28,"./settle.js":30,"./some.js":31,"./synchronous_inspection":32,"./thenables":33,"./timers.js":34,"./using.js":35,"./util":36}],23:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise, INTERNAL, tryConvertToPromise, apiRejection, Proxyable) { var util = _dereq_("./util"); var isArray = util.isArray; function toResolutionValue(val) { switch(val) { case -2: return []; case -3: return {}; } } function PromiseArray(values) { var promise = this._promise = new Promise(INTERNAL); if (values instanceof Promise) { promise._propagateFrom(values, 3); } promise._setOnCancel(this); this._values = values; this._length = 0; this._totalResolved = 0; this._init(undefined, -2); } util.inherits(PromiseArray, Proxyable); PromiseArray.prototype.length = function () { return this._length; }; PromiseArray.prototype.promise = function () { return this._promise; }; PromiseArray.prototype._init = function init(_, resolveValueIfEmpty) { var values = tryConvertToPromise(this._values, this._promise); if (values instanceof Promise) { values = values._target(); var bitField = values._bitField; ; this._values = values; if (((bitField & 50397184) === 0)) { this._promise._setAsyncGuaranteed(); return values._then( init, this._reject, undefined, this, resolveValueIfEmpty ); } else if (((bitField & 33554432) !== 0)) { values = values._value(); } else if (((bitField & 16777216) !== 0)) { return this._reject(values._reason()); } else { return this._cancel(); } } values = util.asArray(values); if (values === null) { var err = apiRejection( "expecting an array or an iterable object but got " + util.classString(values)).reason(); this._promise._rejectCallback(err, false); return; } if (values.length === 0) { if (resolveValueIfEmpty === -5) { this._resolveEmptyArray(); } else { this._resolve(toResolutionValue(resolveValueIfEmpty)); } return; } this._iterate(values); }; PromiseArray.prototype._iterate = function(values) { var len = this.getActualLength(values.length); this._length = len; this._values = this.shouldCopyValues() ? new Array(len) : this._values; var result = this._promise; var isResolved = false; var bitField = null; for (var i = 0; i < len; ++i) { var maybePromise = tryConvertToPromise(values[i], result); if (maybePromise instanceof Promise) { maybePromise = maybePromise._target(); bitField = maybePromise._bitField; } else { bitField = null; } if (isResolved) { if (bitField !== null) { maybePromise.suppressUnhandledRejections(); } } else if (bitField !== null) { if (((bitField & 50397184) === 0)) { maybePromise._proxy(this, i); this._values[i] = maybePromise; } else if (((bitField & 33554432) !== 0)) { isResolved = this._promiseFulfilled(maybePromise._value(), i); } else if (((bitField & 16777216) !== 0)) { isResolved = this._promiseRejected(maybePromise._reason(), i); } else { isResolved = this._promiseCancelled(i); } } else { isResolved = this._promiseFulfilled(maybePromise, i); } } if (!isResolved) result._setAsyncGuaranteed(); }; PromiseArray.prototype._isResolved = function () { return this._values === null; }; PromiseArray.prototype._resolve = function (value) { this._values = null; this._promise._fulfill(value); }; PromiseArray.prototype._cancel = function() { if (this._isResolved() || !this._promise.isCancellable()) return; this._values = null; this._promise._cancel(); }; PromiseArray.prototype._reject = function (reason) { this._values = null; this._promise._rejectCallback(reason, false); }; PromiseArray.prototype._promiseFulfilled = function (value, index) { this._values[index] = value; var totalResolved = ++this._totalResolved; if (totalResolved >= this._length) { this._resolve(this._values); return true; } return false; }; PromiseArray.prototype._promiseCancelled = function() { this._cancel(); return true; }; PromiseArray.prototype._promiseRejected = function (reason) { this._totalResolved++; this._reject(reason); return true; }; PromiseArray.prototype._resultCancelled = function() { if (this._isResolved()) return; var values = this._values; this._cancel(); if (values instanceof Promise) { values.cancel(); } else { for (var i = 0; i < values.length; ++i) { if (values[i] instanceof Promise) { values[i].cancel(); } } } }; PromiseArray.prototype.shouldCopyValues = function () { return true; }; PromiseArray.prototype.getActualLength = function (len) { return len; }; return PromiseArray; }; },{"./util":36}],24:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise, INTERNAL) { var THIS = {}; var util = _dereq_("./util"); var nodebackForPromise = _dereq_("./nodeback"); var withAppended = util.withAppended; var maybeWrapAsError = util.maybeWrapAsError; var canEvaluate = util.canEvaluate; var TypeError = _dereq_("./errors").TypeError; var defaultSuffix = "Async"; var defaultPromisified = {__isPromisified__: true}; var noCopyProps = [ "arity", "length", "name", "arguments", "caller", "callee", "prototype", "__isPromisified__" ]; var noCopyPropsPattern = new RegExp("^(?:" + noCopyProps.join("|") + ")$"); var defaultFilter = function(name) { return util.isIdentifier(name) && name.charAt(0) !== "_" && name !== "constructor"; }; function propsFilter(key) { return !noCopyPropsPattern.test(key); } function isPromisified(fn) { try { return fn.__isPromisified__ === true; } catch (e) { return false; } } function hasPromisified(obj, key, suffix) { var val = util.getDataPropertyOrDefault(obj, key + suffix, defaultPromisified); return val ? isPromisified(val) : false; } function checkValid(ret, suffix, suffixRegexp) { for (var i = 0; i < ret.length; i += 2) { var key = ret[i]; if (suffixRegexp.test(key)) { var keyWithoutAsyncSuffix = key.replace(suffixRegexp, ""); for (var j = 0; j < ret.length; j += 2) { if (ret[j] === keyWithoutAsyncSuffix) { throw new TypeError("Cannot promisify an API that has normal methods with '%s'-suffix\u000a\u000a See http://goo.gl/MqrFmX\u000a" .replace("%s", suffix)); } } } } } function promisifiableMethods(obj, suffix, suffixRegexp, filter) { var keys = util.inheritedDataKeys(obj); var ret = []; for (var i = 0; i < keys.length; ++i) { var key = keys[i]; var value = obj[key]; var passesDefaultFilter = filter === defaultFilter ? true : defaultFilter(key, value, obj); if (typeof value === "function" && !isPromisified(value) && !hasPromisified(obj, key, suffix) && filter(key, value, obj, passesDefaultFilter)) { ret.push(key, value); } } checkValid(ret, suffix, suffixRegexp); return ret; } var escapeIdentRegex = function(str) { return str.replace(/([$])/, "\\$"); }; var makeNodePromisifiedEval; if (!true) { var switchCaseArgumentOrder = function(likelyArgumentCount) { var ret = [likelyArgumentCount]; var min = Math.max(0, likelyArgumentCount - 1 - 3); for(var i = likelyArgumentCount - 1; i >= min; --i) { ret.push(i); } for(var i = likelyArgumentCount + 1; i <= 3; ++i) { ret.push(i); } return ret; }; var argumentSequence = function(argumentCount) { return util.filledRange(argumentCount, "_arg", ""); }; var parameterDeclaration = function(parameterCount) { return util.filledRange( Math.max(parameterCount, 3), "_arg", ""); }; var parameterCount = function(fn) { if (typeof fn.length === "number") { return Math.max(Math.min(fn.length, 1023 + 1), 0); } return 0; }; makeNodePromisifiedEval = function(callback, receiver, originalName, fn, _, multiArgs) { var newParameterCount = Math.max(0, parameterCount(fn) - 1); var argumentOrder = switchCaseArgumentOrder(newParameterCount); var shouldProxyThis = typeof callback === "string" || receiver === THIS; function generateCallForArgumentCount(count) { var args = argumentSequence(count).join(", "); var comma = count > 0 ? ", " : ""; var ret; if (shouldProxyThis) { ret = "ret = callback.call(this, {{args}}, nodeback); break;\n"; } else { ret = receiver === undefined ? "ret = callback({{args}}, nodeback); break;\n" : "ret = callback.call(receiver, {{args}}, nodeback); break;\n"; } return ret.replace("{{args}}", args).replace(", ", comma); } function generateArgumentSwitchCase() { var ret = ""; for (var i = 0; i < argumentOrder.length; ++i) { ret += "case " + argumentOrder[i] +":" + generateCallForArgumentCount(argumentOrder[i]); } ret += " \n\ default: \n\ var args = new Array(len + 1); \n\ var i = 0; \n\ for (var i = 0; i < len; ++i) { \n\ args[i] = arguments[i]; \n\ } \n\ args[i] = nodeback; \n\ [CodeForCall] \n\ break; \n\ ".replace("[CodeForCall]", (shouldProxyThis ? "ret = callback.apply(this, args);\n" : "ret = callback.apply(receiver, args);\n")); return ret; } var getFunctionCode = typeof callback === "string" ? ("this != null ? this['"+callback+"'] : fn") : "fn"; var body = "'use strict'; \n\ var ret = function (Parameters) { \n\ 'use strict'; \n\ var len = arguments.length; \n\ var promise = new Promise(INTERNAL); \n\ promise._captureStackTrace(); \n\ var nodeback = nodebackForPromise(promise, " + multiArgs + "); \n\ var ret; \n\ var callback = tryCatch([GetFunctionCode]); \n\ switch(len) { \n\ [CodeForSwitchCase] \n\ } \n\ if (ret === errorObj) { \n\ promise._rejectCallback(maybeWrapAsError(ret.e), true, true);\n\ } \n\ if (!promise._isFateSealed()) promise._setAsyncGuaranteed(); \n\ return promise; \n\ }; \n\ notEnumerableProp(ret, '__isPromisified__', true); \n\ return ret; \n\ ".replace("[CodeForSwitchCase]", generateArgumentSwitchCase()) .replace("[GetFunctionCode]", getFunctionCode); body = body.replace("Parameters", parameterDeclaration(newParameterCount)); return new Function("Promise", "fn", "receiver", "withAppended", "maybeWrapAsError", "nodebackForPromise", "tryCatch", "errorObj", "notEnumerableProp", "INTERNAL", body)( Promise, fn, receiver, withAppended, maybeWrapAsError, nodebackForPromise, util.tryCatch, util.errorObj, util.notEnumerableProp, INTERNAL); }; } function makeNodePromisifiedClosure(callback, receiver, _, fn, __, multiArgs) { var defaultThis = (function() {return this;})(); var method = callback; if (typeof method === "string") { callback = fn; } function promisified() { var _receiver = receiver; if (receiver === THIS) _receiver = this; var promise = new Promise(INTERNAL); promise._captureStackTrace(); var cb = typeof method === "string" && this !== defaultThis ? this[method] : callback; var fn = nodebackForPromise(promise, multiArgs); try { cb.apply(_receiver, withAppended(arguments, fn)); } catch(e) { promise._rejectCallback(maybeWrapAsError(e), true, true); } if (!promise._isFateSealed()) promise._setAsyncGuaranteed(); return promise; } util.notEnumerableProp(promisified, "__isPromisified__", true); return promisified; } var makeNodePromisified = canEvaluate ? makeNodePromisifiedEval : makeNodePromisifiedClosure; function promisifyAll(obj, suffix, filter, promisifier, multiArgs) { var suffixRegexp = new RegExp(escapeIdentRegex(suffix) + "$"); var methods = promisifiableMethods(obj, suffix, suffixRegexp, filter); for (var i = 0, len = methods.length; i < len; i+= 2) { var key = methods[i]; var fn = methods[i+1]; var promisifiedKey = key + suffix; if (promisifier === makeNodePromisified) { obj[promisifiedKey] = makeNodePromisified(key, THIS, key, fn, suffix, multiArgs); } else { var promisified = promisifier(fn, function() { return makeNodePromisified(key, THIS, key, fn, suffix, multiArgs); }); util.notEnumerableProp(promisified, "__isPromisified__", true); obj[promisifiedKey] = promisified; } } util.toFastProperties(obj); return obj; } function promisify(callback, receiver, multiArgs) { return makeNodePromisified(callback, receiver, undefined, callback, null, multiArgs); } Promise.promisify = function (fn, options) { if (typeof fn !== "function") { throw new TypeError("expecting a function but got " + util.classString(fn)); } if (isPromisified(fn)) { return fn; } options = Object(options); var receiver = options.context === undefined ? THIS : options.context; var multiArgs = !!options.multiArgs; var ret = promisify(fn, receiver, multiArgs); util.copyDescriptors(fn, ret, propsFilter); return ret; }; Promise.promisifyAll = function (target, options) { if (typeof target !== "function" && typeof target !== "object") { throw new TypeError("the target of promisifyAll must be an object or a function\u000a\u000a See http://goo.gl/MqrFmX\u000a"); } options = Object(options); var multiArgs = !!options.multiArgs; var suffix = options.suffix; if (typeof suffix !== "string") suffix = defaultSuffix; var filter = options.filter; if (typeof filter !== "function") filter = defaultFilter; var promisifier = options.promisifier; if (typeof promisifier !== "function") promisifier = makeNodePromisified; if (!util.isIdentifier(suffix)) { throw new RangeError("suffix must be a valid identifier\u000a\u000a See http://goo.gl/MqrFmX\u000a"); } var keys = util.inheritedDataKeys(target); for (var i = 0; i < keys.length; ++i) { var value = target[keys[i]]; if (keys[i] !== "constructor" && util.isClass(value)) { promisifyAll(value.prototype, suffix, filter, promisifier, multiArgs); promisifyAll(value, suffix, filter, promisifier, multiArgs); } } return promisifyAll(target, suffix, filter, promisifier, multiArgs); }; }; },{"./errors":12,"./nodeback":20,"./util":36}],25:[function(_dereq_,module,exports){ "use strict"; module.exports = function( Promise, PromiseArray, tryConvertToPromise, apiRejection) { var util = _dereq_("./util"); var isObject = util.isObject; var es5 = _dereq_("./es5"); var Es6Map; if (typeof Map === "function") Es6Map = Map; var mapToEntries = (function() { var index = 0; var size = 0; function extractEntry(value, key) { this[index] = value; this[index + size] = key; index++; } return function mapToEntries(map) { size = map.size; index = 0; var ret = new Array(map.size * 2); map.forEach(extractEntry, ret); return ret; }; })(); var entriesToMap = function(entries) { var ret = new Es6Map(); var length = entries.length / 2 | 0; for (var i = 0; i < length; ++i) { var key = entries[length + i]; var value = entries[i]; ret.set(key, value); } return ret; }; function PropertiesPromiseArray(obj) { var isMap = false; var entries; if (Es6Map !== undefined && obj instanceof Es6Map) { entries = mapToEntries(obj); isMap = true; } else { var keys = es5.keys(obj); var len = keys.length; entries = new Array(len * 2); for (var i = 0; i < len; ++i) { var key = keys[i]; entries[i] = obj[key]; entries[i + len] = key; } } this.constructor$(entries); this._isMap = isMap; this._init$(undefined, -3); } util.inherits(PropertiesPromiseArray, PromiseArray); PropertiesPromiseArray.prototype._init = function () {}; PropertiesPromiseArray.prototype._promiseFulfilled = function (value, index) { this._values[index] = value; var totalResolved = ++this._totalResolved; if (totalResolved >= this._length) { var val; if (this._isMap) { val = entriesToMap(this._values); } else { val = {}; var keyOffset = this.length(); for (var i = 0, len = this.length(); i < len; ++i) { val[this._values[i + keyOffset]] = this._values[i]; } } this._resolve(val); return true; } return false; }; PropertiesPromiseArray.prototype.shouldCopyValues = function () { return false; }; PropertiesPromiseArray.prototype.getActualLength = function (len) { return len >> 1; }; function props(promises) { var ret; var castValue = tryConvertToPromise(promises); if (!isObject(castValue)) { return apiRejection("cannot await properties of a non-object\u000a\u000a See http://goo.gl/MqrFmX\u000a"); } else if (castValue instanceof Promise) { ret = castValue._then( Promise.props, undefined, undefined, undefined, undefined); } else { ret = new PropertiesPromiseArray(castValue).promise(); } if (castValue instanceof Promise) { ret._propagateFrom(castValue, 2); } return ret; } Promise.prototype.props = function () { return props(this); }; Promise.props = function (promises) { return props(promises); }; }; },{"./es5":13,"./util":36}],26:[function(_dereq_,module,exports){ "use strict"; function arrayMove(src, srcIndex, dst, dstIndex, len) { for (var j = 0; j < len; ++j) { dst[j + dstIndex] = src[j + srcIndex]; src[j + srcIndex] = void 0; } } function Queue(capacity) { this._capacity = capacity; this._length = 0; this._front = 0; } Queue.prototype._willBeOverCapacity = function (size) { return this._capacity < size; }; Queue.prototype._pushOne = function (arg) { var length = this.length(); this._checkCapacity(length + 1); var i = (this._front + length) & (this._capacity - 1); this[i] = arg; this._length = length + 1; }; Queue.prototype._unshiftOne = function(value) { var capacity = this._capacity; this._checkCapacity(this.length() + 1); var front = this._front; var i = (((( front - 1 ) & ( capacity - 1) ) ^ capacity ) - capacity ); this[i] = value; this._front = i; this._length = this.length() + 1; }; Queue.prototype.unshift = function(fn, receiver, arg) { this._unshiftOne(arg); this._unshiftOne(receiver); this._unshiftOne(fn); }; Queue.prototype.push = function (fn, receiver, arg) { var length = this.length() + 3; if (this._willBeOverCapacity(length)) { this._pushOne(fn); this._pushOne(receiver); this._pushOne(arg); return; } var j = this._front + length - 3; this._checkCapacity(length); var wrapMask = this._capacity - 1; this[(j + 0) & wrapMask] = fn; this[(j + 1) & wrapMask] = receiver; this[(j + 2) & wrapMask] = arg; this._length = length; }; Queue.prototype.shift = function () { var front = this._front, ret = this[front]; this[front] = undefined; this._front = (front + 1) & (this._capacity - 1); this._length--; return ret; }; Queue.prototype.length = function () { return this._length; }; Queue.prototype._checkCapacity = function (size) { if (this._capacity < size) { this._resizeTo(this._capacity << 1); } }; Queue.prototype._resizeTo = function (capacity) { var oldCapacity = this._capacity; this._capacity = capacity; var front = this._front; var length = this._length; var moveItemsCount = (front + length) & (oldCapacity - 1); arrayMove(this, 0, this, oldCapacity, moveItemsCount); }; module.exports = Queue; },{}],27:[function(_dereq_,module,exports){ "use strict"; module.exports = function( Promise, INTERNAL, tryConvertToPromise, apiRejection) { var util = _dereq_("./util"); var raceLater = function (promise) { return promise.then(function(array) { return race(array, promise); }); }; function race(promises, parent) { var maybePromise = tryConvertToPromise(promises); if (maybePromise instanceof Promise) { return raceLater(maybePromise); } else { promises = util.asArray(promises); if (promises === null) return apiRejection("expecting an array or an iterable object but got " + util.classString(promises)); } var ret = new Promise(INTERNAL); if (parent !== undefined) { ret._propagateFrom(parent, 3); } var fulfill = ret._fulfill; var reject = ret._reject; for (var i = 0, len = promises.length; i < len; ++i) { var val = promises[i]; if (val === undefined && !(i in promises)) { continue; } Promise.cast(val)._then(fulfill, reject, undefined, ret, null); } return ret; } Promise.race = function (promises) { return race(promises, undefined); }; Promise.prototype.race = function () { return race(this, undefined); }; }; },{"./util":36}],28:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL, debug) { var getDomain = Promise._getDomain; var util = _dereq_("./util"); var tryCatch = util.tryCatch; function ReductionPromiseArray(promises, fn, initialValue, _each) { this.constructor$(promises); var domain = getDomain(); this._fn = domain === null ? fn : domain.bind(fn); if (initialValue !== undefined) { initialValue = Promise.resolve(initialValue); initialValue._attachCancellationCallback(this); } this._initialValue = initialValue; this._currentCancellable = null; this._eachValues = _each === INTERNAL ? [] : undefined; this._promise._captureStackTrace(); this._init$(undefined, -5); } util.inherits(ReductionPromiseArray, PromiseArray); ReductionPromiseArray.prototype._gotAccum = function(accum) { if (this._eachValues !== undefined && accum !== INTERNAL) { this._eachValues.push(accum); } }; ReductionPromiseArray.prototype._eachComplete = function(value) { this._eachValues.push(value); return this._eachValues; }; ReductionPromiseArray.prototype._init = function() {}; ReductionPromiseArray.prototype._resolveEmptyArray = function() { this._resolve(this._eachValues !== undefined ? this._eachValues : this._initialValue); }; ReductionPromiseArray.prototype.shouldCopyValues = function () { return false; }; ReductionPromiseArray.prototype._resolve = function(value) { this._promise._resolveCallback(value); this._values = null; }; ReductionPromiseArray.prototype._resultCancelled = function(sender) { if (sender === this._initialValue) return this._cancel(); if (this._isResolved()) return; this._resultCancelled$(); if (this._currentCancellable instanceof Promise) { this._currentCancellable.cancel(); } if (this._initialValue instanceof Promise) { this._initialValue.cancel(); } }; ReductionPromiseArray.prototype._iterate = function (values) { this._values = values; var value; var i; var length = values.length; if (this._initialValue !== undefined) { value = this._initialValue; i = 0; } else { value = Promise.resolve(values[0]); i = 1; } this._currentCancellable = value; if (!value.isRejected()) { for (; i < length; ++i) { var ctx = { accum: null, value: values[i], index: i, length: length, array: this }; value = value._then(gotAccum, undefined, undefined, ctx, undefined); } } if (this._eachValues !== undefined) { value = value ._then(this._eachComplete, undefined, undefined, this, undefined); } value._then(completed, completed, undefined, value, this); }; Promise.prototype.reduce = function (fn, initialValue) { return reduce(this, fn, initialValue, null); }; Promise.reduce = function (promises, fn, initialValue, _each) { return reduce(promises, fn, initialValue, _each); }; function completed(valueOrReason, array) { if (this.isFulfilled()) { array._resolve(valueOrReason); } else { array._reject(valueOrReason); } } function reduce(promises, fn, initialValue, _each) { if (typeof fn !== "function") { return apiRejection("expecting a function but got " + util.classString(fn)); } var array = new ReductionPromiseArray(promises, fn, initialValue, _each); return array.promise(); } function gotAccum(accum) { this.accum = accum; this.array._gotAccum(accum); var value = tryConvertToPromise(this.value, this.array._promise); if (value instanceof Promise) { this.array._currentCancellable = value; return value._then(gotValue, undefined, undefined, this, undefined); } else { return gotValue.call(this, value); } } function gotValue(value) { var array = this.array; var promise = array._promise; var fn = tryCatch(array._fn); promise._pushContext(); var ret; if (array._eachValues !== undefined) { ret = fn.call(promise._boundValue(), value, this.index, this.length); } else { ret = fn.call(promise._boundValue(), this.accum, value, this.index, this.length); } if (ret instanceof Promise) { array._currentCancellable = ret; } var promiseCreated = promise._popContext(); debug.checkForgottenReturns( ret, promiseCreated, array._eachValues !== undefined ? "Promise.each" : "Promise.reduce", promise ); return ret; } }; },{"./util":36}],29:[function(_dereq_,module,exports){ "use strict"; var util = _dereq_("./util"); var schedule; var noAsyncScheduler = function() { throw new Error("No async scheduler available\u000a\u000a See http://goo.gl/MqrFmX\u000a"); }; if (util.isNode && typeof MutationObserver === "undefined") { var GlobalSetImmediate = global.setImmediate; var ProcessNextTick = process.nextTick; schedule = util.isRecentNode ? function(fn) { GlobalSetImmediate.call(global, fn); } : function(fn) { ProcessNextTick.call(process, fn); }; } else if ((typeof MutationObserver !== "undefined") && !(typeof window !== "undefined" && window.navigator && window.navigator.standalone)) { schedule = (function() { var div = document.createElement("div"); var opts = {attributes: true}; var toggleScheduled = false; var div2 = document.createElement("div"); var o2 = new MutationObserver(function() { div.classList.toggle("foo"); toggleScheduled = false; }); o2.observe(div2, opts); var scheduleToggle = function() { if (toggleScheduled) return; toggleScheduled = true; div2.classList.toggle("foo"); }; return function schedule(fn) { var o = new MutationObserver(function() { o.disconnect(); fn(); }); o.observe(div, opts); scheduleToggle(); }; })(); } else if (typeof setImmediate !== "undefined") { schedule = function (fn) { setImmediate(fn); }; } else if (typeof setTimeout !== "undefined") { schedule = function (fn) { setTimeout(fn, 0); }; } else { schedule = noAsyncScheduler; } module.exports = schedule; },{"./util":36}],30:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise, PromiseArray, debug) { var PromiseInspection = Promise.PromiseInspection; var util = _dereq_("./util"); function SettledPromiseArray(values) { this.constructor$(values); } util.inherits(SettledPromiseArray, PromiseArray); SettledPromiseArray.prototype._promiseResolved = function (index, inspection) { this._values[index] = inspection; var totalResolved = ++this._totalResolved; if (totalResolved >= this._length) { this._resolve(this._values); return true; } return false; }; SettledPromiseArray.prototype._promiseFulfilled = function (value, index) { var ret = new PromiseInspection(); ret._bitField = 33554432; ret._settledValueField = value; return this._promiseResolved(index, ret); }; SettledPromiseArray.prototype._promiseRejected = function (reason, index) { var ret = new PromiseInspection(); ret._bitField = 16777216; ret._settledValueField = reason; return this._promiseResolved(index, ret); }; Promise.settle = function (promises) { debug.deprecated(".settle()", ".reflect()"); return new SettledPromiseArray(promises).promise(); }; Promise.prototype.settle = function () { return Promise.settle(this); }; }; },{"./util":36}],31:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise, PromiseArray, apiRejection) { var util = _dereq_("./util"); var RangeError = _dereq_("./errors").RangeError; var AggregateError = _dereq_("./errors").AggregateError; var isArray = util.isArray; var CANCELLATION = {}; function SomePromiseArray(values) { this.constructor$(values); this._howMany = 0; this._unwrap = false; this._initialized = false; } util.inherits(SomePromiseArray, PromiseArray); SomePromiseArray.prototype._init = function () { if (!this._initialized) { return; } if (this._howMany === 0) { this._resolve([]); return; } this._init$(undefined, -5); var isArrayResolved = isArray(this._values); if (!this._isResolved() && isArrayResolved && this._howMany > this._canPossiblyFulfill()) { this._reject(this._getRangeError(this.length())); } }; SomePromiseArray.prototype.init = function () { this._initialized = true; this._init(); }; SomePromiseArray.prototype.setUnwrap = function () { this._unwrap = true; }; SomePromiseArray.prototype.howMany = function () { return this._howMany; }; SomePromiseArray.prototype.setHowMany = function (count) { this._howMany = count; }; SomePromiseArray.prototype._promiseFulfilled = function (value) { this._addFulfilled(value); if (this._fulfilled() === this.howMany()) { this._values.length = this.howMany(); if (this.howMany() === 1 && this._unwrap) { this._resolve(this._values[0]); } else { this._resolve(this._values); } return true; } return false; }; SomePromiseArray.prototype._promiseRejected = function (reason) { this._addRejected(reason); return this._checkOutcome(); }; SomePromiseArray.prototype._promiseCancelled = function () { if (this._values instanceof Promise || this._values == null) { return this._cancel(); } this._addRejected(CANCELLATION); return this._checkOutcome(); }; SomePromiseArray.prototype._checkOutcome = function() { if (this.howMany() > this._canPossiblyFulfill()) { var e = new AggregateError(); for (var i = this.length(); i < this._values.length; ++i) { if (this._values[i] !== CANCELLATION) { e.push(this._values[i]); } } if (e.length > 0) { this._reject(e); } else { this._cancel(); } return true; } return false; }; SomePromiseArray.prototype._fulfilled = function () { return this._totalResolved; }; SomePromiseArray.prototype._rejected = function () { return this._values.length - this.length(); }; SomePromiseArray.prototype._addRejected = function (reason) { this._values.push(reason); }; SomePromiseArray.prototype._addFulfilled = function (value) { this._values[this._totalResolved++] = value; }; SomePromiseArray.prototype._canPossiblyFulfill = function () { return this.length() - this._rejected(); }; SomePromiseArray.prototype._getRangeError = function (count) { var message = "Input array must contain at least " + this._howMany + " items but contains only " + count + " items"; return new RangeError(message); }; SomePromiseArray.prototype._resolveEmptyArray = function () { this._reject(this._getRangeError(0)); }; function some(promises, howMany) { if ((howMany | 0) !== howMany || howMany < 0) { return apiRejection("expecting a positive integer\u000a\u000a See http://goo.gl/MqrFmX\u000a"); } var ret = new SomePromiseArray(promises); var promise = ret.promise(); ret.setHowMany(howMany); ret.init(); return promise; } Promise.some = function (promises, howMany) { return some(promises, howMany); }; Promise.prototype.some = function (howMany) { return some(this, howMany); }; Promise._SomePromiseArray = SomePromiseArray; }; },{"./errors":12,"./util":36}],32:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise) { function PromiseInspection(promise) { if (promise !== undefined) { promise = promise._target(); this._bitField = promise._bitField; this._settledValueField = promise._isFateSealed() ? promise._settledValue() : undefined; } else { this._bitField = 0; this._settledValueField = undefined; } } PromiseInspection.prototype._settledValue = function() { return this._settledValueField; }; var value = PromiseInspection.prototype.value = function () { if (!this.isFulfilled()) { throw new TypeError("cannot get fulfillment value of a non-fulfilled promise\u000a\u000a See http://goo.gl/MqrFmX\u000a"); } return this._settledValue(); }; var reason = PromiseInspection.prototype.error = PromiseInspection.prototype.reason = function () { if (!this.isRejected()) { throw new TypeError("cannot get rejection reason of a non-rejected promise\u000a\u000a See http://goo.gl/MqrFmX\u000a"); } return this._settledValue(); }; var isFulfilled = PromiseInspection.prototype.isFulfilled = function() { return (this._bitField & 33554432) !== 0; }; var isRejected = PromiseInspection.prototype.isRejected = function () { return (this._bitField & 16777216) !== 0; }; var isPending = PromiseInspection.prototype.isPending = function () { return (this._bitField & 50397184) === 0; }; var isResolved = PromiseInspection.prototype.isResolved = function () { return (this._bitField & 50331648) !== 0; }; PromiseInspection.prototype.isCancelled = Promise.prototype._isCancelled = function() { return (this._bitField & 65536) === 65536; }; Promise.prototype.isCancelled = function() { return this._target()._isCancelled(); }; Promise.prototype.isPending = function() { return isPending.call(this._target()); }; Promise.prototype.isRejected = function() { return isRejected.call(this._target()); }; Promise.prototype.isFulfilled = function() { return isFulfilled.call(this._target()); }; Promise.prototype.isResolved = function() { return isResolved.call(this._target()); }; Promise.prototype.value = function() { return value.call(this._target()); }; Promise.prototype.reason = function() { var target = this._target(); target._unsetRejectionIsUnhandled(); return reason.call(target); }; Promise.prototype._value = function() { return this._settledValue(); }; Promise.prototype._reason = function() { this._unsetRejectionIsUnhandled(); return this._settledValue(); }; Promise.PromiseInspection = PromiseInspection; }; },{}],33:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise, INTERNAL) { var util = _dereq_("./util"); var errorObj = util.errorObj; var isObject = util.isObject; function tryConvertToPromise(obj, context) { if (isObject(obj)) { if (obj instanceof Promise) return obj; var then = getThen(obj); if (then === errorObj) { if (context) context._pushContext(); var ret = Promise.reject(then.e); if (context) context._popContext(); return ret; } else if (typeof then === "function") { if (isAnyBluebirdPromise(obj)) { var ret = new Promise(INTERNAL); obj._then( ret._fulfill, ret._reject, undefined, ret, null ); return ret; } return doThenable(obj, then, context); } } return obj; } function doGetThen(obj) { return obj.then; } function getThen(obj) { try { return doGetThen(obj); } catch (e) { errorObj.e = e; return errorObj; } } var hasProp = {}.hasOwnProperty; function isAnyBluebirdPromise(obj) { return hasProp.call(obj, "_promise0"); } function doThenable(x, then, context) { var promise = new Promise(INTERNAL); var ret = promise; if (context) context._pushContext(); promise._captureStackTrace(); if (context) context._popContext(); var synchronous = true; var result = util.tryCatch(then).call(x, resolve, reject); synchronous = false; if (promise && result === errorObj) { promise._rejectCallback(result.e, true, true); promise = null; } function resolve(value) { if (!promise) return; promise._resolveCallback(value); promise = null; } function reject(reason) { if (!promise) return; promise._rejectCallback(reason, synchronous, true); promise = null; } return ret; } return tryConvertToPromise; }; },{"./util":36}],34:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise, INTERNAL, debug) { var util = _dereq_("./util"); var TimeoutError = Promise.TimeoutError; function HandleWrapper(handle) { this.handle = handle; } HandleWrapper.prototype._resultCancelled = function() { clearTimeout(this.handle); }; var afterValue = function(value) { return delay(+this).thenReturn(value); }; var delay = Promise.delay = function (ms, value) { var ret; var handle; if (value !== undefined) { ret = Promise.resolve(value) ._then(afterValue, null, null, ms, undefined); if (debug.cancellation() && value instanceof Promise) { ret._setOnCancel(value); } } else { ret = new Promise(INTERNAL); handle = setTimeout(function() { ret._fulfill(); }, +ms); if (debug.cancellation()) { ret._setOnCancel(new HandleWrapper(handle)); } } ret._setAsyncGuaranteed(); return ret; }; Promise.prototype.delay = function (ms) { return delay(ms, this); }; var afterTimeout = function (promise, message, parent) { var err; if (typeof message !== "string") { if (message instanceof Error) { err = message; } else { err = new TimeoutError("operation timed out"); } } else { err = new TimeoutError(message); } util.markAsOriginatingFromRejection(err); promise._attachExtraTrace(err); promise._reject(err); if (parent != null) { parent.cancel(); } }; function successClear(value) { clearTimeout(this.handle); return value; } function failureClear(reason) { clearTimeout(this.handle); throw reason; } Promise.prototype.timeout = function (ms, message) { ms = +ms; var ret, parent; var handleWrapper = new HandleWrapper(setTimeout(function timeoutTimeout() { if (ret.isPending()) { afterTimeout(ret, message, parent); } }, ms)); if (debug.cancellation()) { parent = this.then(); ret = parent._then(successClear, failureClear, undefined, handleWrapper, undefined); ret._setOnCancel(handleWrapper); } else { ret = this._then(successClear, failureClear, undefined, handleWrapper, undefined); } return ret; }; }; },{"./util":36}],35:[function(_dereq_,module,exports){ "use strict"; module.exports = function (Promise, apiRejection, tryConvertToPromise, createContext, INTERNAL, debug) { var util = _dereq_("./util"); var TypeError = _dereq_("./errors").TypeError; var inherits = _dereq_("./util").inherits; var errorObj = util.errorObj; var tryCatch = util.tryCatch; function thrower(e) { setTimeout(function(){throw e;}, 0); } function castPreservingDisposable(thenable) { var maybePromise = tryConvertToPromise(thenable); if (maybePromise !== thenable && typeof thenable._isDisposable === "function" && typeof thenable._getDisposer === "function" && thenable._isDisposable()) { maybePromise._setDisposable(thenable._getDisposer()); } return maybePromise; } function dispose(resources, inspection) { var i = 0; var len = resources.length; var ret = new Promise(INTERNAL); function iterator() { if (i >= len) return ret._fulfill(); var maybePromise = castPreservingDisposable(resources[i++]); if (maybePromise instanceof Promise && maybePromise._isDisposable()) { try { maybePromise = tryConvertToPromise( maybePromise._getDisposer().tryDispose(inspection), resources.promise); } catch (e) { return thrower(e); } if (maybePromise instanceof Promise) { return maybePromise._then(iterator, thrower, null, null, null); } } iterator(); } iterator(); return ret; } function Disposer(data, promise, context) { this._data = data; this._promise = promise; this._context = context; } Disposer.prototype.data = function () { return this._data; }; Disposer.prototype.promise = function () { return this._promise; }; Disposer.prototype.resource = function () { if (this.promise().isFulfilled()) { return this.promise().value(); } return null; }; Disposer.prototype.tryDispose = function(inspection) { var resource = this.resource(); var context = this._context; if (context !== undefined) context._pushContext(); var ret = resource !== null ? this.doDispose(resource, inspection) : null; if (context !== undefined) context._popContext(); this._promise._unsetDisposable(); this._data = null; return ret; }; Disposer.isDisposer = function (d) { return (d != null && typeof d.resource === "function" && typeof d.tryDispose === "function"); }; function FunctionDisposer(fn, promise, context) { this.constructor$(fn, promise, context); } inherits(FunctionDisposer, Disposer); FunctionDisposer.prototype.doDispose = function (resource, inspection) { var fn = this.data(); return fn.call(resource, resource, inspection); }; function maybeUnwrapDisposer(value) { if (Disposer.isDisposer(value)) { this.resources[this.index]._setDisposable(value); return value.promise(); } return value; } function ResourceList(length) { this.length = length; this.promise = null; this[length-1] = null; } ResourceList.prototype._resultCancelled = function() { var len = this.length; for (var i = 0; i < len; ++i) { var item = this[i]; if (item instanceof Promise) { item.cancel(); } } }; Promise.using = function () { var len = arguments.length; if (len < 2) return apiRejection( "you must pass at least 2 arguments to Promise.using"); var fn = arguments[len - 1]; if (typeof fn !== "function") { return apiRejection("expecting a function but got " + util.classString(fn)); } var input; var spreadArgs = true; if (len === 2 && Array.isArray(arguments[0])) { input = arguments[0]; len = input.length; spreadArgs = false; } else { input = arguments; len--; } var resources = new ResourceList(len); for (var i = 0; i < len; ++i) { var resource = input[i]; if (Disposer.isDisposer(resource)) { var disposer = resource; resource = resource.promise(); resource._setDisposable(disposer); } else { var maybePromise = tryConvertToPromise(resource); if (maybePromise instanceof Promise) { resource = maybePromise._then(maybeUnwrapDisposer, null, null, { resources: resources, index: i }, undefined); } } resources[i] = resource; } var reflectedResources = new Array(resources.length); for (var i = 0; i < reflectedResources.length; ++i) { reflectedResources[i] = Promise.resolve(resources[i]).reflect(); } var resultPromise = Promise.all(reflectedResources) .then(function(inspections) { for (var i = 0; i < inspections.length; ++i) { var inspection = inspections[i]; if (inspection.isRejected()) { errorObj.e = inspection.error(); return errorObj; } else if (!inspection.isFulfilled()) { resultPromise.cancel(); return; } inspections[i] = inspection.value(); } promise._pushContext(); fn = tryCatch(fn); var ret = spreadArgs ? fn.apply(undefined, inspections) : fn(inspections); var promiseCreated = promise._popContext(); debug.checkForgottenReturns( ret, promiseCreated, "Promise.using", promise); return ret; }); var promise = resultPromise.lastly(function() { var inspection = new Promise.PromiseInspection(resultPromise); return dispose(resources, inspection); }); resources.promise = promise; promise._setOnCancel(resources); return promise; }; Promise.prototype._setDisposable = function (disposer) { this._bitField = this._bitField | 131072; this._disposer = disposer; }; Promise.prototype._isDisposable = function () { return (this._bitField & 131072) > 0; }; Promise.prototype._getDisposer = function () { return this._disposer; }; Promise.prototype._unsetDisposable = function () { this._bitField = this._bitField & (~131072); this._disposer = undefined; }; Promise.prototype.disposer = function (fn) { if (typeof fn === "function") { return new FunctionDisposer(fn, this, createContext()); } throw new TypeError(); }; }; },{"./errors":12,"./util":36}],36:[function(_dereq_,module,exports){ "use strict"; var es5 = _dereq_("./es5"); var canEvaluate = typeof navigator == "undefined"; var errorObj = {e: {}}; var tryCatchTarget; var globalObject = typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : typeof global !== "undefined" ? global : this !== undefined ? this : null; function tryCatcher() { try { var target = tryCatchTarget; tryCatchTarget = null; return target.apply(this, arguments); } catch (e) { errorObj.e = e; return errorObj; } } function tryCatch(fn) { tryCatchTarget = fn; return tryCatcher; } var inherits = function(Child, Parent) { var hasProp = {}.hasOwnProperty; function T() { this.constructor = Child; this.constructor$ = Parent; for (var propertyName in Parent.prototype) { if (hasProp.call(Parent.prototype, propertyName) && propertyName.charAt(propertyName.length-1) !== "$" ) { this[propertyName + "$"] = Parent.prototype[propertyName]; } } } T.prototype = Parent.prototype; Child.prototype = new T(); return Child.prototype; }; function isPrimitive(val) { return val == null || val === true || val === false || typeof val === "string" || typeof val === "number"; } function isObject(value) { return typeof value === "function" || typeof value === "object" && value !== null; } function maybeWrapAsError(maybeError) { if (!isPrimitive(maybeError)) return maybeError; return new Error(safeToString(maybeError)); } function withAppended(target, appendee) { var len = target.length; var ret = new Array(len + 1); var i; for (i = 0; i < len; ++i) { ret[i] = target[i]; } ret[i] = appendee; return ret; } function getDataPropertyOrDefault(obj, key, defaultValue) { if (es5.isES5) { var desc = Object.getOwnPropertyDescriptor(obj, key); if (desc != null) { return desc.get == null && desc.set == null ? desc.value : defaultValue; } } else { return {}.hasOwnProperty.call(obj, key) ? obj[key] : undefined; } } function notEnumerableProp(obj, name, value) { if (isPrimitive(obj)) return obj; var descriptor = { value: value, configurable: true, enumerable: false, writable: true }; es5.defineProperty(obj, name, descriptor); return obj; } function thrower(r) { throw r; } var inheritedDataKeys = (function() { var excludedPrototypes = [ Array.prototype, Object.prototype, Function.prototype ]; var isExcludedProto = function(val) { for (var i = 0; i < excludedPrototypes.length; ++i) { if (excludedPrototypes[i] === val) { return true; } } return false; }; if (es5.isES5) { var getKeys = Object.getOwnPropertyNames; return function(obj) { var ret = []; var visitedKeys = Object.create(null); while (obj != null && !isExcludedProto(obj)) { var keys; try { keys = getKeys(obj); } catch (e) { return ret; } for (var i = 0; i < keys.length; ++i) { var key = keys[i]; if (visitedKeys[key]) continue; visitedKeys[key] = true; var desc = Object.getOwnPropertyDescriptor(obj, key); if (desc != null && desc.get == null && desc.set == null) { ret.push(key); } } obj = es5.getPrototypeOf(obj); } return ret; }; } else { var hasProp = {}.hasOwnProperty; return function(obj) { if (isExcludedProto(obj)) return []; var ret = []; /*jshint forin:false */ enumeration: for (var key in obj) { if (hasProp.call(obj, key)) { ret.push(key); } else { for (var i = 0; i < excludedPrototypes.length; ++i) { if (hasProp.call(excludedPrototypes[i], key)) { continue enumeration; } } ret.push(key); } } return ret; }; } })(); var thisAssignmentPattern = /this\s*\.\s*\S+\s*=/; function isClass(fn) { try { if (typeof fn === "function") { var keys = es5.names(fn.prototype); var hasMethods = es5.isES5 && keys.length > 1; var hasMethodsOtherThanConstructor = keys.length > 0 && !(keys.length === 1 && keys[0] === "constructor"); var hasThisAssignmentAndStaticMethods = thisAssignmentPattern.test(fn + "") && es5.names(fn).length > 0; if (hasMethods || hasMethodsOtherThanConstructor || hasThisAssignmentAndStaticMethods) { return true; } } return false; } catch (e) { return false; } } function toFastProperties(obj) { /*jshint -W027,-W055,-W031*/ function FakeConstructor() {} FakeConstructor.prototype = obj; var l = 8; while (l--) new FakeConstructor(); return obj; eval(obj); } var rident = /^[a-z$_][a-z$_0-9]*$/i; function isIdentifier(str) { return rident.test(str); } function filledRange(count, prefix, suffix) { var ret = new Array(count); for(var i = 0; i < count; ++i) { ret[i] = prefix + i + suffix; } return ret; } function safeToString(obj) { try { return obj + ""; } catch (e) { return "[no string representation]"; } } function isError(obj) { return obj !== null && typeof obj === "object" && typeof obj.message === "string" && typeof obj.name === "string"; } function markAsOriginatingFromRejection(e) { try { notEnumerableProp(e, "isOperational", true); } catch(ignore) {} } function originatesFromRejection(e) { if (e == null) return false; return ((e instanceof Error["__BluebirdErrorTypes__"].OperationalError) || e["isOperational"] === true); } function canAttachTrace(obj) { return isError(obj) && es5.propertyIsWritable(obj, "stack"); } var ensureErrorObject = (function() { if (!("stack" in new Error())) { return function(value) { if (canAttachTrace(value)) return value; try {throw new Error(safeToString(value));} catch(err) {return err;} }; } else { return function(value) { if (canAttachTrace(value)) return value; return new Error(safeToString(value)); }; } })(); function classString(obj) { return {}.toString.call(obj); } function copyDescriptors(from, to, filter) { var keys = es5.names(from); for (var i = 0; i < keys.length; ++i) { var key = keys[i]; if (filter(key)) { try { es5.defineProperty(to, key, es5.getDescriptor(from, key)); } catch (ignore) {} } } } var asArray = function(v) { if (es5.isArray(v)) { return v; } return null; }; if (typeof Symbol !== "undefined" && Symbol.iterator) { var ArrayFrom = typeof Array.from === "function" ? function(v) { return Array.from(v); } : function(v) { var ret = []; var it = v[Symbol.iterator](); var itResult; while (!((itResult = it.next()).done)) { ret.push(itResult.value); } return ret; }; asArray = function(v) { if (es5.isArray(v)) { return v; } else if (v != null && typeof v[Symbol.iterator] === "function") { return ArrayFrom(v); } return null; }; } var isNode = typeof process !== "undefined" && classString(process).toLowerCase() === "[object process]"; function env(key, def) { return isNode ? process.env[key] : def; } var ret = { isClass: isClass, isIdentifier: isIdentifier, inheritedDataKeys: inheritedDataKeys, getDataPropertyOrDefault: getDataPropertyOrDefault, thrower: thrower, isArray: es5.isArray, asArray: asArray, notEnumerableProp: notEnumerableProp, isPrimitive: isPrimitive, isObject: isObject, isError: isError, canEvaluate: canEvaluate, errorObj: errorObj, tryCatch: tryCatch, inherits: inherits, withAppended: withAppended, maybeWrapAsError: maybeWrapAsError, toFastProperties: toFastProperties, filledRange: filledRange, toString: safeToString, canAttachTrace: canAttachTrace, ensureErrorObject: ensureErrorObject, originatesFromRejection: originatesFromRejection, markAsOriginatingFromRejection: markAsOriginatingFromRejection, classString: classString, copyDescriptors: copyDescriptors, hasDevTools: typeof chrome !== "undefined" && chrome && typeof chrome.loadTimes === "function", isNode: isNode, env: env, global: globalObject }; ret.isRecentNode = ret.isNode && (function() { var version = process.versions.node.split(".").map(Number); return (version[0] === 0 && version[1] > 10) || (version[0] > 0); })(); if (ret.isNode) ret.toFastProperties(process); try {throw new Error(); } catch (e) {ret.lastLineError = e;} module.exports = ret; },{"./es5":13}]},{},[4])(4) }); ;if (typeof window !== 'undefined' && window !== null) { window.P = window.Promise; } else if (typeof self !== 'undefined' && self !== null) { self.P = self.Promise; }
/** * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ 'use strict'; const launchEditor = require('../util/launchEditor'); module.exports = function(req, res, next) { if (req.url === '/open-stack-frame') { var frame = JSON.parse(req.rawBody); launchEditor(frame.file, frame.lineNumber); res.end('OK'); } else { next(); } };
import foo { bar } from "bar";
/** * @license RequireJS Copyright (c) 2004-2010, The Dojo Foundation All Rights Reserved. * Available via the MIT, GPL or new BSD license. * see: http://github.com/jrburke/requirejs for details */ //laxbreak is true to allow build pragmas to change some statements. /*jslint plusplus: false, laxbreak: true */ /*global window: false, document: false, navigator: false, setTimeout: false, traceDeps: true, clearInterval: false, self: false, setInterval: false */ //>>includeStart("useStrict", pragmas.useStrict); "use strict"; //>>includeEnd("useStrict"); var require; (function () { //Change this version number for each release. var version = "0.9.0", empty = {}, s, i, defContextName = "_", contextLoads = [], scripts, script, rePkg, src, m, cfg, setReadyState, readyRegExp = /^(complete|loaded)$/, isBrowser = !!(typeof window !== "undefined" && navigator && document), ostring = Object.prototype.toString, scrollIntervalId; function isFunction(it) { return ostring.call(it) === "[object Function]"; } //Check for an existing version of require. If so, then exit out. Only allow //one version of require to be active in a page. However, allow for a require //config object, just exit quickly if require is an actual function. if (typeof require !== "undefined") { if (isFunction(require)) { return; } else { //assume it is a config object. cfg = require; } } //>>excludeStart("requireExcludeContext", pragmas.requireExcludeContext); function makeContextFunc(name, contextName, force) { return function () { //A version of a require function that uses the current context. //If last arg is a string, then it is a context. //If last arg is not a string, then add context to it. var args = [].concat(Array.prototype.slice.call(arguments, 0)); if (force || typeof arguments[arguments.length - 1] !== "string") { args.push(contextName); } return (name ? require[name] : require).apply(null, args); }; } //>>excludeEnd("requireExcludeContext"); //>>excludeStart("requireExcludePlugin", pragmas.requireExcludePlugin); /** * Calls a method on a plugin. The obj object should have two property, * name: the name of the method to call on the plugin * args: the arguments to pass to the plugin method. */ function callPlugin(prefix, context, obj) { //Call the plugin, or load it. var plugin = s.plugins.defined[prefix], waiting; if (plugin) { plugin[obj.name].apply(null, obj.args); } else { //Put the call in the waiting call BEFORE requiring the module, //since the require could be synchronous in some environments, //like builds waiting = s.plugins.waiting[prefix] || (s.plugins.waiting[prefix] = []); waiting.push(obj); //Load the module context.defined.require(["require/" + prefix]); } } //>>excludeEnd("requireExcludePlugin"); /** * Main entry point. * * If the only argument to require is a string, then the module that * is represented by that string is fetched for the appropriate context. * * If the first argument is an array, then it will be treated as an array * of dependency string names to fetch. An optional function callback can * be specified to execute when all of those dependencies are available. */ require = function (deps, callback, contextName) { if (typeof deps === "string" && !isFunction(callback)) { //Just return the module wanted. In this scenario, the //second arg (if passed) is just the contextName. return require.get(deps, callback); } //Do more work, either return require.def.apply(require, arguments); }; /** * The function that handles definitions of modules. Differs from * require() in that a string for the module should be the first argument, * and the function to execute after dependencies are loaded should * return a value to define the module corresponding to the first argument's * name. */ require.def = function (name, deps, callback, contextName) { var config = null, context, newContext, contextRequire, loaded, canSetContext, prop, newLength, outDeps, mods, pluginPrefix, paths, index, i; //Normalize the arguments. if (typeof name === "string") { //Defining a module. First, pull off any plugin prefix. index = name.indexOf("!"); if (index !== -1) { pluginPrefix = name.substring(0, index); name = name.substring(index + 1, name.length); } //Check if there are no dependencies, and adjust args. if (!require.isArray(deps)) { contextName = callback; callback = deps; deps = []; } contextName = contextName || s.ctxName; //If module already defined for context, or already waiting to be //evaluated, leave. context = s.contexts[contextName]; if (context && (context.defined[name] || context.waiting[name])) { return require; } } else if (require.isArray(name)) { //Just some code that has dependencies. Adjust args accordingly. contextName = callback; callback = deps; deps = name; name = null; } else if (require.isFunction(name)) { //Just a function that does not define a module and //does not have dependencies. Useful if just want to wait //for whatever modules are in flight and execute some code after //those modules load. callback = name; contextName = deps; name = null; deps = []; } else { //name is a config object. config = name; name = null; //Adjust args if no dependencies. if (require.isFunction(deps)) { contextName = callback; callback = deps; deps = []; } contextName = contextName || config.context; } contextName = contextName || s.ctxName; //>>excludeStart("requireExcludeContext", pragmas.requireExcludeContext); if (contextName !== s.ctxName) { //If nothing is waiting on being loaded in the current context, //then switch s.ctxName to current contextName. loaded = (s.contexts[s.ctxName] && s.contexts[s.ctxName].loaded); canSetContext = true; if (loaded) { for (prop in loaded) { if (!(prop in empty)) { if (!loaded[prop]) { canSetContext = false; break; } } } } if (canSetContext) { s.ctxName = contextName; } } //>>excludeEnd("requireExcludeContext"); //Grab the context, or create a new one for the given context name. context = s.contexts[contextName]; if (!context) { newContext = { contextName: contextName, config: { waitSeconds: 7, baseUrl: s.baseUrl || "./", paths: {} }, waiting: [], specified: { "require": true, "exports": true, "module": true }, loaded: { "require": true }, defined: {}, modifiers: {} }; //Define require for this context. //>>includeStart("requireExcludeContext", pragmas.requireExcludeContext); //A placeholder for build pragmas. newContext.defined.require = require; //>>includeEnd("requireExcludeContext"); //>>excludeStart("requireExcludeContext", pragmas.requireExcludeContext); newContext.defined.require = contextRequire = makeContextFunc(null, contextName); require.mixin(contextRequire, { //>>excludeStart("requireExcludeModify", pragmas.requireExcludeModify); modify: makeContextFunc("modify", contextName), def: makeContextFunc("def", contextName), //>>excludeEnd("requireExcludeModify"); get: makeContextFunc("get", contextName, true), nameToUrl: makeContextFunc("nameToUrl", contextName, true), ready: require.ready, context: newContext, config: newContext.config, isBrowser: s.isBrowser }); //>>excludeEnd("requireExcludeContext"); //>>excludeStart("requireExcludePlugin", pragmas.requireExcludePlugin); if (s.plugins.newContext) { s.plugins.newContext(newContext); } //>>excludeEnd("requireExcludePlugin"); context = s.contexts[contextName] = newContext; } //If have a config object, update the context's config object with //the config values. if (config) { //Make sure the baseUrl ends in a slash. if (config.baseUrl) { if (config.baseUrl.charAt(config.baseUrl.length - 1) !== "/") { config.baseUrl += "/"; } } //Save off the paths since they require special processing, //they are additive. paths = context.config.paths; //Mix in the config values, favoring the new values over //existing ones in context.config. require.mixin(context.config, config, true); //Adjust paths if necessary. if (config.paths) { for (prop in config.paths) { if (!(prop in empty)) { paths[prop] = config.paths[prop]; } } context.config.paths = paths; } //If a deps array or a config callback is specified, then call //require with those args. This is useful when require is defined as a //config object before require.js is loaded. if (config.deps || config.callback) { require(config.deps || [], config.callback); } //>>excludeStart("requireExcludePageLoad", pragmas.requireExcludePageLoad); //Set up ready callback, if asked. Useful when require is defined as a //config object before require.js is loaded. if (config.ready) { require.ready(config.ready); } //>>excludeEnd("requireExcludePageLoad"); //If it is just a config block, nothing else, //then return. if (!deps) { return require; } } //Normalize dependency strings: need to determine if they have //prefixes and to also normalize any relative paths. Replace the deps //array of strings with an array of objects. if (deps) { outDeps = deps; deps = []; for (i = 0; i < outDeps.length; i++) { deps[i] = require.splitPrefix(outDeps[i], name); } } //Store the module for later evaluation newLength = context.waiting.push({ name: name, deps: deps, callback: callback }); if (name) { //Store index of insertion for quick lookup context.waiting[name] = newLength - 1; //Mark the module as specified: not loaded yet, but in the process, //so no need to fetch it again. Important to do it here for the //pause/resume case where there are multiple modules in a file. context.specified[name] = true; //>>excludeStart("requireExcludeModify", pragmas.requireExcludeModify); //Load any modifiers for the module. mods = context.modifiers[name]; if (mods) { require(mods, contextName); } //>>excludeEnd("requireExcludeModify"); } //If the callback is not an actual function, it means it already //has the definition of the module as a literal value. if (name && callback && !require.isFunction(callback)) { context.defined[name] = callback; } //If a pluginPrefix is available, call the plugin, or load it. //>>excludeStart("requireExcludePlugin", pragmas.requireExcludePlugin); if (pluginPrefix) { callPlugin(pluginPrefix, context, { name: "require", args: [name, deps, callback, context] }); } //>>excludeEnd("requireExcludePlugin"); //See if all is loaded. If paused, then do not check the dependencies //of the module yet. if (s.paused) { s.paused.push([pluginPrefix, name, deps, context]); } else { require.checkDeps(pluginPrefix, name, deps, context); require.checkLoaded(contextName); } return require; }; /** * Simple function to mix in properties from source into target, * but only if target does not already have a property of the same name. */ require.mixin = function (target, source, override) { for (var prop in source) { if (!(prop in empty) && (!(prop in target) || override)) { target[prop] = source[prop]; } } return require; }; require.version = version; //Set up page state. s = require.s = { ctxName: defContextName, contexts: {}, //>>excludeStart("requireExcludePlugin", pragmas.requireExcludePlugin); plugins: { defined: {}, callbacks: {}, waiting: {} }, //>>excludeEnd("requireExcludePlugin"); isBrowser: isBrowser, isPageLoaded: !isBrowser, readyCalls: [], doc: isBrowser ? document : null }; require.isBrowser = s.isBrowser; s.head = isBrowser ? document.getElementsByTagName("head")[0] : null; //>>excludeStart("requireExcludePlugin", pragmas.requireExcludePlugin); /** * Sets up a plugin callback name. Want to make it easy to test if a plugin * needs to be called for a certain lifecycle event by testing for * if (s.plugins.onLifeCyleEvent) so only define the lifecycle event * if there is a real plugin that registers for it. */ function makePluginCallback(name, returnOnTrue) { var cbs = s.plugins.callbacks[name] = []; s.plugins[name] = function () { for (var i = 0, cb; (cb = cbs[i]); i++) { if (cb.apply(null, arguments) === true && returnOnTrue) { return true; } } return false; }; } /** * Registers a new plugin for require. */ require.plugin = function (obj) { var i, prop, call, prefix = obj.prefix, cbs = s.plugins.callbacks, waiting = s.plugins.waiting[prefix], generics, defined = s.plugins.defined, contexts = s.contexts, context; //Do not allow redefinition of a plugin, there may be internal //state in the plugin that could be lost. if (defined[prefix]) { return require; } //Save the plugin. defined[prefix] = obj; //Set up plugin callbacks for methods that need to be generic to //require, for lifecycle cases where it does not care about a particular //plugin, but just that some plugin work needs to be done. generics = ["newContext", "isWaiting", "orderDeps"]; for (i = 0; (prop = generics[i]); i++) { if (!s.plugins[prop]) { makePluginCallback(prop, prop === "isWaiting"); } cbs[prop].push(obj[prop]); } //Call newContext for any contexts that were already created. if (obj.newContext) { for (prop in contexts) { if (!(prop in empty)) { context = contexts[prop]; obj.newContext(context); } } } //If there are waiting requests for a plugin, execute them now. if (waiting) { for (i = 0; (call = waiting[i]); i++) { if (obj[call.name]) { obj[call.name].apply(null, call.args); } } delete s.plugins.waiting[prefix]; } return require; }; //>>excludeEnd("requireExcludePlugin"); /** * Pauses the tracing of dependencies. Useful in a build scenario when * multiple modules are bundled into one file, and they all need to be * require before figuring out what is left still to load. */ require.pause = function () { if (!s.paused) { s.paused = []; } }; /** * Resumes the tracing of dependencies. Useful in a build scenario when * multiple modules are bundled into one file. This method is related * to require.pause() and should only be called if require.pause() was called first. */ require.resume = function () { var i, args, paused; if (s.paused) { paused = s.paused; delete s.paused; for (i = 0; (args = paused[i]); i++) { require.checkDeps.apply(require, args); } } require.checkLoaded(s.ctxName); }; /** * Trace down the dependencies to see if they are loaded. If not, trigger * the load. * @param {String} pluginPrefix the plugin prefix, if any associated with the name. * * @param {String} name: the name of the module that has the dependencies. * * @param {Array} deps array of dependencies. * * @param {Object} context: the loading context. * * @private */ require.checkDeps = function (pluginPrefix, name, deps, context) { //Figure out if all the modules are loaded. If the module is not //being loaded or already loaded, add it to the "to load" list, //and request it to be loaded. var i, dep, index, depPrefix, split; if (pluginPrefix) { //>>excludeStart("requireExcludePlugin", pragmas.requireExcludePlugin); callPlugin(pluginPrefix, context, { name: "checkDeps", args: [name, deps, context] }); //>>excludeEnd("requireExcludePlugin"); } else { for (i = 0; (dep = deps[i]); i++) { if (!context.specified[dep.fullName]) { context.specified[dep.fullName] = true; //If a plugin, call its load method. if (dep.prefix) { //>>excludeStart("requireExcludePlugin", pragmas.requireExcludePlugin); callPlugin(dep.prefix, context, { name: "load", args: [dep.name, context.contextName] }); //>>excludeEnd("requireExcludePlugin"); } else { require.load(dep.name, context.contextName); } } } } }; //>>excludeStart("requireExcludeModify", pragmas.requireExcludeModify); /** * Register a module that modifies another module. The modifier will * only be called once the target module has been loaded. * * First syntax: * * require.modify({ * "some/target1": "my/modifier1", * "some/target2": "my/modifier2", * }); * * With this syntax, the my/modifier1 will only be loaded when * "some/target1" is loaded. * * Second syntax, defining a modifier. * * require.modify("some/target1", "my/modifier", * ["some/target1", "some/other"], * function (target, other) { * //Modify properties of target here. * Only properties of target can be modified, but * target cannot be replaced. * } * ); */ require.modify = function (target, name, deps, callback, contextName) { var prop, modifier, list, cName = (typeof target === "string" ? contextName : name) || s.ctxName, context = s.contexts[cName], mods = context.modifiers; if (typeof target === "string") { //A modifier module. //First store that it is a modifier. list = mods[target] || (mods[target] = []); if (!list[name]) { list.push(name); list[name] = true; } //Trigger the normal module definition logic. require.def(name, deps, callback, contextName); } else { //A list of modifiers. Save them for future reference. for (prop in target) { if (!(prop in empty)) { //Store the modifier for future use. modifier = target[prop]; list = context.modifiers[prop] || (context.modifiers[prop] = []); if (!list[modifier]) { list.push(modifier); list[modifier] = true; if (context.specified[prop]) { //Load the modifier right away. require([modifier], cName); } } } } } }; //>>excludeEnd("requireExcludeModify"); require.isArray = function (it) { return ostring.call(it) === "[object Array]"; }; require.isFunction = isFunction; /** * Gets one module's exported value. This method is used by require(). * It is broken out as a separate function to allow a host environment * shim to overwrite this function with something appropriate for that * environment. * * @param {String} moduleName the name of the module. * @param {String} [contextName] the name of the context to use. Uses * default context if no contextName is provided. * * @returns {Object} the exported module value. */ require.get = function (moduleName, contextName) { if (moduleName === "exports" || moduleName === "module") { throw new Error("require of " + moduleName + " is not allowed."); } contextName = contextName || s.ctxName; var ret = s.contexts[contextName].defined[moduleName]; if (ret === undefined) { throw new Error("require: module name '" + moduleName + "' has not been loaded yet for context: " + contextName); } return ret; }; /** * Makes the request to load a module. May be an async load depending on * the environment and the circumstance of the load call. Override this * method in a host environment shim to do something specific for that * environment. * * @param {String} moduleName the name of the module. * @param {String} contextName the name of the context to use. */ require.load = function (moduleName, contextName) { var context = s.contexts[contextName], url; s.isDone = false; context.loaded[moduleName] = false; //>>excludeStart("requireExcludeContext", pragmas.requireExcludeContext); if (contextName !== s.ctxName) { //Not in the right context now, hold on to it until //the current context finishes all its loading. contextLoads.push(arguments); } else { //>>excludeEnd("requireExcludeContext"); //First derive the path name for the module. url = require.nameToUrl(moduleName, null, contextName); require.attach(url, contextName, moduleName); context.startTime = (new Date()).getTime(); //>>excludeStart("requireExcludeContext", pragmas.requireExcludeContext); } //>>excludeEnd("requireExcludeContext"); }; require.jsExtRegExp = /\.js$/; /** * Given a relative module name, like ./something, normalize it to * a real name that can be mapped to a path. * @param {String} name the relative name * @param {String} baseName a real name that the name arg is relative * to. * @returns {String} normalized name */ require.normalizeName = function (name, baseName) { //Adjust any relative paths. var part; if (name.charAt(0) === ".") { //Convert baseName to array, and lop off the last part, //so that . matches that "directory" and not name of the baseName's //module. For instance, baseName of "one/two/three", maps to //"one/two/three.js", but we want the directory, "one/two" for //this normalization. baseName = baseName.split("/"); baseName = baseName.slice(0, baseName.length - 1); name = baseName.concat(name.split("/")); for (i = 0; (part = name[i]); i++) { if (part === ".") { name.splice(i, 1); i -= 1; } else if (part === "..") { name.splice(i - 1, 2); i -= 2; } } name = name.join("/"); } return name; }; /** * Splits a name into a possible plugin prefix and * the module name. If baseName is provided it will * also normalize the name via require.normalizeName() * * @param {String} name the module name * @param {String} [baseName] base name that name is * relative to. * * @returns {Object} with properties, 'prefix' (which * may be null), 'name' and 'fullName', which is a combination * of the prefix (if it exists) and the name. */ require.splitPrefix = function (name, baseName) { var index = name.indexOf("!"), prefix = null; if (index !== -1) { prefix = name.substring(0, index); name = name.substring(index + 1, name.length); } //Account for relative paths if there is a base name. if (baseName) { name = require.normalizeName(name, baseName); } return { prefix: prefix, name: name, fullName: prefix ? prefix + "!" + name : name }; }; /** * Converts a module name to a file path. */ require.nameToUrl = function (moduleName, ext, contextName) { var paths, syms, i, parentModule, url, config = s.contexts[contextName].config; //If a colon is in the URL, it indicates a protocol is used and it is just //an URL to a file, or if it starts with a slash or ends with .js, it is just a plain file. //The slash is important for protocol-less URLs as well as full paths. if (moduleName.indexOf(":") !== -1 || moduleName.charAt(0) === '/' || require.jsExtRegExp.test(moduleName)) { //Just a plain path, not module name lookup, so just return it. return moduleName; } else if (moduleName.charAt(0) === ".") { throw new Error("require.nameToUrl does not handle relative module names (ones that start with '.' or '..')"); } else { //A module that needs to be converted to a path. paths = config.paths; syms = moduleName.split("/"); //For each module name segment, see if there is a path //registered for it. Start with most specific name //and work up from it. for (i = syms.length; i > 0; i--) { parentModule = syms.slice(0, i).join("/"); if (paths[parentModule]) { syms.splice(0, i, paths[parentModule]); break; } } //Join the path parts together, then figure out if baseUrl is needed. url = syms.join("/") + (ext || ".js"); return ((url.charAt(0) === '/' || url.match(/^\w+:/)) ? "" : config.baseUrl) + url; } }; /** * Checks if all modules for a context are loaded, and if so, evaluates the * new ones in right dependency order. * * @private */ require.checkLoaded = function (contextName) { var context = s.contexts[contextName || s.ctxName], waitInterval = context.config.waitSeconds * 1000, //It is possible to disable the wait interval by using waitSeconds of 0. expired = waitInterval && (context.startTime + waitInterval) < new Date().getTime(), loaded = context.loaded, defined = context.defined, modifiers = context.modifiers, waiting = context.waiting, noLoads = "", hasLoadedProp = false, stillLoading = false, prop, //>>excludeStart("requireExcludePlugin", pragmas.requireExcludePlugin); pIsWaiting = s.plugins.isWaiting, pOrderDeps = s.plugins.orderDeps, //>>excludeEnd("requireExcludePlugin"); i, module, allDone, loads, loadArgs, traced = {}; //If already doing a checkLoaded call, //then do not bother checking loaded state. if (context.isCheckLoaded) { return; } //Signal that checkLoaded is being require, so other calls that could be triggered //by calling a waiting callback that then calls require and then this function //should not proceed. At the end of this function, if there are still things //waiting, then checkLoaded will be called again. context.isCheckLoaded = true; //See if anything is still in flight. for (prop in loaded) { if (!(prop in empty)) { hasLoadedProp = true; if (!loaded[prop]) { if (expired) { noLoads += prop + " "; } else { stillLoading = true; break; } } } } //Check for exit conditions. if (!hasLoadedProp && !waiting.length //>>excludeStart("requireExcludePlugin", pragmas.requireExcludePlugin); && (!pIsWaiting || !pIsWaiting(context)) //>>excludeEnd("requireExcludePlugin"); ) { //If the loaded object had no items, then the rest of //the work below does not need to be done. context.isCheckLoaded = false; return; } if (expired && noLoads) { //If wait time expired, throw error of unloaded modules. throw new Error("require.js load timeout for modules: " + noLoads); } if (stillLoading) { //Something is still waiting to load. Wait for it. context.isCheckLoaded = false; if (require.isBrowser) { setTimeout(function () { require.checkLoaded(contextName); }, 50); } return; } //Order the dependencies. Also clean up state because the evaluation //of modules might create new loading tasks, so need to reset. //Be sure to call plugins too. context.waiting = []; context.loaded = {}; //>>excludeStart("requireExcludePlugin", pragmas.requireExcludePlugin); //Call plugins to order their dependencies, do their //module definitions. if (pOrderDeps) { pOrderDeps(context); } //>>excludeEnd("requireExcludePlugin"); //>>excludeStart("requireExcludeModify", pragmas.requireExcludeModify); //Before defining the modules, give priority treatment to any modifiers //for modules that are already defined. for (prop in modifiers) { if (!(prop in empty)) { if (defined[prop]) { require.execModifiers(prop, traced, waiting, context); } } } //>>excludeEnd("requireExcludeModify"); //Define the modules, doing a depth first search. for (i = 0; (module = waiting[i]); i++) { require.exec(module, traced, waiting, context); } //Indicate checkLoaded is now done. context.isCheckLoaded = false; if (context.waiting.length //>>excludeStart("requireExcludePlugin", pragmas.requireExcludePlugin); || (pIsWaiting && pIsWaiting(context)) //>>excludeEnd("requireExcludePlugin"); ) { //More things in this context are waiting to load. They were probably //added while doing the work above in checkLoaded, calling module //callbacks that triggered other require calls. require.checkLoaded(contextName); } else if (contextLoads.length) { //>>excludeStart("requireExcludeContext", pragmas.requireExcludeContext); //Check for other contexts that need to load things. //First, make sure current context has no more things to //load. After defining the modules above, new require calls //could have been made. loaded = context.loaded; allDone = true; for (prop in loaded) { if (!(prop in empty)) { if (!loaded[prop]) { allDone = false; break; } } } if (allDone) { s.ctxName = contextLoads[0][1]; loads = contextLoads; //Reset contextLoads in case some of the waiting loads //are for yet another context. contextLoads = []; for (i = 0; (loadArgs = loads[i]); i++) { require.load.apply(require, loadArgs); } } //>>excludeEnd("requireExcludeContext"); } else { //Make sure we reset to default context. s.ctxName = defContextName; s.isDone = true; if (require.callReady) { require.callReady(); } } }; /** * Executes the modules in the correct order. * * @private */ require.exec = function (module, traced, waiting, context) { //Some modules are just plain script files, abddo not have a formal //module definition, if (!module) { return undefined; } var name = module.name, cb = module.callback, deps = module.deps, j, dep, defined = context.defined, ret, args = [], prefix, depModule, usingExports = false, depName; //If already traced or defined, do not bother a second time. if (name) { if (traced[name] || defined[name]) { return defined[name]; } //Mark this module as being traced, so that it is not retraced (as in a circular //dependency) traced[name] = true; } if (deps) { for (j = 0; (dep = deps[j]); j++) { depName = dep.name; if (depName === "exports") { //CommonJS module spec 1.1 depModule = defined[name] = {}; usingExports = true; } else if (depName === "module") { //CommonJS module spec 1.1 depModule = { id: name, uri: name ? require.nameToUrl(name, null, context.contextName) : undefined }; } else { //Get dependent module. It could not exist, for a circular //dependency or if the loaded dependency does not actually call //require. Favor not throwing an error here if undefined because //we want to allow code that does not use require as a module //definition framework to still work -- allow a web site to //gradually update to contained modules. That is more //important than forcing a throw for the circular dependency case. depModule = depName in defined ? defined[depName] : (traced[depName] ? undefined : require.exec(waiting[waiting[depName]], traced, waiting, context)); } args.push(depModule); } } //Call the callback to define the module, if necessary. cb = module.callback; if (cb && require.isFunction(cb)) { ret = require.execCb(name, cb, args); if (name) { if (usingExports) { ret = defined[name]; } else { if (name in defined) { throw new Error(name + " has already been defined"); } else { defined[name] = ret; } } } } //>>excludeStart("requireExcludeModify", pragmas.requireExcludeModify); //Execute modifiers, if they exist. require.execModifiers(name, traced, waiting, context); //>>excludeEnd("requireExcludeModify"); return ret; }; /** * Executes a module callack function. Broken out as a separate function * solely to allow the build system to sequence the files in the built * layer in the right sequence. * @param {String} name the module name. * @param {Function} cb the module callback/definition function. * @param {Array} args The arguments (dependent modules) to pass to callback. * * @private */ require.execCb = function (name, cb, args) { return cb.apply(null, args); }; //>>excludeStart("requireExcludeModify", pragmas.requireExcludeModify); /** * Executes modifiers for the given module name. * @param {String} target * @param {Object} traced * @param {Object} context * * @private */ require.execModifiers = function (target, traced, waiting, context) { var modifiers = context.modifiers, mods = modifiers[target], mod, i; if (mods) { for (i = 0; i < mods.length; i++) { mod = mods[i]; //Not all modifiers define a module, they might collect other modules. //If it is just a collection it will not be in waiting. if (mod in waiting) { require.exec(waiting[waiting[mod]], traced, waiting, context); } } delete modifiers[target]; } }; //>>excludeEnd("requireExcludeModify"); /** * callback for script loads, used to check status of loading. * * @param {Event} evt the event from the browser for the script * that was loaded. * * @private */ require.onScriptLoad = function (evt) { var node = evt.target || evt.srcElement, contextName, moduleName; if (evt.type === "load" || readyRegExp.test(node.readyState)) { //Pull out the name of the module and the context. contextName = node.getAttribute("data-requirecontext"); moduleName = node.getAttribute("data-requiremodule"); //Mark the module loaded. s.contexts[contextName].loaded[moduleName] = true; require.checkLoaded(contextName); //Clean up script binding. if (node.removeEventListener) { node.removeEventListener("load", require.onScriptLoad, false); } else { //Probably IE. node.detachEvent("onreadystatechange", require.onScriptLoad); } } }; /** * Attaches the script represented by the URL to the current * environment. Right now only supports browser loading, * but can be redefined in other environments to do the right thing. */ require.attach = function (url, contextName, moduleName) { if (require.isBrowser) { var node = document.createElement("script"); node.type = "text/javascript"; node.charset = "utf-8"; node.setAttribute("data-requirecontext", contextName); node.setAttribute("data-requiremodule", moduleName); //Set up load listener. if (node.addEventListener) { node.addEventListener("load", require.onScriptLoad, false); } else { //Probably IE. node.attachEvent("onreadystatechange", require.onScriptLoad); } node.src = url; return s.head.appendChild(node); } return null; }; //Determine what baseUrl should be if not already defined via a require config object s.baseUrl = cfg && cfg.baseUrl; if (require.isBrowser && (!s.baseUrl || !s.head)) { //Figure out baseUrl. Get it from the script tag with require.js in it. scripts = document.getElementsByTagName("script"); if (cfg && cfg.baseUrlMatch) { rePkg = cfg.baseUrlMatch; } else { //>>includeStart("jquery", pragmas.jquery); rePkg = /(requireplugins-|require-)?jquery[\-\d\.]*(min)?\.js(\W|$)/i; //>>includeEnd("jquery"); //>>includeStart("dojoConvert", pragmas.dojoConvert); rePkg = /dojo\.js(\W|$)/i; //>>includeEnd("dojoConvert"); //>>excludeStart("dojoConvert", pragmas.dojoConvert); //>>excludeStart("jquery", pragmas.jquery); rePkg = /(allplugins-)?require\.js(\W|$)/i; //>>excludeEnd("jquery"); //>>excludeEnd("dojoConvert"); } for (i = scripts.length - 1; i > -1 && (script = scripts[i]); i--) { //Set the "head" where we can append children by //using the script's parent. if (!s.head) { s.head = script.parentNode; } //Using .src instead of getAttribute to get an absolute URL. //While using a relative URL will be fine for script tags, other //URLs used for text! resources that use XHR calls might benefit //from an absolute URL. src = script.src; if (src) { m = src.match(rePkg); if (m) { s.baseUrl = src.substring(0, m.index); break; } } } } //>>excludeStart("requireExcludePageLoad", pragmas.requireExcludePageLoad); //****** START page load functionality **************** /** * Sets the page as loaded and triggers check for all modules loaded. */ require.pageLoaded = function () { if (!s.isPageLoaded) { s.isPageLoaded = true; if (scrollIntervalId) { clearInterval(scrollIntervalId); } //Part of a fix for FF < 3.6 where readyState was not set to //complete so libraries like jQuery that check for readyState //after page load where not getting initialized correctly. //Original approach suggested by Andrea Giammarchi: //http://webreflection.blogspot.com/2009/11/195-chars-to-help-lazy-loading.html //see other setReadyState reference for the rest of the fix. if (setReadyState) { document.readyState = "complete"; } require.callReady(); } }; /** * Internal function that calls back any ready functions. If you are * integrating RequireJS with another library without require.ready support, * you can define this method to call your page ready code instead. */ require.callReady = function () { var callbacks = s.readyCalls, i, callback; if (s.isPageLoaded && s.isDone && callbacks.length) { s.readyCalls = []; for (i = 0; (callback = callbacks[i]); i++) { callback(); } } }; /** * Registers functions to call when the page is loaded */ require.ready = function (callback) { if (s.isPageLoaded && s.isDone) { callback(); } else { s.readyCalls.push(callback); } return require; }; if (require.isBrowser) { if (document.addEventListener) { //Standards. Hooray! Assumption here that if standards based, //it knows about DOMContentLoaded. document.addEventListener("DOMContentLoaded", require.pageLoaded, false); window.addEventListener("load", require.pageLoaded, false); //Part of FF < 3.6 readystate fix (see setReadyState refs for more info) if (!document.readyState) { setReadyState = true; document.readyState = "loading"; } } else if (window.attachEvent) { window.attachEvent("onload", require.pageLoaded); //DOMContentLoaded approximation, as found by Diego Perini: //http://javascript.nwbox.com/IEContentLoaded/ if (self === self.top) { scrollIntervalId = setInterval(function () { try { document.documentElement.doScroll("left"); require.pageLoaded(); } catch (e) {} }, 30); } } //Check if document already complete, and if so, just trigger page load //listeners. NOTE: does not work with Firefox before 3.6. To support //those browsers, manually call require.pageLoaded(). if (document.readyState === "complete") { require.pageLoaded(); } } //****** END page load functionality **************** //>>excludeEnd("requireExcludePageLoad"); //Set up default context. If require was a configuration object, use that as base config. if (cfg) { require(cfg); } }());
/* Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.plugins.setLang( 'blockquote', 'en-au', { toolbar: 'Block Quote' });
/* Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.plugins.setLang( 'preview', 'uk', { preview: 'Попередній перегляд' });
var reduce = require("./reduce"); var add = require("./add"); function sum(list){ return reduce(list, add, 0); }; module.exports = sum;
YUI.add("lang/datatype-date-format_pt",function(a){a.Intl.add("datatype-date-format","pt",{"a":["dom","seg","ter","qua","qui","sex","sáb"],"A":["domingo","segunda-feira","terça-feira","quarta-feira","quinta-feira","sexta-feira","sábado"],"b":["jan","fev","mar","abr","mai","jun","jul","ago","set","out","nov","dez"],"B":["janeiro","fevereiro","março","abril","maio","junho","julho","agosto","setembro","outubro","novembro","dezembro"],"c":"%a, %d de %b de %Y %Hh%Mmin%Ss %Z","p":["AM","PM"],"P":["am","pm"],"x":"%d/%m/%y","X":"%Hh%Mmin%Ss"});},"@VERSION@");
/* =========================================================== * fi.js * Finnish translation for Trumbowyg * http://alex-d.github.com/Trumbowyg * =========================================================== * Author : Teppo Koivula (teppokoivula) * Github : https://github.com/teppokoivula */ jQuery.trumbowyg.langs.fi={viewHTML:"Näytä HTML",formatting:"Muotoilu",p:"Kappale",blockquote:"Lainaus",code:"Koodi",header:"Otsikko",bold:"Lihavointi",italic:"Kursivointi",strikethrough:"Yliviivaus",underline:"Allevivaus",strong:"Vahvennus",em:"Painotus",del:"Poistettu",unorderedList:"Numeroimaton lista",orderedList:"Numeroitu lista",insertImage:"Lisää kuva",insertVideo:"Lisää video",link:"Linkki",createLink:"Luo linkki",unlink:"Poista linkki",justifyLeft:"Asemoi vasemmalle",justifyCenter:"Keskitä",justifyRight:"Asemoi oikealle",justifyFull:"Tasaa",horizontalRule:"Vaakaviiva",fullscreen:"Kokoruutu",close:"Sulje",submit:"Lähetä",reset:"Palauta",invalidUrl:"Viallinen URL-osoite",required:"Pakollinen",description:"Kuvaus",title:"Otsikko",text:"Teksti"};
/** * @license Highmaps JS v4.2.3 (2016-02-08) * * (c) 2011-2016 Torstein Honsi * * License: www.highcharts.com/license */ /*eslint no-unused-vars: 0 */ // @todo: Not needed in HC5 (function (root, factory) { if (typeof module === 'object' && module.exports) { module.exports = root.document ? factory(root) : factory; } else { root.Highcharts = factory(root); } }(typeof window !== 'undefined' ? window : this, function (win) { // eslint-disable-line no-undef // encapsulated variables var UNDEFINED, doc = win.document, math = Math, mathRound = math.round, mathFloor = math.floor, mathCeil = math.ceil, mathMax = math.max, mathMin = math.min, mathAbs = math.abs, mathCos = math.cos, mathSin = math.sin, mathPI = math.PI, deg2rad = mathPI * 2 / 360, // some variables userAgent = (win.navigator && win.navigator.userAgent) || '', isOpera = win.opera, isMS = /(msie|trident|edge)/i.test(userAgent) && !isOpera, docMode8 = doc && doc.documentMode === 8, isWebKit = !isMS && /AppleWebKit/.test(userAgent), isFirefox = /Firefox/.test(userAgent), isTouchDevice = /(Mobile|Android|Windows Phone)/.test(userAgent), SVG_NS = 'http://www.w3.org/2000/svg', hasSVG = doc && doc.createElementNS && !!doc.createElementNS(SVG_NS, 'svg').createSVGRect, hasBidiBug = isFirefox && parseInt(userAgent.split('Firefox/')[1], 10) < 4, // issue #38 useCanVG = doc && !hasSVG && !isMS && !!doc.createElement('canvas').getContext, Renderer, hasTouch, symbolSizes = {}, idCounter = 0, garbageBin, defaultOptions, dateFormat, // function pathAnim, timeUnits, noop = function () {}, charts = [], chartCount = 0, PRODUCT = 'Highmaps', VERSION = '4.2.3', // some constants for frequently used strings DIV = 'div', ABSOLUTE = 'absolute', RELATIVE = 'relative', HIDDEN = 'hidden', PREFIX = 'highcharts-', VISIBLE = 'visible', PX = 'px', NONE = 'none', M = 'M', L = 'L', numRegex = /^[0-9]+$/, NORMAL_STATE = '', HOVER_STATE = 'hover', SELECT_STATE = 'select', marginNames = ['plotTop', 'marginRight', 'marginBottom', 'plotLeft'], // Object for extending Axis AxisPlotLineOrBandExtension, // constants for attributes STROKE_WIDTH = 'stroke-width', // time methods, changed based on whether or not UTC is used Date, // Allow using a different Date class makeTime, timezoneOffset, getTimezoneOffset, getMinutes, getHours, getDay, getDate, getMonth, getFullYear, setMilliseconds, setSeconds, setMinutes, setHours, setDate, setMonth, setFullYear, // lookup over the types and the associated classes seriesTypes = {}, Highcharts; /** * Provide error messages for debugging, with links to online explanation */ function error(code, stop) { var msg = 'Highcharts error #' + code + ': www.highcharts.com/errors/' + code; if (stop) { throw new Error(msg); } // else ... if (win.console) { console.log(msg); // eslint-disable-line no-console } } // The Highcharts namespace Highcharts = win.Highcharts ? error(16, true) : { win: win }; Highcharts.seriesTypes = seriesTypes; var timers = [], getStyle, // Previous adapter functions inArray, each, grep, offset, map, addEvent, removeEvent, fireEvent, animate, stop; /** * An animator object. One instance applies to one property (attribute or style prop) * on one element. * * @param {object} elem The element to animate. May be a DOM element or a Highcharts SVGElement wrapper. * @param {object} options Animation options, including duration, easing, step and complete. * @param {object} prop The property to animate. */ function Fx(elem, options, prop) { this.options = options; this.elem = elem; this.prop = prop; } Fx.prototype = { /** * Animating a path definition on SVGElement * @returns {undefined} */ dSetter: function () { var start = this.paths[0], end = this.paths[1], ret = [], now = this.now, i = start.length, startVal; if (now === 1) { // land on the final path without adjustment points appended in the ends ret = this.toD; } else if (i === end.length && now < 1) { while (i--) { startVal = parseFloat(start[i]); ret[i] = isNaN(startVal) ? // a letter instruction like M or L start[i] : now * (parseFloat(end[i] - startVal)) + startVal; } } else { // if animation is finished or length not matching, land on right value ret = end; } this.elem.attr('d', ret); }, /** * Update the element with the current animation step * @returns {undefined} */ update: function () { var elem = this.elem, prop = this.prop, // if destroyed, it is null now = this.now, step = this.options.step; // Animation setter defined from outside if (this[prop + 'Setter']) { this[prop + 'Setter'](); // Other animations on SVGElement } else if (elem.attr) { if (elem.element) { elem.attr(prop, now); } // HTML styles, raw HTML content like container size } else { elem.style[prop] = now + this.unit; } if (step) { step.call(elem, now, this); } }, /** * Run an animation */ run: function (from, to, unit) { var self = this, timer = function (gotoEnd) { return timer.stopped ? false : self.step(gotoEnd); }, i; this.startTime = +new Date(); this.start = from; this.end = to; this.unit = unit; this.now = this.start; this.pos = 0; timer.elem = this.elem; if (timer() && timers.push(timer) === 1) { timer.timerId = setInterval(function () { for (i = 0; i < timers.length; i++) { if (!timers[i]()) { timers.splice(i--, 1); } } if (!timers.length) { clearInterval(timer.timerId); } }, 13); } }, /** * Run a single step in the animation * @param {Boolean} gotoEnd Whether to go to then endpoint of the animation after abort * @returns {Boolean} True if animation continues */ step: function (gotoEnd) { var t = +new Date(), ret, done, options = this.options, elem = this.elem, complete = options.complete, duration = options.duration, curAnim = options.curAnim, i; if (elem.attr && !elem.element) { // #2616, element including flag is destroyed ret = false; } else if (gotoEnd || t >= duration + this.startTime) { this.now = this.end; this.pos = 1; this.update(); curAnim[this.prop] = true; done = true; for (i in curAnim) { if (curAnim[i] !== true) { done = false; } } if (done && complete) { complete.call(elem); } ret = false; } else { this.pos = options.easing((t - this.startTime) / duration); this.now = this.start + ((this.end - this.start) * this.pos); this.update(); ret = true; } return ret; }, /** * Prepare start and end values so that the path can be animated one to one */ initPath: function (elem, fromD, toD) { fromD = fromD || ''; var shift = elem.shift, bezier = fromD.indexOf('C') > -1, numParams = bezier ? 7 : 3, endLength, slice, i, start = fromD.split(' '), end = [].concat(toD), // copy isArea = elem.isArea, positionFactor = isArea ? 2 : 1, sixify = function (arr) { // in splines make move points have six parameters like bezier curves i = arr.length; while (i--) { if (arr[i] === M || arr[i] === L) { arr.splice(i + 1, 0, arr[i + 1], arr[i + 2], arr[i + 1], arr[i + 2]); } } }; if (bezier) { sixify(start); sixify(end); } // If shifting points, prepend a dummy point to the end path. For areas, // prepend both at the beginning and end of the path. if (shift <= end.length / numParams && start.length === end.length) { while (shift--) { end = end.slice(0, numParams).concat(end); if (isArea) { end = end.concat(end.slice(end.length - numParams)); } } } elem.shift = 0; // reset for following animations // Copy and append last point until the length matches the end length if (start.length) { endLength = end.length; while (start.length < endLength) { // Pull out the slice that is going to be appended or inserted. In a line graph, // the positionFactor is 1, and the last point is sliced out. In an area graph, // the positionFactor is 2, causing the middle two points to be sliced out, since // an area path starts at left, follows the upper path then turns and follows the // bottom back. slice = start.slice().splice( (start.length / positionFactor) - numParams, numParams * positionFactor ); // Disable first control point if (bezier) { slice[numParams - 6] = slice[numParams - 2]; slice[numParams - 5] = slice[numParams - 1]; } // Now insert the slice, either in the middle (for areas) or at the end (for lines) [].splice.apply( start, [(start.length / positionFactor), 0].concat(slice) ); } } return [start, end]; } }; // End of Fx prototype /** * Extend an object with the members of another * @param {Object} a The object to be extended * @param {Object} b The object to add to the first one */ var extend = Highcharts.extend = function (a, b) { var n; if (!a) { a = {}; } for (n in b) { a[n] = b[n]; } return a; }; /** * Deep merge two or more objects and return a third object. If the first argument is * true, the contents of the second object is copied into the first object. * Previously this function redirected to jQuery.extend(true), but this had two limitations. * First, it deep merged arrays, which lead to workarounds in Highcharts. Second, * it copied properties from extended prototypes. */ function merge() { var i, args = arguments, len, ret = {}, doCopy = function (copy, original) { var value, key; // An object is replacing a primitive if (typeof copy !== 'object') { copy = {}; } for (key in original) { if (original.hasOwnProperty(key)) { value = original[key]; // Copy the contents of objects, but not arrays or DOM nodes if (value && typeof value === 'object' && Object.prototype.toString.call(value) !== '[object Array]' && key !== 'renderTo' && typeof value.nodeType !== 'number') { copy[key] = doCopy(copy[key] || {}, value); // Primitives and arrays are copied over directly } else { copy[key] = original[key]; } } } return copy; }; // If first argument is true, copy into the existing object. Used in setOptions. if (args[0] === true) { ret = args[1]; args = Array.prototype.slice.call(args, 2); } // For each argument, extend the return len = args.length; for (i = 0; i < len; i++) { ret = doCopy(ret, args[i]); } return ret; } /** * Shortcut for parseInt * @param {Object} s * @param {Number} mag Magnitude */ function pInt(s, mag) { return parseInt(s, mag || 10); } /** * Check for string * @param {Object} s */ function isString(s) { return typeof s === 'string'; } /** * Check for object * @param {Object} obj */ function isObject(obj) { return obj && typeof obj === 'object'; } /** * Check for array * @param {Object} obj */ function isArray(obj) { return Object.prototype.toString.call(obj) === '[object Array]'; } /** * Check for number * @param {Object} n */ function isNumber(n) { return typeof n === 'number'; } function log2lin(num) { return math.log(num) / math.LN10; } function lin2log(num) { return math.pow(10, num); } /** * Remove last occurence of an item from an array * @param {Array} arr * @param {Mixed} item */ function erase(arr, item) { var i = arr.length; while (i--) { if (arr[i] === item) { arr.splice(i, 1); break; } } //return arr; } /** * Returns true if the object is not null or undefined. * @param {Object} obj */ function defined(obj) { return obj !== UNDEFINED && obj !== null; } /** * Set or get an attribute or an object of attributes. Can't use jQuery attr because * it attempts to set expando properties on the SVG element, which is not allowed. * * @param {Object} elem The DOM element to receive the attribute(s) * @param {String|Object} prop The property or an abject of key-value pairs * @param {String} value The value if a single property is set */ function attr(elem, prop, value) { var key, ret; // if the prop is a string if (isString(prop)) { // set the value if (defined(value)) { elem.setAttribute(prop, value); // get the value } else if (elem && elem.getAttribute) { // elem not defined when printing pie demo... ret = elem.getAttribute(prop); } // else if prop is defined, it is a hash of key/value pairs } else if (defined(prop) && isObject(prop)) { for (key in prop) { elem.setAttribute(key, prop[key]); } } return ret; } /** * Check if an element is an array, and if not, make it into an array. */ function splat(obj) { return isArray(obj) ? obj : [obj]; } /** * Set a timeout if the delay is given, otherwise perform the function synchronously * @param {Function} fn The function to perform * @param {Number} delay Delay in milliseconds * @param {Ojbect} context The context * @returns {Nubmer} An identifier for the timeout */ function syncTimeout(fn, delay, context) { if (delay) { return setTimeout(fn, delay, context); } fn.call(0, context); } /** * Return the first value that is defined. */ var pick = Highcharts.pick = function () { var args = arguments, i, arg, length = args.length; for (i = 0; i < length; i++) { arg = args[i]; if (arg !== UNDEFINED && arg !== null) { return arg; } } }; /** * Set CSS on a given element * @param {Object} el * @param {Object} styles Style object with camel case property names */ function css(el, styles) { if (isMS && !hasSVG) { // #2686 if (styles && styles.opacity !== UNDEFINED) { styles.filter = 'alpha(opacity=' + (styles.opacity * 100) + ')'; } } extend(el.style, styles); } /** * Utility function to create element with attributes and styles * @param {Object} tag * @param {Object} attribs * @param {Object} styles * @param {Object} parent * @param {Object} nopad */ function createElement(tag, attribs, styles, parent, nopad) { var el = doc.createElement(tag); if (attribs) { extend(el, attribs); } if (nopad) { css(el, { padding: 0, border: 'none', margin: 0 }); } if (styles) { css(el, styles); } if (parent) { parent.appendChild(el); } return el; } /** * Extend a prototyped class by new members * @param {Object} parent * @param {Object} members */ function extendClass(Parent, members) { var object = function () { }; object.prototype = new Parent(); extend(object.prototype, members); return object; } /** * Pad a string to a given length by adding 0 to the beginning * @param {Number} number * @param {Number} length */ function pad(number, length) { return new Array((length || 2) + 1 - String(number).length).join(0) + number; } /** * Return a length based on either the integer value, or a percentage of a base. */ function relativeLength(value, base) { return (/%$/).test(value) ? base * parseFloat(value) / 100 : parseFloat(value); } /** * Wrap a method with extended functionality, preserving the original function * @param {Object} obj The context object that the method belongs to * @param {String} method The name of the method to extend * @param {Function} func A wrapper function callback. This function is called with the same arguments * as the original function, except that the original function is unshifted and passed as the first * argument. */ var wrap = Highcharts.wrap = function (obj, method, func) { var proceed = obj[method]; obj[method] = function () { var args = Array.prototype.slice.call(arguments); args.unshift(proceed); return func.apply(this, args); }; }; function getTZOffset(timestamp) { return ((getTimezoneOffset && getTimezoneOffset(timestamp)) || timezoneOffset || 0) * 60000; } /** * Based on http://www.php.net/manual/en/function.strftime.php * @param {String} format * @param {Number} timestamp * @param {Boolean} capitalize */ dateFormat = function (format, timestamp, capitalize) { if (!defined(timestamp) || isNaN(timestamp)) { return defaultOptions.lang.invalidDate || ''; } format = pick(format, '%Y-%m-%d %H:%M:%S'); var date = new Date(timestamp - getTZOffset(timestamp)), key, // used in for constuct below // get the basic time values hours = date[getHours](), day = date[getDay](), dayOfMonth = date[getDate](), month = date[getMonth](), fullYear = date[getFullYear](), lang = defaultOptions.lang, langWeekdays = lang.weekdays, // List all format keys. Custom formats can be added from the outside. replacements = extend({ // Day 'a': langWeekdays[day].substr(0, 3), // Short weekday, like 'Mon' 'A': langWeekdays[day], // Long weekday, like 'Monday' 'd': pad(dayOfMonth), // Two digit day of the month, 01 to 31 'e': dayOfMonth, // Day of the month, 1 through 31 'w': day, // Week (none implemented) //'W': weekNumber(), // Month 'b': lang.shortMonths[month], // Short month, like 'Jan' 'B': lang.months[month], // Long month, like 'January' 'm': pad(month + 1), // Two digit month number, 01 through 12 // Year 'y': fullYear.toString().substr(2, 2), // Two digits year, like 09 for 2009 'Y': fullYear, // Four digits year, like 2009 // Time 'H': pad(hours), // Two digits hours in 24h format, 00 through 23 'k': hours, // Hours in 24h format, 0 through 23 'I': pad((hours % 12) || 12), // Two digits hours in 12h format, 00 through 11 'l': (hours % 12) || 12, // Hours in 12h format, 1 through 12 'M': pad(date[getMinutes]()), // Two digits minutes, 00 through 59 'p': hours < 12 ? 'AM' : 'PM', // Upper case AM or PM 'P': hours < 12 ? 'am' : 'pm', // Lower case AM or PM 'S': pad(date.getSeconds()), // Two digits seconds, 00 through 59 'L': pad(mathRound(timestamp % 1000), 3) // Milliseconds (naming from Ruby) }, Highcharts.dateFormats); // do the replaces for (key in replacements) { while (format.indexOf('%' + key) !== -1) { // regex would do it in one line, but this is faster format = format.replace('%' + key, typeof replacements[key] === 'function' ? replacements[key](timestamp) : replacements[key]); } } // Optionally capitalize the string and return return capitalize ? format.substr(0, 1).toUpperCase() + format.substr(1) : format; }; /** * Format a single variable. Similar to sprintf, without the % prefix. */ function formatSingle(format, val) { var floatRegex = /f$/, decRegex = /\.([0-9])/, lang = defaultOptions.lang, decimals; if (floatRegex.test(format)) { // float decimals = format.match(decRegex); decimals = decimals ? decimals[1] : -1; if (val !== null) { val = Highcharts.numberFormat( val, decimals, lang.decimalPoint, format.indexOf(',') > -1 ? lang.thousandsSep : '' ); } } else { val = dateFormat(format, val); } return val; } /** * Format a string according to a subset of the rules of Python's String.format method. */ function format(str, ctx) { var splitter = '{', isInside = false, segment, valueAndFormat, path, i, len, ret = [], val, index; while ((index = str.indexOf(splitter)) !== -1) { segment = str.slice(0, index); if (isInside) { // we're on the closing bracket looking back valueAndFormat = segment.split(':'); path = valueAndFormat.shift().split('.'); // get first and leave format len = path.length; val = ctx; // Assign deeper paths for (i = 0; i < len; i++) { val = val[path[i]]; } // Format the replacement if (valueAndFormat.length) { val = formatSingle(valueAndFormat.join(':'), val); } // Push the result and advance the cursor ret.push(val); } else { ret.push(segment); } str = str.slice(index + 1); // the rest isInside = !isInside; // toggle splitter = isInside ? '}' : '{'; // now look for next matching bracket } ret.push(str); return ret.join(''); } /** * Get the magnitude of a number */ function getMagnitude(num) { return math.pow(10, mathFloor(math.log(num) / math.LN10)); } /** * Take an interval and normalize it to multiples of 1, 2, 2.5 and 5 * @param {Number} interval * @param {Array} multiples * @param {Number} magnitude * @param {Object} options */ function normalizeTickInterval(interval, multiples, magnitude, allowDecimals, preventExceed) { var normalized, i, retInterval = interval; // round to a tenfold of 1, 2, 2.5 or 5 magnitude = pick(magnitude, 1); normalized = interval / magnitude; // multiples for a linear scale if (!multiples) { multiples = [1, 2, 2.5, 5, 10]; // the allowDecimals option if (allowDecimals === false) { if (magnitude === 1) { multiples = [1, 2, 5, 10]; } else if (magnitude <= 0.1) { multiples = [1 / magnitude]; } } } // normalize the interval to the nearest multiple for (i = 0; i < multiples.length; i++) { retInterval = multiples[i]; if ((preventExceed && retInterval * magnitude >= interval) || // only allow tick amounts smaller than natural (!preventExceed && (normalized <= (multiples[i] + (multiples[i + 1] || multiples[i])) / 2))) { break; } } // multiply back to the correct magnitude retInterval *= magnitude; return retInterval; } /** * Utility method that sorts an object array and keeping the order of equal items. * ECMA script standard does not specify the behaviour when items are equal. */ function stableSort(arr, sortFunction) { var length = arr.length, sortValue, i; // Add index to each item for (i = 0; i < length; i++) { arr[i].safeI = i; // stable sort index } arr.sort(function (a, b) { sortValue = sortFunction(a, b); return sortValue === 0 ? a.safeI - b.safeI : sortValue; }); // Remove index from items for (i = 0; i < length; i++) { delete arr[i].safeI; // stable sort index } } /** * Non-recursive method to find the lowest member of an array. Math.min raises a maximum * call stack size exceeded error in Chrome when trying to apply more than 150.000 points. This * method is slightly slower, but safe. */ function arrayMin(data) { var i = data.length, min = data[0]; while (i--) { if (data[i] < min) { min = data[i]; } } return min; } /** * Non-recursive method to find the lowest member of an array. Math.min raises a maximum * call stack size exceeded error in Chrome when trying to apply more than 150.000 points. This * method is slightly slower, but safe. */ function arrayMax(data) { var i = data.length, max = data[0]; while (i--) { if (data[i] > max) { max = data[i]; } } return max; } /** * Utility method that destroys any SVGElement or VMLElement that are properties on the given object. * It loops all properties and invokes destroy if there is a destroy method. The property is * then delete'ed. * @param {Object} The object to destroy properties on * @param {Object} Exception, do not destroy this property, only delete it. */ function destroyObjectProperties(obj, except) { var n; for (n in obj) { // If the object is non-null and destroy is defined if (obj[n] && obj[n] !== except && obj[n].destroy) { // Invoke the destroy obj[n].destroy(); } // Delete the property from the object. delete obj[n]; } } /** * Discard an element by moving it to the bin and delete * @param {Object} The HTML node to discard */ function discardElement(element) { // create a garbage bin element, not part of the DOM if (!garbageBin) { garbageBin = createElement(DIV); } // move the node and empty bin if (element) { garbageBin.appendChild(element); } garbageBin.innerHTML = ''; } /** * Fix JS round off float errors * @param {Number} num */ function correctFloat(num, prec) { return parseFloat( num.toPrecision(prec || 14) ); } /** * Set the global animation to either a given value, or fall back to the * given chart's animation option * @param {Object} animation * @param {Object} chart */ function setAnimation(animation, chart) { chart.renderer.globalAnimation = pick(animation, chart.animation); } /** * The time unit lookup */ timeUnits = { millisecond: 1, second: 1000, minute: 60000, hour: 3600000, day: 24 * 3600000, week: 7 * 24 * 3600000, month: 28 * 24 * 3600000, year: 364 * 24 * 3600000 }; /** * Format a number and return a string based on input settings * @param {Number} number The input number to format * @param {Number} decimals The amount of decimals * @param {String} decimalPoint The decimal point, defaults to the one given in the lang options * @param {String} thousandsSep The thousands separator, defaults to the one given in the lang options */ Highcharts.numberFormat = function (number, decimals, decimalPoint, thousandsSep) { number = +number || 0; var lang = defaultOptions.lang, origDec = (number.toString().split('.')[1] || '').length, decimalComponent, strinteger, thousands, absNumber = Math.abs(number), ret; if (decimals === -1) { decimals = Math.min(origDec, 20); // Preserve decimals. Not huge numbers (#3793). } else if (isNaN(decimals)) { decimals = 2; } // A string containing the positive integer component of the number strinteger = String(pInt(absNumber.toFixed(decimals))); // Leftover after grouping into thousands. Can be 0, 1 or 3. thousands = strinteger.length > 3 ? strinteger.length % 3 : 0; // Language decimalPoint = pick(decimalPoint, lang.decimalPoint); thousandsSep = pick(thousandsSep, lang.thousandsSep); // Start building the return ret = number < 0 ? '-' : ''; // Add the leftover after grouping into thousands. For example, in the number 42 000 000, // this line adds 42. ret += thousands ? strinteger.substr(0, thousands) + thousandsSep : ''; // Add the remaining thousands groups, joined by the thousands separator ret += strinteger.substr(thousands).replace(/(\d{3})(?=\d)/g, '$1' + thousandsSep); // Add the decimal point and the decimal component if (+decimals) { // Get the decimal component, and add power to avoid rounding errors with float numbers (#4573) decimalComponent = Math.abs(absNumber - strinteger + Math.pow(10, -Math.max(decimals, origDec) - 1)); ret += decimalPoint + decimalComponent.toFixed(decimals).slice(2); } return ret; }; /** * Easing definition * @param {Number} pos Current position, ranging from 0 to 1 */ Math.easeInOutSine = function (pos) { return -0.5 * (Math.cos(Math.PI * pos) - 1); }; /** * Internal method to return CSS value for given element and property */ getStyle = function (el, prop) { var style; // For width and height, return the actual inner pixel size (#4913) if (prop === 'width') { return Math.min(el.offsetWidth, el.scrollWidth) - getStyle(el, 'padding-left') - getStyle(el, 'padding-right'); } else if (prop === 'height') { return Math.min(el.offsetHeight, el.scrollHeight) - getStyle(el, 'padding-top') - getStyle(el, 'padding-bottom'); } // Otherwise, get the computed style style = win.getComputedStyle(el, undefined); return style && pInt(style.getPropertyValue(prop)); }; /** * Return the index of an item in an array, or -1 if not found */ inArray = function (item, arr) { return arr.indexOf ? arr.indexOf(item) : [].indexOf.call(arr, item); }; /** * Filter an array */ grep = function (elements, callback) { return [].filter.call(elements, callback); }; /** * Map an array */ map = function (arr, fn) { var results = [], i = 0, len = arr.length; for (; i < len; i++) { results[i] = fn.call(arr[i], arr[i], i, arr); } return results; }; /** * Get the element's offset position, corrected by overflow:auto. */ offset = function (el) { var docElem = doc.documentElement, box = el.getBoundingClientRect(); return { top: box.top + (win.pageYOffset || docElem.scrollTop) - (docElem.clientTop || 0), left: box.left + (win.pageXOffset || docElem.scrollLeft) - (docElem.clientLeft || 0) }; }; /** * Stop running animation. * A possible extension to this would be to stop a single property, when * we want to continue animating others. Then assign the prop to the timer * in the Fx.run method, and check for the prop here. This would be an improvement * in all cases where we stop the animation from .attr. Instead of stopping * everything, we can just stop the actual attributes we're setting. */ stop = function (el) { var i = timers.length; // Remove timers related to this element (#4519) while (i--) { if (timers[i].elem === el) { timers[i].stopped = true; // #4667 } } }; /** * Utility for iterating over an array. * @param {Array} arr * @param {Function} fn */ each = function (arr, fn) { // modern browsers return Array.prototype.forEach.call(arr, fn); }; /** * Add an event listener */ addEvent = function (el, type, fn) { var events = el.hcEvents = el.hcEvents || {}; function wrappedFn(e) { e.target = e.srcElement || win; // #2820 fn.call(el, e); } // Handle DOM events in modern browsers if (el.addEventListener) { el.addEventListener(type, fn, false); // Handle old IE implementation } else if (el.attachEvent) { if (!el.hcEventsIE) { el.hcEventsIE = {}; } // Link wrapped fn with original fn, so we can get this in removeEvent el.hcEventsIE[fn.toString()] = wrappedFn; el.attachEvent('on' + type, wrappedFn); } if (!events[type]) { events[type] = []; } events[type].push(fn); }; /** * Remove event added with addEvent */ removeEvent = function (el, type, fn) { var events, hcEvents = el.hcEvents, index; function removeOneEvent(type, fn) { if (el.removeEventListener) { el.removeEventListener(type, fn, false); } else if (el.attachEvent) { fn = el.hcEventsIE[fn.toString()]; el.detachEvent('on' + type, fn); } } function removeAllEvents() { var types, len, n; if (!el.nodeName) { return; // break on non-DOM events } if (type) { types = {}; types[type] = true; } else { types = hcEvents; } for (n in types) { if (hcEvents[n]) { len = hcEvents[n].length; while (len--) { removeOneEvent(n, hcEvents[n][len]); } } } } if (hcEvents) { if (type) { events = hcEvents[type] || []; if (fn) { index = inArray(fn, events); if (index > -1) { events.splice(index, 1); hcEvents[type] = events; } removeOneEvent(type, fn); } else { removeAllEvents(); hcEvents[type] = []; } } else { removeAllEvents(); el.hcEvents = {}; } } }; /** * Fire an event on a custom object */ fireEvent = function (el, type, eventArguments, defaultFunction) { var e, hcEvents = el.hcEvents, events, len, i, preventDefault, fn; eventArguments = eventArguments || {}; if (doc.createEvent && (el.dispatchEvent || el.fireEvent)) { e = doc.createEvent('Events'); e.initEvent(type, true, true); e.target = el; extend(e, eventArguments); if (el.dispatchEvent) { el.dispatchEvent(e); } else { el.fireEvent(type, e); } } else if (hcEvents) { events = hcEvents[type] || []; len = events.length; // Attach a simple preventDefault function to skip default handler if called preventDefault = function () { eventArguments.defaultPrevented = true; }; for (i = 0; i < len; i++) { fn = events[i]; // eventArguments is never null here if (eventArguments.stopped) { return; } eventArguments.preventDefault = preventDefault; eventArguments.target = el; // If the type is not set, we're running a custom event (#2297). If it is set, // we're running a browser event, and setting it will cause en error in // IE8 (#2465). if (!eventArguments.type) { eventArguments.type = type; } // If the event handler return false, prevent the default handler from executing if (fn.call(el, eventArguments) === false) { eventArguments.preventDefault(); } } } // Run the default if not prevented if (defaultFunction && !eventArguments.defaultPrevented) { defaultFunction(eventArguments); } }; /** * The global animate method, which uses Fx to create individual animators. */ animate = function (el, params, opt) { var start, unit = '', end, fx, args, prop; if (!isObject(opt)) { // Number or undefined/null args = arguments; opt = { duration: args[2], easing: args[3], complete: args[4] }; } if (!isNumber(opt.duration)) { opt.duration = 400; } opt.easing = Math[opt.easing] || Math.easeInOutSine; opt.curAnim = merge(params); for (prop in params) { fx = new Fx(el, opt, prop); end = null; if (prop === 'd') { fx.paths = fx.initPath( el, el.d, params.d ); fx.toD = params.d; start = 0; end = 1; } else if (el.attr) { start = el.attr(prop); } else { start = parseFloat(getStyle(el, prop)) || 0; if (prop !== 'opacity') { unit = 'px'; } } if (!end) { end = params[prop]; } if (end.match && end.match('px')) { end = end.replace(/px/g, ''); // #4351 } fx.run(start, end, unit); } }; /** * Register Highcharts as a plugin in jQuery */ if (win.jQuery) { win.jQuery.fn.highcharts = function () { var args = [].slice.call(arguments); if (this[0]) { // this[0] is the renderTo div // Create the chart if (args[0]) { new Highcharts[ // eslint-disable-line no-new isString(args[0]) ? args.shift() : 'Chart' // Constructor defaults to Chart ](this[0], args[0], args[1]); return this; } // When called without parameters or with the return argument, return an existing chart return charts[attr(this[0], 'data-highcharts-chart')]; } }; } /** * Compatibility section to add support for legacy IE. This can be removed if old IE * support is not needed. */ if (doc && !doc.defaultView) { getStyle = function (el, prop) { var val, alias = { width: 'clientWidth', height: 'clientHeight' }[prop]; if (el.style[prop]) { return pInt(el.style[prop]); } if (prop === 'opacity') { prop = 'filter'; } // Getting the rendered width and height if (alias) { el.style.zoom = 1; return el[alias] - 2 * getStyle(el, 'padding'); } val = el.currentStyle[prop.replace(/\-(\w)/g, function (a, b) { return b.toUpperCase(); })]; if (prop === 'filter') { val = val.replace( /alpha\(opacity=([0-9]+)\)/, function (a, b) { return b / 100; } ); } return val === '' ? 1 : pInt(val); }; } if (!Array.prototype.forEach) { each = function (arr, fn) { // legacy var i = 0, len = arr.length; for (; i < len; i++) { if (fn.call(arr[i], arr[i], i, arr) === false) { return i; } } }; } if (!Array.prototype.indexOf) { inArray = function (item, arr) { var len, i = 0; if (arr) { len = arr.length; for (; i < len; i++) { if (arr[i] === item) { return i; } } } return -1; }; } if (!Array.prototype.filter) { grep = function (elements, fn) { var ret = [], i = 0, length = elements.length; for (; i < length; i++) { if (fn(elements[i], i)) { ret.push(elements[i]); } } return ret; }; } //--- End compatibility section --- // Expose utilities Highcharts.Fx = Fx; Highcharts.inArray = inArray; Highcharts.each = each; Highcharts.grep = grep; Highcharts.offset = offset; Highcharts.map = map; Highcharts.addEvent = addEvent; Highcharts.removeEvent = removeEvent; Highcharts.fireEvent = fireEvent; Highcharts.animate = animate; Highcharts.stop = stop; /* **************************************************************************** * Handle the options * *****************************************************************************/ defaultOptions = { colors: ['#7cb5ec', '#434348', '#90ed7d', '#f7a35c', '#8085e9', '#f15c80', '#e4d354', '#2b908f', '#f45b5b', '#91e8e1'], symbols: ['circle', 'diamond', 'square', 'triangle', 'triangle-down'], lang: { loading: 'Loading...', months: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'], shortMonths: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'], weekdays: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'], // invalidDate: '', decimalPoint: '.', numericSymbols: ['k', 'M', 'G', 'T', 'P', 'E'], // SI prefixes used in axis labels resetZoom: 'Reset zoom', resetZoomTitle: 'Reset zoom level 1:1', thousandsSep: ' ' }, global: { useUTC: true, //timezoneOffset: 0, canvasToolsURL: 'http://code.highcharts.com/modules/canvas-tools.js', VMLRadialGradientURL: 'http://code.highcharts.com/maps/4.2.3/gfx/vml-radial-gradient.png' }, chart: { //animation: true, //alignTicks: false, //reflow: true, //className: null, //events: { load, selection }, //margin: [null], //marginTop: null, //marginRight: null, //marginBottom: null, //marginLeft: null, borderColor: '#4572A7', //borderWidth: 0, borderRadius: 0, defaultSeriesType: 'line', ignoreHiddenSeries: true, //inverted: false, //shadow: false, spacing: [10, 10, 15, 10], //spacingTop: 10, //spacingRight: 10, //spacingBottom: 15, //spacingLeft: 10, //style: { // fontFamily: '"Lucida Grande", "Lucida Sans Unicode", Verdana, Arial, Helvetica, sans-serif', // default font // fontSize: '12px' //}, backgroundColor: '#FFFFFF', //plotBackgroundColor: null, plotBorderColor: '#C0C0C0', //plotBorderWidth: 0, //plotShadow: false, //zoomType: '' resetZoomButton: { theme: { zIndex: 20 }, position: { align: 'right', x: -10, //verticalAlign: 'top', y: 10 } // relativeTo: 'plot' } }, title: { text: 'Chart title', align: 'center', // floating: false, margin: 15, // x: 0, // verticalAlign: 'top', // y: null, style: { color: '#333333', fontSize: '18px' } }, subtitle: { text: '', align: 'center', // floating: false // x: 0, // verticalAlign: 'top', // y: null, style: { color: '#555555' } }, plotOptions: { line: { // base series options allowPointSelect: false, showCheckbox: false, animation: { duration: 1000 }, //connectNulls: false, //cursor: 'default', //clip: true, //dashStyle: null, //enableMouseTracking: true, events: {}, //legendIndex: 0, //linecap: 'round', lineWidth: 2, //shadow: false, // stacking: null, marker: { //enabled: true, //symbol: null, lineWidth: 0, radius: 4, lineColor: '#FFFFFF', //fillColor: null, states: { // states for a single point hover: { enabled: true, lineWidthPlus: 1, radiusPlus: 2 }, select: { fillColor: '#FFFFFF', lineColor: '#000000', lineWidth: 2 } } }, point: { events: {} }, dataLabels: { align: 'center', // defer: true, // enabled: false, formatter: function () { return this.y === null ? '' : Highcharts.numberFormat(this.y, -1); }, style: { color: 'contrast', fontSize: '11px', fontWeight: 'bold', textShadow: '0 0 6px contrast, 0 0 3px contrast' }, verticalAlign: 'bottom', // above singular point x: 0, y: 0, // backgroundColor: undefined, // borderColor: undefined, // borderRadius: undefined, // borderWidth: undefined, padding: 5 // shadow: false }, cropThreshold: 300, // draw points outside the plot area when the number of points is less than this pointRange: 0, //pointStart: 0, //pointInterval: 1, //showInLegend: null, // auto: true for standalone series, false for linked series softThreshold: true, states: { // states for the entire series hover: { //enabled: false, lineWidthPlus: 1, marker: { // lineWidth: base + 1, // radius: base + 1 }, halo: { size: 10, opacity: 0.25 } }, select: { marker: {} } }, stickyTracking: true, //tooltip: { //pointFormat: '<span style="color:{point.color}">\u25CF</span> {series.name}: <b>{point.y}</b>' //valueDecimals: null, //xDateFormat: '%A, %b %e, %Y', //valuePrefix: '', //ySuffix: '' //} turboThreshold: 1000 // zIndex: null } }, labels: { //items: [], style: { //font: defaultFont, position: ABSOLUTE, color: '#3E576F' } }, legend: { enabled: true, align: 'center', //floating: false, layout: 'horizontal', labelFormatter: function () { return this.name; }, //borderWidth: 0, borderColor: '#909090', borderRadius: 0, navigation: { // animation: true, activeColor: '#274b6d', // arrowSize: 12 inactiveColor: '#CCC' // style: {} // text styles }, // margin: 20, // reversed: false, shadow: false, // backgroundColor: null, /*style: { padding: '5px' },*/ itemStyle: { color: '#333333', fontSize: '12px', fontWeight: 'bold' }, itemHoverStyle: { //cursor: 'pointer', removed as of #601 color: '#000' }, itemHiddenStyle: { color: '#CCC' }, itemCheckboxStyle: { position: ABSOLUTE, width: '13px', // for IE precision height: '13px' }, // itemWidth: undefined, // symbolRadius: 0, // symbolWidth: 16, symbolPadding: 5, verticalAlign: 'bottom', // width: undefined, x: 0, y: 0, title: { //text: null, style: { fontWeight: 'bold' } } }, loading: { // hideDuration: 100, labelStyle: { fontWeight: 'bold', position: RELATIVE, top: '45%' }, // showDuration: 0, style: { position: ABSOLUTE, backgroundColor: 'white', opacity: 0.5, textAlign: 'center' } }, tooltip: { enabled: true, animation: hasSVG, //crosshairs: null, backgroundColor: 'rgba(249, 249, 249, .85)', borderWidth: 1, borderRadius: 3, dateTimeLabelFormats: { millisecond: '%A, %b %e, %H:%M:%S.%L', second: '%A, %b %e, %H:%M:%S', minute: '%A, %b %e, %H:%M', hour: '%A, %b %e, %H:%M', day: '%A, %b %e, %Y', week: 'Week from %A, %b %e, %Y', month: '%B %Y', year: '%Y' }, footerFormat: '', //formatter: defaultFormatter, headerFormat: '<span style="font-size: 10px">{point.key}</span><br/>', pointFormat: '<span style="color:{point.color}">\u25CF</span> {series.name}: <b>{point.y}</b><br/>', shadow: true, //shape: 'callout', //shared: false, snap: isTouchDevice ? 25 : 10, style: { color: '#333333', cursor: 'default', fontSize: '12px', padding: '8px', pointerEvents: 'none', // #1686 http://caniuse.com/#feat=pointer-events whiteSpace: 'nowrap' } //xDateFormat: '%A, %b %e, %Y', //valueDecimals: null, //valuePrefix: '', //valueSuffix: '' }, credits: { enabled: true, text: 'Highcharts.com', href: 'http://www.highcharts.com', position: { align: 'right', x: -10, verticalAlign: 'bottom', y: -5 }, style: { cursor: 'pointer', color: '#909090', fontSize: '9px' } } }; /** * Set the time methods globally based on the useUTC option. Time method can be either * local time or UTC (default). */ function setTimeMethods() { var globalOptions = defaultOptions.global, useUTC = globalOptions.useUTC, GET = useUTC ? 'getUTC' : 'get', SET = useUTC ? 'setUTC' : 'set'; Date = globalOptions.Date || win.Date; timezoneOffset = useUTC && globalOptions.timezoneOffset; getTimezoneOffset = useUTC && globalOptions.getTimezoneOffset; makeTime = function (year, month, date, hours, minutes, seconds) { var d; if (useUTC) { d = Date.UTC.apply(0, arguments); d += getTZOffset(d); } else { d = new Date( year, month, pick(date, 1), pick(hours, 0), pick(minutes, 0), pick(seconds, 0) ).getTime(); } return d; }; getMinutes = GET + 'Minutes'; getHours = GET + 'Hours'; getDay = GET + 'Day'; getDate = GET + 'Date'; getMonth = GET + 'Month'; getFullYear = GET + 'FullYear'; setMilliseconds = SET + 'Milliseconds'; setSeconds = SET + 'Seconds'; setMinutes = SET + 'Minutes'; setHours = SET + 'Hours'; setDate = SET + 'Date'; setMonth = SET + 'Month'; setFullYear = SET + 'FullYear'; } /** * Merge the default options with custom options and return the new options structure * @param {Object} options The new custom options */ function setOptions(options) { // Copy in the default options defaultOptions = merge(true, defaultOptions, options); // Apply UTC setTimeMethods(); return defaultOptions; } /** * Get the updated default options. Until 3.0.7, merely exposing defaultOptions for outside modules * wasn't enough because the setOptions method created a new object. */ function getOptions() { return defaultOptions; } // Series defaults var defaultPlotOptions = defaultOptions.plotOptions, defaultSeriesOptions = defaultPlotOptions.line; // set the default time methods setTimeMethods(); /** * Handle color operations. The object methods are chainable. * @param {String} input The input color in either rbga or hex format */ function Color(input) { // Backwards compatibility, allow instanciation without new if (!(this instanceof Color)) { return new Color(input); } // Initialize this.init(input); } Color.prototype = { // Collection of parsers. This can be extended from the outside by pushing parsers // to Highcharts.Colors.prototype.parsers. parsers: [{ // RGBA color regex: /rgba\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]?(?:\.[0-9]+)?)\s*\)/, parse: function (result) { return [pInt(result[1]), pInt(result[2]), pInt(result[3]), parseFloat(result[4], 10)]; } }, { // HEX color regex: /#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/, parse: function (result) { return [pInt(result[1], 16), pInt(result[2], 16), pInt(result[3], 16), 1]; } }, { // RGB color regex: /rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/, parse: function (result) { return [pInt(result[1]), pInt(result[2]), pInt(result[3]), 1]; } }], /** * Parse the input color to rgba array * @param {String} input */ init: function (input) { var result, rgba, i, parser; this.input = input; // Gradients if (input && input.stops) { this.stops = map(input.stops, function (stop) { return new Color(stop[1]); }); // Solid colors } else { i = this.parsers.length; while (i-- && !rgba) { parser = this.parsers[i]; result = parser.regex.exec(input); if (result) { rgba = parser.parse(result); } } } this.rgba = rgba || []; }, /** * Return the color a specified format * @param {String} format */ get: function (format) { var input = this.input, rgba = this.rgba, ret; if (this.stops) { ret = merge(input); ret.stops = [].concat(ret.stops); each(this.stops, function (stop, i) { ret.stops[i] = [ret.stops[i][0], stop.get(format)]; }); // it's NaN if gradient colors on a column chart } else if (rgba && !isNaN(rgba[0])) { if (format === 'rgb' || (!format && rgba[3] === 1)) { ret = 'rgb(' + rgba[0] + ',' + rgba[1] + ',' + rgba[2] + ')'; } else if (format === 'a') { ret = rgba[3]; } else { ret = 'rgba(' + rgba.join(',') + ')'; } } else { ret = input; } return ret; }, /** * Brighten the color * @param {Number} alpha */ brighten: function (alpha) { var i, rgba = this.rgba; if (this.stops) { each(this.stops, function (stop) { stop.brighten(alpha); }); } else if (isNumber(alpha) && alpha !== 0) { for (i = 0; i < 3; i++) { rgba[i] += pInt(alpha * 255); if (rgba[i] < 0) { rgba[i] = 0; } if (rgba[i] > 255) { rgba[i] = 255; } } } return this; }, /** * Set the color's opacity to a given alpha value * @param {Number} alpha */ setOpacity: function (alpha) { this.rgba[3] = alpha; return this; } }; /** * A wrapper object for SVG elements */ function SVGElement() {} SVGElement.prototype = { // Default base for animation opacity: 1, // For labels, these CSS properties are applied to the <text> node directly textProps: ['direction', 'fontSize', 'fontWeight', 'fontFamily', 'fontStyle', 'color', 'lineHeight', 'width', 'textDecoration', 'textOverflow', 'textShadow'], /** * Initialize the SVG renderer * @param {Object} renderer * @param {String} nodeName */ init: function (renderer, nodeName) { var wrapper = this; wrapper.element = nodeName === 'span' ? createElement(nodeName) : doc.createElementNS(SVG_NS, nodeName); wrapper.renderer = renderer; }, /** * Animate a given attribute * @param {Object} params * @param {Number} options Options include duration, easing, step and complete * @param {Function} complete Function to perform at the end of animation */ animate: function (params, options, complete) { var animOptions = pick(options, this.renderer.globalAnimation, true); stop(this); // stop regardless of animation actually running, or reverting to .attr (#607) if (animOptions) { animOptions = merge(animOptions, {}); //#2625 if (complete) { // allows using a callback with the global animation without overwriting it animOptions.complete = complete; } animate(this, params, animOptions); } else { this.attr(params, null, complete); } return this; }, /** * Build an SVG gradient out of a common JavaScript configuration object */ colorGradient: function (color, prop, elem) { var renderer = this.renderer, colorObject, gradName, gradAttr, radAttr, gradients, gradientObject, stops, stopColor, stopOpacity, radialReference, n, id, key = [], value; // Apply linear or radial gradients if (color.linearGradient) { gradName = 'linearGradient'; } else if (color.radialGradient) { gradName = 'radialGradient'; } if (gradName) { gradAttr = color[gradName]; gradients = renderer.gradients; stops = color.stops; radialReference = elem.radialReference; // Keep < 2.2 kompatibility if (isArray(gradAttr)) { color[gradName] = gradAttr = { x1: gradAttr[0], y1: gradAttr[1], x2: gradAttr[2], y2: gradAttr[3], gradientUnits: 'userSpaceOnUse' }; } // Correct the radial gradient for the radial reference system if (gradName === 'radialGradient' && radialReference && !defined(gradAttr.gradientUnits)) { radAttr = gradAttr; // Save the radial attributes for updating gradAttr = merge(gradAttr, renderer.getRadialAttr(radialReference, radAttr), { gradientUnits: 'userSpaceOnUse' } ); } // Build the unique key to detect whether we need to create a new element (#1282) for (n in gradAttr) { if (n !== 'id') { key.push(n, gradAttr[n]); } } for (n in stops) { key.push(stops[n]); } key = key.join(','); // Check if a gradient object with the same config object is created within this renderer if (gradients[key]) { id = gradients[key].attr('id'); } else { // Set the id and create the element gradAttr.id = id = PREFIX + idCounter++; gradients[key] = gradientObject = renderer.createElement(gradName) .attr(gradAttr) .add(renderer.defs); gradientObject.radAttr = radAttr; // The gradient needs to keep a list of stops to be able to destroy them gradientObject.stops = []; each(stops, function (stop) { var stopObject; if (stop[1].indexOf('rgba') === 0) { colorObject = Color(stop[1]); stopColor = colorObject.get('rgb'); stopOpacity = colorObject.get('a'); } else { stopColor = stop[1]; stopOpacity = 1; } stopObject = renderer.createElement('stop').attr({ offset: stop[0], 'stop-color': stopColor, 'stop-opacity': stopOpacity }).add(gradientObject); // Add the stop element to the gradient gradientObject.stops.push(stopObject); }); } // Set the reference to the gradient object value = 'url(' + renderer.url + '#' + id + ')'; elem.setAttribute(prop, value); elem.gradient = key; // Allow the color to be concatenated into tooltips formatters etc. (#2995) color.toString = function () { return value; }; } }, /** * Apply a polyfill to the text-stroke CSS property, by copying the text element * and apply strokes to the copy. * * Contrast checks at http://jsfiddle.net/highcharts/43soe9m1/2/ */ applyTextShadow: function (textShadow) { var elem = this.element, tspans, hasContrast = textShadow.indexOf('contrast') !== -1, styles = {}, forExport = this.renderer.forExport, // IE10 and IE11 report textShadow in elem.style even though it doesn't work. Check // this again with new IE release. In exports, the rendering is passed to PhantomJS. supports = forExport || (elem.style.textShadow !== UNDEFINED && !isMS); // When the text shadow is set to contrast, use dark stroke for light text and vice versa if (hasContrast) { styles.textShadow = textShadow = textShadow.replace(/contrast/g, this.renderer.getContrast(elem.style.fill)); } // Safari with retina displays as well as PhantomJS bug (#3974). Firefox does not tolerate this, // it removes the text shadows. if (isWebKit || forExport) { styles.textRendering = 'geometricPrecision'; } /* Selective side-by-side testing in supported browser (http://jsfiddle.net/highcharts/73L1ptrh/) if (elem.textContent.indexOf('2.') === 0) { elem.style['text-shadow'] = 'none'; supports = false; } // */ // No reason to polyfill, we've got native support if (supports) { this.css(styles); // Apply altered textShadow or textRendering workaround } else { this.fakeTS = true; // Fake text shadow // In order to get the right y position of the clones, // copy over the y setter this.ySetter = this.xSetter; tspans = [].slice.call(elem.getElementsByTagName('tspan')); each(textShadow.split(/\s?,\s?/g), function (textShadow) { var firstChild = elem.firstChild, color, strokeWidth; textShadow = textShadow.split(' '); color = textShadow[textShadow.length - 1]; // Approximately tune the settings to the text-shadow behaviour strokeWidth = textShadow[textShadow.length - 2]; if (strokeWidth) { each(tspans, function (tspan, y) { var clone; // Let the first line start at the correct X position if (y === 0) { tspan.setAttribute('x', elem.getAttribute('x')); y = elem.getAttribute('y'); tspan.setAttribute('y', y || 0); if (y === null) { elem.setAttribute('y', 0); } } // Create the clone and apply shadow properties clone = tspan.cloneNode(1); attr(clone, { 'class': PREFIX + 'text-shadow', 'fill': color, 'stroke': color, 'stroke-opacity': 1 / mathMax(pInt(strokeWidth), 3), 'stroke-width': strokeWidth, 'stroke-linejoin': 'round' }); elem.insertBefore(clone, firstChild); }); } }); } }, /** * Set or get a given attribute * @param {Object|String} hash * @param {Mixed|Undefined} val */ attr: function (hash, val, complete) { var key, value, element = this.element, hasSetSymbolSize, ret = this, skipAttr, setter; // single key-value pair if (typeof hash === 'string' && val !== UNDEFINED) { key = hash; hash = {}; hash[key] = val; } // used as a getter: first argument is a string, second is undefined if (typeof hash === 'string') { ret = (this[hash + 'Getter'] || this._defaultGetter).call(this, hash, element); // setter } else { for (key in hash) { value = hash[key]; skipAttr = false; if (this.symbolName && /^(x|y|width|height|r|start|end|innerR|anchorX|anchorY)/.test(key)) { if (!hasSetSymbolSize) { this.symbolAttr(hash); hasSetSymbolSize = true; } skipAttr = true; } if (this.rotation && (key === 'x' || key === 'y')) { this.doTransform = true; } if (!skipAttr) { setter = this[key + 'Setter'] || this._defaultSetter; setter.call(this, value, key, element); // Let the shadow follow the main element if (this.shadows && /^(width|height|visibility|x|y|d|transform|cx|cy|r)$/.test(key)) { this.updateShadows(key, value, setter); } } } // Update transform. Do this outside the loop to prevent redundant updating for batch setting // of attributes. if (this.doTransform) { this.updateTransform(); this.doTransform = false; } } // In accordance with animate, run a complete callback if (complete) { complete(); } return ret; }, /** * Update the shadow elements with new attributes * @param {String} key The attribute name * @param {String|Number} value The value of the attribute * @param {Function} setter The setter function, inherited from the parent wrapper * @returns {undefined} */ updateShadows: function (key, value, setter) { var shadows = this.shadows, i = shadows.length; while (i--) { setter.call( null, key === 'height' ? Math.max(value - (shadows[i].cutHeight || 0), 0) : key === 'd' ? this.d : value, key, shadows[i] ); } }, /** * Add a class name to an element */ addClass: function (className) { var element = this.element, currentClassName = attr(element, 'class') || ''; if (currentClassName.indexOf(className) === -1) { attr(element, 'class', currentClassName + ' ' + className); } return this; }, /* hasClass and removeClass are not (yet) needed hasClass: function (className) { return attr(this.element, 'class').indexOf(className) !== -1; }, removeClass: function (className) { attr(this.element, 'class', attr(this.element, 'class').replace(className, '')); return this; }, */ /** * If one of the symbol size affecting parameters are changed, * check all the others only once for each call to an element's * .attr() method * @param {Object} hash */ symbolAttr: function (hash) { var wrapper = this; each(['x', 'y', 'r', 'start', 'end', 'width', 'height', 'innerR', 'anchorX', 'anchorY'], function (key) { wrapper[key] = pick(hash[key], wrapper[key]); }); wrapper.attr({ d: wrapper.renderer.symbols[wrapper.symbolName]( wrapper.x, wrapper.y, wrapper.width, wrapper.height, wrapper ) }); }, /** * Apply a clipping path to this object * @param {String} id */ clip: function (clipRect) { return this.attr('clip-path', clipRect ? 'url(' + this.renderer.url + '#' + clipRect.id + ')' : NONE); }, /** * Calculate the coordinates needed for drawing a rectangle crisply and return the * calculated attributes * @param {Number} strokeWidth * @param {Number} x * @param {Number} y * @param {Number} width * @param {Number} height */ crisp: function (rect) { var wrapper = this, key, attribs = {}, normalizer, strokeWidth = wrapper.strokeWidth || 0; normalizer = mathRound(strokeWidth) % 2 / 2; // mathRound because strokeWidth can sometimes have roundoff errors // normalize for crisp edges rect.x = mathFloor(rect.x || wrapper.x || 0) + normalizer; rect.y = mathFloor(rect.y || wrapper.y || 0) + normalizer; rect.width = mathFloor((rect.width || wrapper.width || 0) - 2 * normalizer); rect.height = mathFloor((rect.height || wrapper.height || 0) - 2 * normalizer); rect.strokeWidth = strokeWidth; for (key in rect) { if (wrapper[key] !== rect[key]) { // only set attribute if changed wrapper[key] = attribs[key] = rect[key]; } } return attribs; }, /** * Set styles for the element * @param {Object} styles */ css: function (styles) { var elemWrapper = this, oldStyles = elemWrapper.styles, newStyles = {}, elem = elemWrapper.element, textWidth, n, serializedCss = '', hyphenate, hasNew = !oldStyles; // convert legacy if (styles && styles.color) { styles.fill = styles.color; } // Filter out existing styles to increase performance (#2640) if (oldStyles) { for (n in styles) { if (styles[n] !== oldStyles[n]) { newStyles[n] = styles[n]; hasNew = true; } } } if (hasNew) { textWidth = elemWrapper.textWidth = (styles && styles.width && elem.nodeName.toLowerCase() === 'text' && pInt(styles.width)) || elemWrapper.textWidth; // #3501 // Merge the new styles with the old ones if (oldStyles) { styles = extend( oldStyles, newStyles ); } // store object elemWrapper.styles = styles; if (textWidth && (useCanVG || (!hasSVG && elemWrapper.renderer.forExport))) { delete styles.width; } // serialize and set style attribute if (isMS && !hasSVG) { css(elemWrapper.element, styles); } else { hyphenate = function (a, b) { return '-' + b.toLowerCase(); }; for (n in styles) { serializedCss += n.replace(/([A-Z])/g, hyphenate) + ':' + styles[n] + ';'; } attr(elem, 'style', serializedCss); // #1881 } // re-build text if (textWidth && elemWrapper.added) { elemWrapper.renderer.buildText(elemWrapper); } } return elemWrapper; }, /** * Add an event listener * @param {String} eventType * @param {Function} handler */ on: function (eventType, handler) { var svgElement = this, element = svgElement.element; // touch if (hasTouch && eventType === 'click') { element.ontouchstart = function (e) { svgElement.touchEventFired = Date.now(); e.preventDefault(); handler.call(element, e); }; element.onclick = function (e) { if (userAgent.indexOf('Android') === -1 || Date.now() - (svgElement.touchEventFired || 0) > 1100) { // #2269 handler.call(element, e); } }; } else { // simplest possible event model for internal use element['on' + eventType] = handler; } return this; }, /** * Set the coordinates needed to draw a consistent radial gradient across * pie slices regardless of positioning inside the chart. The format is * [centerX, centerY, diameter] in pixels. */ setRadialReference: function (coordinates) { var existingGradient = this.renderer.gradients[this.element.gradient]; this.element.radialReference = coordinates; // On redrawing objects with an existing gradient, the gradient needs // to be repositioned (#3801) if (existingGradient && existingGradient.radAttr) { existingGradient.animate( this.renderer.getRadialAttr( coordinates, existingGradient.radAttr ) ); } return this; }, /** * Move an object and its children by x and y values * @param {Number} x * @param {Number} y */ translate: function (x, y) { return this.attr({ translateX: x, translateY: y }); }, /** * Invert a group, rotate and flip */ invert: function () { var wrapper = this; wrapper.inverted = true; wrapper.updateTransform(); return wrapper; }, /** * Private method to update the transform attribute based on internal * properties */ updateTransform: function () { var wrapper = this, translateX = wrapper.translateX || 0, translateY = wrapper.translateY || 0, scaleX = wrapper.scaleX, scaleY = wrapper.scaleY, inverted = wrapper.inverted, rotation = wrapper.rotation, element = wrapper.element, transform; // flipping affects translate as adjustment for flipping around the group's axis if (inverted) { translateX += wrapper.attr('width'); translateY += wrapper.attr('height'); } // Apply translate. Nearly all transformed elements have translation, so instead // of checking for translate = 0, do it always (#1767, #1846). transform = ['translate(' + translateX + ',' + translateY + ')']; // apply rotation if (inverted) { transform.push('rotate(90) scale(-1,1)'); } else if (rotation) { // text rotation transform.push('rotate(' + rotation + ' ' + (element.getAttribute('x') || 0) + ' ' + (element.getAttribute('y') || 0) + ')'); // Delete bBox memo when the rotation changes //delete wrapper.bBox; } // apply scale if (defined(scaleX) || defined(scaleY)) { transform.push('scale(' + pick(scaleX, 1) + ' ' + pick(scaleY, 1) + ')'); } if (transform.length) { element.setAttribute('transform', transform.join(' ')); } }, /** * Bring the element to the front */ toFront: function () { var element = this.element; element.parentNode.appendChild(element); return this; }, /** * Break down alignment options like align, verticalAlign, x and y * to x and y relative to the chart. * * @param {Object} alignOptions * @param {Boolean} alignByTranslate * @param {String[Object} box The box to align to, needs a width and height. When the * box is a string, it refers to an object in the Renderer. For example, when * box is 'spacingBox', it refers to Renderer.spacingBox which holds width, height * x and y properties. * */ align: function (alignOptions, alignByTranslate, box) { var align, vAlign, x, y, attribs = {}, alignTo, renderer = this.renderer, alignedObjects = renderer.alignedObjects; // First call on instanciate if (alignOptions) { this.alignOptions = alignOptions; this.alignByTranslate = alignByTranslate; if (!box || isString(box)) { // boxes other than renderer handle this internally this.alignTo = alignTo = box || 'renderer'; erase(alignedObjects, this); // prevent duplicates, like legendGroup after resize alignedObjects.push(this); box = null; // reassign it below } // When called on resize, no arguments are supplied } else { alignOptions = this.alignOptions; alignByTranslate = this.alignByTranslate; alignTo = this.alignTo; } box = pick(box, renderer[alignTo], renderer); // Assign variables align = alignOptions.align; vAlign = alignOptions.verticalAlign; x = (box.x || 0) + (alignOptions.x || 0); // default: left align y = (box.y || 0) + (alignOptions.y || 0); // default: top align // Align if (align === 'right' || align === 'center') { x += (box.width - (alignOptions.width || 0)) / { right: 1, center: 2 }[align]; } attribs[alignByTranslate ? 'translateX' : 'x'] = mathRound(x); // Vertical align if (vAlign === 'bottom' || vAlign === 'middle') { y += (box.height - (alignOptions.height || 0)) / ({ bottom: 1, middle: 2 }[vAlign] || 1); } attribs[alignByTranslate ? 'translateY' : 'y'] = mathRound(y); // Animate only if already placed this[this.placed ? 'animate' : 'attr'](attribs); this.placed = true; this.alignAttr = attribs; return this; }, /** * Get the bounding box (width, height, x and y) for the element */ getBBox: function (reload, rot) { var wrapper = this, bBox, // = wrapper.bBox, renderer = wrapper.renderer, width, height, rotation, rad, element = wrapper.element, styles = wrapper.styles, textStr = wrapper.textStr, textShadow, elemStyle = element.style, toggleTextShadowShim, cache = renderer.cache, cacheKeys = renderer.cacheKeys, cacheKey; rotation = pick(rot, wrapper.rotation); rad = rotation * deg2rad; if (textStr !== UNDEFINED) { // Properties that affect bounding box cacheKey = ['', rotation || 0, styles && styles.fontSize, element.style.width].join(','); // Since numbers are monospaced, and numerical labels appear a lot in a chart, // we assume that a label of n characters has the same bounding box as others // of the same length. if (textStr === '' || numRegex.test(textStr)) { cacheKey = 'num:' + textStr.toString().length + cacheKey; // Caching all strings reduces rendering time by 4-5%. } else { cacheKey = textStr + cacheKey; } } if (cacheKey && !reload) { bBox = cache[cacheKey]; } // No cache found if (!bBox) { // SVG elements if (element.namespaceURI === SVG_NS || renderer.forExport) { try { // Fails in Firefox if the container has display: none. // When the text shadow shim is used, we need to hide the fake shadows // to get the correct bounding box (#3872) toggleTextShadowShim = this.fakeTS && function (display) { each(element.querySelectorAll('.' + PREFIX + 'text-shadow'), function (tspan) { tspan.style.display = display; }); }; // Workaround for #3842, Firefox reporting wrong bounding box for shadows if (isFirefox && elemStyle.textShadow) { textShadow = elemStyle.textShadow; elemStyle.textShadow = ''; } else if (toggleTextShadowShim) { toggleTextShadowShim(NONE); } bBox = element.getBBox ? // SVG: use extend because IE9 is not allowed to change width and height in case // of rotation (below) extend({}, element.getBBox()) : // Canvas renderer and legacy IE in export mode { width: element.offsetWidth, height: element.offsetHeight }; // #3842 if (textShadow) { elemStyle.textShadow = textShadow; } else if (toggleTextShadowShim) { toggleTextShadowShim(''); } } catch (e) {} // If the bBox is not set, the try-catch block above failed. The other condition // is for Opera that returns a width of -Infinity on hidden elements. if (!bBox || bBox.width < 0) { bBox = { width: 0, height: 0 }; } // VML Renderer or useHTML within SVG } else { bBox = wrapper.htmlGetBBox(); } // True SVG elements as well as HTML elements in modern browsers using the .useHTML option // need to compensated for rotation if (renderer.isSVG) { width = bBox.width; height = bBox.height; // Workaround for wrong bounding box in IE9 and IE10 (#1101, #1505, #1669, #2568) if (isMS && styles && styles.fontSize === '11px' && height.toPrecision(3) === '16.9') { bBox.height = height = 14; } // Adjust for rotated text if (rotation) { bBox.width = mathAbs(height * mathSin(rad)) + mathAbs(width * mathCos(rad)); bBox.height = mathAbs(height * mathCos(rad)) + mathAbs(width * mathSin(rad)); } } // Cache it if (cacheKey) { // Rotate (#4681) while (cacheKeys.length > 250) { delete cache[cacheKeys.shift()]; } if (!cache[cacheKey]) { cacheKeys.push(cacheKey); } cache[cacheKey] = bBox; } } return bBox; }, /** * Show the element */ show: function (inherit) { return this.attr({ visibility: inherit ? 'inherit' : VISIBLE }); }, /** * Hide the element */ hide: function () { return this.attr({ visibility: HIDDEN }); }, fadeOut: function (duration) { var elemWrapper = this; elemWrapper.animate({ opacity: 0 }, { duration: duration || 150, complete: function () { elemWrapper.attr({ y: -9999 }); // #3088, assuming we're only using this for tooltips } }); }, /** * Add the element * @param {Object|Undefined} parent Can be an element, an element wrapper or undefined * to append the element to the renderer.box. */ add: function (parent) { var renderer = this.renderer, element = this.element, inserted; if (parent) { this.parentGroup = parent; } // mark as inverted this.parentInverted = parent && parent.inverted; // build formatted text if (this.textStr !== undefined) { renderer.buildText(this); } // Mark as added this.added = true; // If we're adding to renderer root, or other elements in the group // have a z index, we need to handle it if (!parent || parent.handleZ || this.zIndex) { inserted = this.zIndexSetter(); } // If zIndex is not handled, append at the end if (!inserted) { (parent ? parent.element : renderer.box).appendChild(element); } // fire an event for internal hooks if (this.onAdd) { this.onAdd(); } return this; }, /** * Removes a child either by removeChild or move to garbageBin. * Issue 490; in VML removeChild results in Orphaned nodes according to sIEve, discardElement does not. */ safeRemoveChild: function (element) { var parentNode = element.parentNode; if (parentNode) { parentNode.removeChild(element); } }, /** * Destroy the element and element wrapper */ destroy: function () { var wrapper = this, element = wrapper.element || {}, shadows = wrapper.shadows, parentToClean = wrapper.renderer.isSVG && element.nodeName === 'SPAN' && wrapper.parentGroup, grandParent, key, i; // remove events element.onclick = element.onmouseout = element.onmouseover = element.onmousemove = element.point = null; stop(wrapper); // stop running animations if (wrapper.clipPath) { wrapper.clipPath = wrapper.clipPath.destroy(); } // Destroy stops in case this is a gradient object if (wrapper.stops) { for (i = 0; i < wrapper.stops.length; i++) { wrapper.stops[i] = wrapper.stops[i].destroy(); } wrapper.stops = null; } // remove element wrapper.safeRemoveChild(element); // destroy shadows if (shadows) { each(shadows, function (shadow) { wrapper.safeRemoveChild(shadow); }); } // In case of useHTML, clean up empty containers emulating SVG groups (#1960, #2393, #2697). while (parentToClean && parentToClean.div && parentToClean.div.childNodes.length === 0) { grandParent = parentToClean.parentGroup; wrapper.safeRemoveChild(parentToClean.div); delete parentToClean.div; parentToClean = grandParent; } // remove from alignObjects if (wrapper.alignTo) { erase(wrapper.renderer.alignedObjects, wrapper); } for (key in wrapper) { delete wrapper[key]; } return null; }, /** * Add a shadow to the element. Must be done after the element is added to the DOM * @param {Boolean|Object} shadowOptions */ shadow: function (shadowOptions, group, cutOff) { var shadows = [], i, shadow, element = this.element, strokeWidth, shadowWidth, shadowElementOpacity, // compensate for inverted plot area transform; if (shadowOptions) { shadowWidth = pick(shadowOptions.width, 3); shadowElementOpacity = (shadowOptions.opacity || 0.15) / shadowWidth; transform = this.parentInverted ? '(-1,-1)' : '(' + pick(shadowOptions.offsetX, 1) + ', ' + pick(shadowOptions.offsetY, 1) + ')'; for (i = 1; i <= shadowWidth; i++) { shadow = element.cloneNode(0); strokeWidth = (shadowWidth * 2) + 1 - (2 * i); attr(shadow, { 'isShadow': 'true', 'stroke': shadowOptions.color || 'black', 'stroke-opacity': shadowElementOpacity * i, 'stroke-width': strokeWidth, 'transform': 'translate' + transform, 'fill': NONE }); if (cutOff) { attr(shadow, 'height', mathMax(attr(shadow, 'height') - strokeWidth, 0)); shadow.cutHeight = strokeWidth; } if (group) { group.element.appendChild(shadow); } else { element.parentNode.insertBefore(shadow, element); } shadows.push(shadow); } this.shadows = shadows; } return this; }, xGetter: function (key) { if (this.element.nodeName === 'circle') { key = { x: 'cx', y: 'cy' }[key] || key; } return this._defaultGetter(key); }, /** * Get the current value of an attribute or pseudo attribute, used mainly * for animation. */ _defaultGetter: function (key) { var ret = pick(this[key], this.element ? this.element.getAttribute(key) : null, 0); if (/^[\-0-9\.]+$/.test(ret)) { // is numerical ret = parseFloat(ret); } return ret; }, dSetter: function (value, key, element) { if (value && value.join) { // join path value = value.join(' '); } if (/(NaN| {2}|^$)/.test(value)) { value = 'M 0 0'; } element.setAttribute(key, value); this[key] = value; }, dashstyleSetter: function (value) { var i; value = value && value.toLowerCase(); if (value) { value = value .replace('shortdashdotdot', '3,1,1,1,1,1,') .replace('shortdashdot', '3,1,1,1') .replace('shortdot', '1,1,') .replace('shortdash', '3,1,') .replace('longdash', '8,3,') .replace(/dot/g, '1,3,') .replace('dash', '4,3,') .replace(/,$/, '') .split(','); // ending comma i = value.length; while (i--) { value[i] = pInt(value[i]) * this['stroke-width']; } value = value.join(',') .replace('NaN', 'none'); // #3226 this.element.setAttribute('stroke-dasharray', value); } }, alignSetter: function (value) { this.element.setAttribute('text-anchor', { left: 'start', center: 'middle', right: 'end' }[value]); }, opacitySetter: function (value, key, element) { this[key] = value; element.setAttribute(key, value); }, titleSetter: function (value) { var titleNode = this.element.getElementsByTagName('title')[0]; if (!titleNode) { titleNode = doc.createElementNS(SVG_NS, 'title'); this.element.appendChild(titleNode); } titleNode.appendChild( doc.createTextNode( (String(pick(value), '')).replace(/<[^>]*>/g, '') // #3276, #3895 ) ); }, textSetter: function (value) { if (value !== this.textStr) { // Delete bBox memo when the text changes delete this.bBox; this.textStr = value; if (this.added) { this.renderer.buildText(this); } } }, fillSetter: function (value, key, element) { if (typeof value === 'string') { element.setAttribute(key, value); } else if (value) { this.colorGradient(value, key, element); } }, visibilitySetter: function (value, key, element) { // IE9-11 doesn't handle visibilty:inherit well, so we remove the attribute instead (#2881, #3909) if (value === 'inherit') { element.removeAttribute(key); } else { element.setAttribute(key, value); } }, zIndexSetter: function (value, key) { var renderer = this.renderer, parentGroup = this.parentGroup, parentWrapper = parentGroup || renderer, parentNode = parentWrapper.element || renderer.box, childNodes, otherElement, otherZIndex, element = this.element, inserted, run = this.added, i; if (defined(value)) { element.setAttribute(key, value); // So we can read it for other elements in the group value = +value; if (this[key] === value) { // Only update when needed (#3865) run = false; } this[key] = value; } // Insert according to this and other elements' zIndex. Before .add() is called, // nothing is done. Then on add, or by later calls to zIndexSetter, the node // is placed on the right place in the DOM. if (run) { value = this.zIndex; if (value && parentGroup) { parentGroup.handleZ = true; } childNodes = parentNode.childNodes; for (i = 0; i < childNodes.length && !inserted; i++) { otherElement = childNodes[i]; otherZIndex = attr(otherElement, 'zIndex'); if (otherElement !== element && ( // Insert before the first element with a higher zIndex pInt(otherZIndex) > value || // If no zIndex given, insert before the first element with a zIndex (!defined(value) && defined(otherZIndex)) )) { parentNode.insertBefore(element, otherElement); inserted = true; } } if (!inserted) { parentNode.appendChild(element); } } return inserted; }, _defaultSetter: function (value, key, element) { element.setAttribute(key, value); } }; // Some shared setters and getters SVGElement.prototype.yGetter = SVGElement.prototype.xGetter; SVGElement.prototype.translateXSetter = SVGElement.prototype.translateYSetter = SVGElement.prototype.rotationSetter = SVGElement.prototype.verticalAlignSetter = SVGElement.prototype.scaleXSetter = SVGElement.prototype.scaleYSetter = function (value, key) { this[key] = value; this.doTransform = true; }; // WebKit and Batik have problems with a stroke-width of zero, so in this case we remove the // stroke attribute altogether. #1270, #1369, #3065, #3072. SVGElement.prototype['stroke-widthSetter'] = SVGElement.prototype.strokeSetter = function (value, key, element) { this[key] = value; // Only apply the stroke attribute if the stroke width is defined and larger than 0 if (this.stroke && this['stroke-width']) { this.strokeWidth = this['stroke-width']; SVGElement.prototype.fillSetter.call(this, this.stroke, 'stroke', element); // use prototype as instance may be overridden element.setAttribute('stroke-width', this['stroke-width']); this.hasStroke = true; } else if (key === 'stroke-width' && value === 0 && this.hasStroke) { element.removeAttribute('stroke'); this.hasStroke = false; } }; /** * The default SVG renderer */ var SVGRenderer = function () { this.init.apply(this, arguments); }; SVGRenderer.prototype = { Element: SVGElement, /** * Initialize the SVGRenderer * @param {Object} container * @param {Number} width * @param {Number} height * @param {Boolean} forExport */ init: function (container, width, height, style, forExport, allowHTML) { var renderer = this, boxWrapper, element, desc; boxWrapper = renderer.createElement('svg') .attr({ version: '1.1' }) .css(this.getStyle(style)); element = boxWrapper.element; container.appendChild(element); // For browsers other than IE, add the namespace attribute (#1978) if (container.innerHTML.indexOf('xmlns') === -1) { attr(element, 'xmlns', SVG_NS); } // object properties renderer.isSVG = true; renderer.box = element; renderer.boxWrapper = boxWrapper; renderer.alignedObjects = []; // Page url used for internal references. #24, #672, #1070 renderer.url = (isFirefox || isWebKit) && doc.getElementsByTagName('base').length ? win.location.href .replace(/#.*?$/, '') // remove the hash .replace(/([\('\)])/g, '\\$1') // escape parantheses and quotes .replace(/ /g, '%20') : // replace spaces (needed for Safari only) ''; // Add description desc = this.createElement('desc').add(); desc.element.appendChild(doc.createTextNode('Created with ' + PRODUCT + ' ' + VERSION)); renderer.defs = this.createElement('defs').add(); renderer.allowHTML = allowHTML; renderer.forExport = forExport; renderer.gradients = {}; // Object where gradient SvgElements are stored renderer.cache = {}; // Cache for numerical bounding boxes renderer.cacheKeys = []; renderer.imgCount = 0; renderer.setSize(width, height, false); // Issue 110 workaround: // In Firefox, if a div is positioned by percentage, its pixel position may land // between pixels. The container itself doesn't display this, but an SVG element // inside this container will be drawn at subpixel precision. In order to draw // sharp lines, this must be compensated for. This doesn't seem to work inside // iframes though (like in jsFiddle). var subPixelFix, rect; if (isFirefox && container.getBoundingClientRect) { renderer.subPixelFix = subPixelFix = function () { css(container, { left: 0, top: 0 }); rect = container.getBoundingClientRect(); css(container, { left: (mathCeil(rect.left) - rect.left) + PX, top: (mathCeil(rect.top) - rect.top) + PX }); }; // run the fix now subPixelFix(); // run it on resize addEvent(win, 'resize', subPixelFix); } }, getStyle: function (style) { this.style = extend({ fontFamily: '"Lucida Grande", "Lucida Sans Unicode", Arial, Helvetica, sans-serif', // default font fontSize: '12px' }, style); return this.style; }, /** * Detect whether the renderer is hidden. This happens when one of the parent elements * has display: none. #608. */ isHidden: function () { return !this.boxWrapper.getBBox().width; }, /** * Destroys the renderer and its allocated members. */ destroy: function () { var renderer = this, rendererDefs = renderer.defs; renderer.box = null; renderer.boxWrapper = renderer.boxWrapper.destroy(); // Call destroy on all gradient elements destroyObjectProperties(renderer.gradients || {}); renderer.gradients = null; // Defs are null in VMLRenderer // Otherwise, destroy them here. if (rendererDefs) { renderer.defs = rendererDefs.destroy(); } // Remove sub pixel fix handler // We need to check that there is a handler, otherwise all functions that are registered for event 'resize' are removed // See issue #982 if (renderer.subPixelFix) { removeEvent(win, 'resize', renderer.subPixelFix); } renderer.alignedObjects = null; return null; }, /** * Create a wrapper for an SVG element * @param {Object} nodeName */ createElement: function (nodeName) { var wrapper = new this.Element(); wrapper.init(this, nodeName); return wrapper; }, /** * Dummy function for use in canvas renderer */ draw: function () {}, /** * Get converted radial gradient attributes */ getRadialAttr: function (radialReference, gradAttr) { return { cx: (radialReference[0] - radialReference[2] / 2) + gradAttr.cx * radialReference[2], cy: (radialReference[1] - radialReference[2] / 2) + gradAttr.cy * radialReference[2], r: gradAttr.r * radialReference[2] }; }, /** * Parse a simple HTML string into SVG tspans * * @param {Object} textNode The parent text SVG node */ buildText: function (wrapper) { var textNode = wrapper.element, renderer = this, forExport = renderer.forExport, textStr = pick(wrapper.textStr, '').toString(), hasMarkup = textStr.indexOf('<') !== -1, lines, childNodes = textNode.childNodes, styleRegex, hrefRegex, parentX = attr(textNode, 'x'), textStyles = wrapper.styles, width = wrapper.textWidth, textLineHeight = textStyles && textStyles.lineHeight, textShadow = textStyles && textStyles.textShadow, ellipsis = textStyles && textStyles.textOverflow === 'ellipsis', i = childNodes.length, tempParent = width && !wrapper.added && this.box, getLineHeight = function (tspan) { return textLineHeight ? pInt(textLineHeight) : renderer.fontMetrics( /(px|em)$/.test(tspan && tspan.style.fontSize) ? tspan.style.fontSize : ((textStyles && textStyles.fontSize) || renderer.style.fontSize || 12), tspan ).h; }, unescapeAngleBrackets = function (inputStr) { return inputStr.replace(/&lt;/g, '<').replace(/&gt;/g, '>'); }; /// remove old text while (i--) { textNode.removeChild(childNodes[i]); } // Skip tspans, add text directly to text node. The forceTSpan is a hook // used in text outline hack. if (!hasMarkup && !textShadow && !ellipsis && textStr.indexOf(' ') === -1) { textNode.appendChild(doc.createTextNode(unescapeAngleBrackets(textStr))); // Complex strings, add more logic } else { styleRegex = /<.*style="([^"]+)".*>/; hrefRegex = /<.*href="(http[^"]+)".*>/; if (tempParent) { tempParent.appendChild(textNode); // attach it to the DOM to read offset width } if (hasMarkup) { lines = textStr .replace(/<(b|strong)>/g, '<span style="font-weight:bold">') .replace(/<(i|em)>/g, '<span style="font-style:italic">') .replace(/<a/g, '<span') .replace(/<\/(b|strong|i|em|a)>/g, '</span>') .split(/<br.*?>/g); } else { lines = [textStr]; } // remove empty line at end if (lines[lines.length - 1] === '') { lines.pop(); } // build the lines each(lines, function (line, lineNo) { var spans, spanNo = 0; line = line.replace(/<span/g, '|||<span').replace(/<\/span>/g, '</span>|||'); spans = line.split('|||'); each(spans, function (span) { if (span !== '' || spans.length === 1) { var attributes = {}, tspan = doc.createElementNS(SVG_NS, 'tspan'), spanStyle; // #390 if (styleRegex.test(span)) { spanStyle = span.match(styleRegex)[1].replace(/(;| |^)color([ :])/, '$1fill$2'); attr(tspan, 'style', spanStyle); } if (hrefRegex.test(span) && !forExport) { // Not for export - #1529 attr(tspan, 'onclick', 'location.href=\"' + span.match(hrefRegex)[1] + '\"'); css(tspan, { cursor: 'pointer' }); } span = unescapeAngleBrackets(span.replace(/<(.|\n)*?>/g, '') || ' '); // Nested tags aren't supported, and cause crash in Safari (#1596) if (span !== ' ') { // add the text node tspan.appendChild(doc.createTextNode(span)); if (!spanNo) { // first span in a line, align it to the left if (lineNo && parentX !== null) { attributes.x = parentX; } } else { attributes.dx = 0; // #16 } // add attributes attr(tspan, attributes); // Append it textNode.appendChild(tspan); // first span on subsequent line, add the line height if (!spanNo && lineNo) { // allow getting the right offset height in exporting in IE if (!hasSVG && forExport) { css(tspan, { display: 'block' }); } // Set the line height based on the font size of either // the text element or the tspan element attr( tspan, 'dy', getLineHeight(tspan) ); } /*if (width) { renderer.breakText(wrapper, width); }*/ // Check width and apply soft breaks or ellipsis if (width) { var words = span.replace(/([^\^])-/g, '$1- ').split(' '), // #1273 hasWhiteSpace = spans.length > 1 || lineNo || (words.length > 1 && textStyles.whiteSpace !== 'nowrap'), tooLong, wasTooLong, actualWidth, rest = [], dy = getLineHeight(tspan), softLineNo = 1, rotation = wrapper.rotation, wordStr = span, // for ellipsis cursor = wordStr.length, // binary search cursor bBox; while ((hasWhiteSpace || ellipsis) && (words.length || rest.length)) { wrapper.rotation = 0; // discard rotation when computing box bBox = wrapper.getBBox(true); actualWidth = bBox.width; // Old IE cannot measure the actualWidth for SVG elements (#2314) if (!hasSVG && renderer.forExport) { actualWidth = renderer.measureSpanWidth(tspan.firstChild.data, wrapper.styles); } tooLong = actualWidth > width; // For ellipsis, do a binary search for the correct string length if (wasTooLong === undefined) { wasTooLong = tooLong; // First time } if (ellipsis && wasTooLong) { cursor /= 2; if (wordStr === '' || (!tooLong && cursor < 0.5)) { words = []; // All ok, break out } else { if (tooLong) { wasTooLong = true; } wordStr = span.substring(0, wordStr.length + (tooLong ? -1 : 1) * mathCeil(cursor)); words = [wordStr + (width > 3 ? '\u2026' : '')]; tspan.removeChild(tspan.firstChild); } // Looping down, this is the first word sequence that is not too long, // so we can move on to build the next line. } else if (!tooLong || words.length === 1) { words = rest; rest = []; if (words.length) { softLineNo++; tspan = doc.createElementNS(SVG_NS, 'tspan'); attr(tspan, { dy: dy, x: parentX }); if (spanStyle) { // #390 attr(tspan, 'style', spanStyle); } textNode.appendChild(tspan); } if (actualWidth > width) { // a single word is pressing it out width = actualWidth; } } else { // append to existing line tspan tspan.removeChild(tspan.firstChild); rest.unshift(words.pop()); } if (words.length) { tspan.appendChild(doc.createTextNode(words.join(' ').replace(/- /g, '-'))); } } if (wasTooLong) { wrapper.attr('title', wrapper.textStr); } wrapper.rotation = rotation; } spanNo++; } } }); }); if (tempParent) { tempParent.removeChild(textNode); // attach it to the DOM to read offset width } // Apply the text shadow if (textShadow && wrapper.applyTextShadow) { wrapper.applyTextShadow(textShadow); } } }, /* breakText: function (wrapper, width) { var bBox = wrapper.getBBox(), node = wrapper.element, textLength = node.textContent.length, pos = mathRound(width * textLength / bBox.width), // try this position first, based on average character width increment = 0, finalPos; if (bBox.width > width) { while (finalPos === undefined) { textLength = node.getSubStringLength(0, pos); if (textLength <= width) { if (increment === -1) { finalPos = pos; } else { increment = 1; } } else { if (increment === 1) { finalPos = pos - 1; } else { increment = -1; } } pos += increment; } } console.log(finalPos, node.getSubStringLength(0, finalPos)) }, */ /** * Returns white for dark colors and black for bright colors */ getContrast: function (color) { color = Color(color).rgba; return color[0] + color[1] + color[2] > 384 ? '#000000' : '#FFFFFF'; }, /** * Create a button with preset states * @param {String} text * @param {Number} x * @param {Number} y * @param {Function} callback * @param {Object} normalState * @param {Object} hoverState * @param {Object} pressedState */ button: function (text, x, y, callback, normalState, hoverState, pressedState, disabledState, shape) { var label = this.label(text, x, y, shape, null, null, null, null, 'button'), curState = 0, stateOptions, stateStyle, normalStyle, hoverStyle, pressedStyle, disabledStyle, verticalGradient = { x1: 0, y1: 0, x2: 0, y2: 1 }; // Normal state - prepare the attributes normalState = merge({ 'stroke-width': 1, stroke: '#CCCCCC', fill: { linearGradient: verticalGradient, stops: [ [0, '#FEFEFE'], [1, '#F6F6F6'] ] }, r: 2, padding: 5, style: { color: 'black' } }, normalState); normalStyle = normalState.style; delete normalState.style; // Hover state hoverState = merge(normalState, { stroke: '#68A', fill: { linearGradient: verticalGradient, stops: [ [0, '#FFF'], [1, '#ACF'] ] } }, hoverState); hoverStyle = hoverState.style; delete hoverState.style; // Pressed state pressedState = merge(normalState, { stroke: '#68A', fill: { linearGradient: verticalGradient, stops: [ [0, '#9BD'], [1, '#CDF'] ] } }, pressedState); pressedStyle = pressedState.style; delete pressedState.style; // Disabled state disabledState = merge(normalState, { style: { color: '#CCC' } }, disabledState); disabledStyle = disabledState.style; delete disabledState.style; // Add the events. IE9 and IE10 need mouseover and mouseout to funciton (#667). addEvent(label.element, isMS ? 'mouseover' : 'mouseenter', function () { if (curState !== 3) { label.attr(hoverState) .css(hoverStyle); } }); addEvent(label.element, isMS ? 'mouseout' : 'mouseleave', function () { if (curState !== 3) { stateOptions = [normalState, hoverState, pressedState][curState]; stateStyle = [normalStyle, hoverStyle, pressedStyle][curState]; label.attr(stateOptions) .css(stateStyle); } }); label.setState = function (state) { label.state = curState = state; if (!state) { label.attr(normalState) .css(normalStyle); } else if (state === 2) { label.attr(pressedState) .css(pressedStyle); } else if (state === 3) { label.attr(disabledState) .css(disabledStyle); } }; return label .on('click', function (e) { if (curState !== 3) { callback.call(label, e); } }) .attr(normalState) .css(extend({ cursor: 'default' }, normalStyle)); }, /** * Make a straight line crisper by not spilling out to neighbour pixels * @param {Array} points * @param {Number} width */ crispLine: function (points, width) { // points format: [M, 0, 0, L, 100, 0] // normalize to a crisp line if (points[1] === points[4]) { // Substract due to #1129. Now bottom and left axis gridlines behave the same. points[1] = points[4] = mathRound(points[1]) - (width % 2 / 2); } if (points[2] === points[5]) { points[2] = points[5] = mathRound(points[2]) + (width % 2 / 2); } return points; }, /** * Draw a path * @param {Array} path An SVG path in array form */ path: function (path) { var attr = { fill: NONE }; if (isArray(path)) { attr.d = path; } else if (isObject(path)) { // attributes extend(attr, path); } return this.createElement('path').attr(attr); }, /** * Draw and return an SVG circle * @param {Number} x The x position * @param {Number} y The y position * @param {Number} r The radius */ circle: function (x, y, r) { var attr = isObject(x) ? x : { x: x, y: y, r: r }, wrapper = this.createElement('circle'); // Setting x or y translates to cx and cy wrapper.xSetter = wrapper.ySetter = function (value, key, element) { element.setAttribute('c' + key, value); }; return wrapper.attr(attr); }, /** * Draw and return an arc * @param {Number} x X position * @param {Number} y Y position * @param {Number} r Radius * @param {Number} innerR Inner radius like used in donut charts * @param {Number} start Starting angle * @param {Number} end Ending angle */ arc: function (x, y, r, innerR, start, end) { var arc; if (isObject(x)) { y = x.y; r = x.r; innerR = x.innerR; start = x.start; end = x.end; x = x.x; } // Arcs are defined as symbols for the ability to set // attributes in attr and animate arc = this.symbol('arc', x || 0, y || 0, r || 0, r || 0, { innerR: innerR || 0, start: start || 0, end: end || 0 }); arc.r = r; // #959 return arc; }, /** * Draw and return a rectangle * @param {Number} x Left position * @param {Number} y Top position * @param {Number} width * @param {Number} height * @param {Number} r Border corner radius * @param {Number} strokeWidth A stroke width can be supplied to allow crisp drawing */ rect: function (x, y, width, height, r, strokeWidth) { r = isObject(x) ? x.r : r; var wrapper = this.createElement('rect'), attribs = isObject(x) ? x : x === UNDEFINED ? {} : { x: x, y: y, width: mathMax(width, 0), height: mathMax(height, 0) }; if (strokeWidth !== UNDEFINED) { wrapper.strokeWidth = strokeWidth; attribs = wrapper.crisp(attribs); } if (r) { attribs.r = r; } wrapper.rSetter = function (value, key, element) { attr(element, { rx: value, ry: value }); }; return wrapper.attr(attribs); }, /** * Resize the box and re-align all aligned elements * @param {Object} width * @param {Object} height * @param {Boolean} animate * */ setSize: function (width, height, animate) { var renderer = this, alignedObjects = renderer.alignedObjects, i = alignedObjects.length; renderer.width = width; renderer.height = height; renderer.boxWrapper[pick(animate, true) ? 'animate' : 'attr']({ width: width, height: height }); while (i--) { alignedObjects[i].align(); } }, /** * Create a group * @param {String} name The group will be given a class name of 'highcharts-{name}'. * This can be used for styling and scripting. */ g: function (name) { var elem = this.createElement('g'); return defined(name) ? elem.attr({ 'class': PREFIX + name }) : elem; }, /** * Display an image * @param {String} src * @param {Number} x * @param {Number} y * @param {Number} width * @param {Number} height */ image: function (src, x, y, width, height) { var attribs = { preserveAspectRatio: NONE }, elemWrapper; // optional properties if (arguments.length > 1) { extend(attribs, { x: x, y: y, width: width, height: height }); } elemWrapper = this.createElement('image').attr(attribs); // set the href in the xlink namespace if (elemWrapper.element.setAttributeNS) { elemWrapper.element.setAttributeNS('http://www.w3.org/1999/xlink', 'href', src); } else { // could be exporting in IE // using href throws "not supported" in ie7 and under, requries regex shim to fix later elemWrapper.element.setAttribute('hc-svg-href', src); } return elemWrapper; }, /** * Draw a symbol out of pre-defined shape paths from the namespace 'symbol' object. * * @param {Object} symbol * @param {Object} x * @param {Object} y * @param {Object} radius * @param {Object} options */ symbol: function (symbol, x, y, width, height, options) { var ren = this, obj, // get the symbol definition function symbolFn = this.symbols[symbol], // check if there's a path defined for this symbol path = symbolFn && symbolFn( mathRound(x), mathRound(y), width, height, options ), imageRegex = /^url\((.*?)\)$/, imageSrc, imageSize, centerImage; if (path) { obj = this.path(path); // expando properties for use in animate and attr extend(obj, { symbolName: symbol, x: x, y: y, width: width, height: height }); if (options) { extend(obj, options); } // image symbols } else if (imageRegex.test(symbol)) { // On image load, set the size and position centerImage = function (img, size) { if (img.element) { // it may be destroyed in the meantime (#1390) img.attr({ width: size[0], height: size[1] }); if (!img.alignByTranslate) { // #185 img.translate( mathRound((width - size[0]) / 2), // #1378 mathRound((height - size[1]) / 2) ); } } }; imageSrc = symbol.match(imageRegex)[1]; imageSize = symbolSizes[imageSrc] || (options && options.width && options.height && [options.width, options.height]); // Ireate the image synchronously, add attribs async obj = this.image(imageSrc) .attr({ x: x, y: y }); obj.isImg = true; if (imageSize) { centerImage(obj, imageSize); } else { // Initialize image to be 0 size so export will still function if there's no cached sizes. obj.attr({ width: 0, height: 0 }); // Create a dummy JavaScript image to get the width and height. Due to a bug in IE < 8, // the created element must be assigned to a variable in order to load (#292). createElement('img', { onload: function () { // Special case for SVGs on IE11, the width is not accessible until the image is // part of the DOM (#2854). if (this.width === 0) { css(this, { position: ABSOLUTE, top: '-999em' }); doc.body.appendChild(this); } // Center the image centerImage(obj, symbolSizes[imageSrc] = [this.width, this.height]); // Clean up after #2854 workaround. if (this.parentNode) { this.parentNode.removeChild(this); } // Fire the load event when all external images are loaded ren.imgCount--; if (!ren.imgCount) { charts[ren.chartIndex].onload(); } }, src: imageSrc }); } this.imgCount++; } return obj; }, /** * An extendable collection of functions for defining symbol paths. */ symbols: { 'circle': function (x, y, w, h) { var cpw = 0.166 * w; return [ M, x + w / 2, y, 'C', x + w + cpw, y, x + w + cpw, y + h, x + w / 2, y + h, 'C', x - cpw, y + h, x - cpw, y, x + w / 2, y, 'Z' ]; }, 'square': function (x, y, w, h) { return [ M, x, y, L, x + w, y, x + w, y + h, x, y + h, 'Z' ]; }, 'triangle': function (x, y, w, h) { return [ M, x + w / 2, y, L, x + w, y + h, x, y + h, 'Z' ]; }, 'triangle-down': function (x, y, w, h) { return [ M, x, y, L, x + w, y, x + w / 2, y + h, 'Z' ]; }, 'diamond': function (x, y, w, h) { return [ M, x + w / 2, y, L, x + w, y + h / 2, x + w / 2, y + h, x, y + h / 2, 'Z' ]; }, 'arc': function (x, y, w, h, options) { var start = options.start, radius = options.r || w || h, end = options.end - 0.001, // to prevent cos and sin of start and end from becoming equal on 360 arcs (related: #1561) innerRadius = options.innerR, open = options.open, cosStart = mathCos(start), sinStart = mathSin(start), cosEnd = mathCos(end), sinEnd = mathSin(end), longArc = options.end - start < mathPI ? 0 : 1; return [ M, x + radius * cosStart, y + radius * sinStart, 'A', // arcTo radius, // x radius radius, // y radius 0, // slanting longArc, // long or short arc 1, // clockwise x + radius * cosEnd, y + radius * sinEnd, open ? M : L, x + innerRadius * cosEnd, y + innerRadius * sinEnd, 'A', // arcTo innerRadius, // x radius innerRadius, // y radius 0, // slanting longArc, // long or short arc 0, // clockwise x + innerRadius * cosStart, y + innerRadius * sinStart, open ? '' : 'Z' // close ]; }, /** * Callout shape used for default tooltips, also used for rounded rectangles in VML */ callout: function (x, y, w, h, options) { var arrowLength = 6, halfDistance = 6, r = mathMin((options && options.r) || 0, w, h), safeDistance = r + halfDistance, anchorX = options && options.anchorX, anchorY = options && options.anchorY, path; path = [ 'M', x + r, y, 'L', x + w - r, y, // top side 'C', x + w, y, x + w, y, x + w, y + r, // top-right corner 'L', x + w, y + h - r, // right side 'C', x + w, y + h, x + w, y + h, x + w - r, y + h, // bottom-right corner 'L', x + r, y + h, // bottom side 'C', x, y + h, x, y + h, x, y + h - r, // bottom-left corner 'L', x, y + r, // left side 'C', x, y, x, y, x + r, y // top-right corner ]; if (anchorX && anchorX > w && anchorY > y + safeDistance && anchorY < y + h - safeDistance) { // replace right side path.splice(13, 3, 'L', x + w, anchorY - halfDistance, x + w + arrowLength, anchorY, x + w, anchorY + halfDistance, x + w, y + h - r ); } else if (anchorX && anchorX < 0 && anchorY > y + safeDistance && anchorY < y + h - safeDistance) { // replace left side path.splice(33, 3, 'L', x, anchorY + halfDistance, x - arrowLength, anchorY, x, anchorY - halfDistance, x, y + r ); } else if (anchorY && anchorY > h && anchorX > x + safeDistance && anchorX < x + w - safeDistance) { // replace bottom path.splice(23, 3, 'L', anchorX + halfDistance, y + h, anchorX, y + h + arrowLength, anchorX - halfDistance, y + h, x + r, y + h ); } else if (anchorY && anchorY < 0 && anchorX > x + safeDistance && anchorX < x + w - safeDistance) { // replace top path.splice(3, 3, 'L', anchorX - halfDistance, y, anchorX, y - arrowLength, anchorX + halfDistance, y, w - r, y ); } return path; } }, /** * Define a clipping rectangle * @param {String} id * @param {Number} x * @param {Number} y * @param {Number} width * @param {Number} height */ clipRect: function (x, y, width, height) { var wrapper, id = PREFIX + idCounter++, clipPath = this.createElement('clipPath').attr({ id: id }).add(this.defs); wrapper = this.rect(x, y, width, height, 0).add(clipPath); wrapper.id = id; wrapper.clipPath = clipPath; wrapper.count = 0; return wrapper; }, /** * Add text to the SVG object * @param {String} str * @param {Number} x Left position * @param {Number} y Top position * @param {Boolean} useHTML Use HTML to render the text */ text: function (str, x, y, useHTML) { // declare variables var renderer = this, fakeSVG = useCanVG || (!hasSVG && renderer.forExport), wrapper, attr = {}; if (useHTML && (renderer.allowHTML || !renderer.forExport)) { return renderer.html(str, x, y); } attr.x = Math.round(x || 0); // X is always needed for line-wrap logic if (y) { attr.y = Math.round(y); } if (str || str === 0) { attr.text = str; } wrapper = renderer.createElement('text') .attr(attr); // Prevent wrapping from creating false offsetWidths in export in legacy IE (#1079, #1063) if (fakeSVG) { wrapper.css({ position: ABSOLUTE }); } if (!useHTML) { wrapper.xSetter = function (value, key, element) { var tspans = element.getElementsByTagName('tspan'), tspan, parentVal = element.getAttribute(key), i; for (i = 0; i < tspans.length; i++) { tspan = tspans[i]; // If the x values are equal, the tspan represents a linebreak if (tspan.getAttribute(key) === parentVal) { tspan.setAttribute(key, value); } } element.setAttribute(key, value); }; } return wrapper; }, /** * Utility to return the baseline offset and total line height from the font size */ fontMetrics: function (fontSize, elem) { var lineHeight, baseline, style; fontSize = fontSize || this.style.fontSize; if (!fontSize && elem && win.getComputedStyle) { elem = elem.element || elem; // SVGElement style = win.getComputedStyle(elem, ''); fontSize = style && style.fontSize; // #4309, the style doesn't exist inside a hidden iframe in Firefox } fontSize = /px/.test(fontSize) ? pInt(fontSize) : /em/.test(fontSize) ? parseFloat(fontSize) * 12 : 12; // Empirical values found by comparing font size and bounding box height. // Applies to the default font family. http://jsfiddle.net/highcharts/7xvn7/ lineHeight = fontSize < 24 ? fontSize + 3 : mathRound(fontSize * 1.2); baseline = mathRound(lineHeight * 0.8); return { h: lineHeight, b: baseline, f: fontSize }; }, /** * Correct X and Y positioning of a label for rotation (#1764) */ rotCorr: function (baseline, rotation, alterY) { var y = baseline; if (rotation && alterY) { y = mathMax(y * mathCos(rotation * deg2rad), 4); } return { x: (-baseline / 3) * mathSin(rotation * deg2rad), y: y }; }, /** * Add a label, a text item that can hold a colored or gradient background * as well as a border and shadow. * @param {string} str * @param {Number} x * @param {Number} y * @param {String} shape * @param {Number} anchorX In case the shape has a pointer, like a flag, this is the * coordinates it should be pinned to * @param {Number} anchorY * @param {Boolean} baseline Whether to position the label relative to the text baseline, * like renderer.text, or to the upper border of the rectangle. * @param {String} className Class name for the group */ label: function (str, x, y, shape, anchorX, anchorY, useHTML, baseline, className) { var renderer = this, wrapper = renderer.g(className), text = renderer.text('', 0, 0, useHTML) .attr({ zIndex: 1 }), //.add(wrapper), box, bBox, alignFactor = 0, padding = 3, paddingLeft = 0, width, height, wrapperX, wrapperY, crispAdjust = 0, deferredAttr = {}, baselineOffset, needsBox, updateBoxSize, updateTextPadding, boxAttr; /** * This function runs after the label is added to the DOM (when the bounding box is * available), and after the text of the label is updated to detect the new bounding * box and reflect it in the border box. */ updateBoxSize = function () { var boxX, boxY, style = text.element.style; bBox = (width === undefined || height === undefined || wrapper.styles.textAlign) && defined(text.textStr) && text.getBBox(); //#3295 && 3514 box failure when string equals 0 wrapper.width = (width || bBox.width || 0) + 2 * padding + paddingLeft; wrapper.height = (height || bBox.height || 0) + 2 * padding; // update the label-scoped y offset baselineOffset = padding + renderer.fontMetrics(style && style.fontSize, text).b; if (needsBox) { if (!box) { // create the border box if it is not already present boxX = crispAdjust; boxY = (baseline ? -baselineOffset : 0) + crispAdjust; wrapper.box = box = shape ? renderer.symbol(shape, boxX, boxY, wrapper.width, wrapper.height, deferredAttr) : renderer.rect(boxX, boxY, wrapper.width, wrapper.height, 0, deferredAttr[STROKE_WIDTH]); if (!box.isImg) { // #4324, fill "none" causes it to be ignored by mouse events in IE box.attr('fill', NONE); } box.add(wrapper); } // apply the box attributes if (!box.isImg) { // #1630 box.attr(extend({ width: mathRound(wrapper.width), height: mathRound(wrapper.height) }, deferredAttr)); } deferredAttr = null; } }; /** * This function runs after setting text or padding, but only if padding is changed */ updateTextPadding = function () { var styles = wrapper.styles, textAlign = styles && styles.textAlign, x = paddingLeft + padding, y; // determin y based on the baseline y = baseline ? 0 : baselineOffset; // compensate for alignment if (defined(width) && bBox && (textAlign === 'center' || textAlign === 'right')) { x += { center: 0.5, right: 1 }[textAlign] * (width - bBox.width); } // update if anything changed if (x !== text.x || y !== text.y) { text.attr('x', x); if (y !== UNDEFINED) { text.attr('y', y); } } // record current values text.x = x; text.y = y; }; /** * Set a box attribute, or defer it if the box is not yet created * @param {Object} key * @param {Object} value */ boxAttr = function (key, value) { if (box) { box.attr(key, value); } else { deferredAttr[key] = value; } }; /** * After the text element is added, get the desired size of the border box * and add it before the text in the DOM. */ wrapper.onAdd = function () { text.add(wrapper); wrapper.attr({ text: (str || str === 0) ? str : '', // alignment is available now // #3295: 0 not rendered if given as a value x: x, y: y }); if (box && defined(anchorX)) { wrapper.attr({ anchorX: anchorX, anchorY: anchorY }); } }; /* * Add specific attribute setters. */ // only change local variables wrapper.widthSetter = function (value) { width = value; }; wrapper.heightSetter = function (value) { height = value; }; wrapper.paddingSetter = function (value) { if (defined(value) && value !== padding) { padding = wrapper.padding = value; updateTextPadding(); } }; wrapper.paddingLeftSetter = function (value) { if (defined(value) && value !== paddingLeft) { paddingLeft = value; updateTextPadding(); } }; // change local variable and prevent setting attribute on the group wrapper.alignSetter = function (value) { value = { left: 0, center: 0.5, right: 1 }[value]; if (value !== alignFactor) { alignFactor = value; if (bBox) { // Bounding box exists, means we're dynamically changing wrapper.attr({ x: x }); } } }; // apply these to the box and the text alike wrapper.textSetter = function (value) { if (value !== UNDEFINED) { text.textSetter(value); } updateBoxSize(); updateTextPadding(); }; // apply these to the box but not to the text wrapper['stroke-widthSetter'] = function (value, key) { if (value) { needsBox = true; } crispAdjust = value % 2 / 2; boxAttr(key, value); }; wrapper.strokeSetter = wrapper.fillSetter = wrapper.rSetter = function (value, key) { if (key === 'fill' && value) { needsBox = true; } boxAttr(key, value); }; wrapper.anchorXSetter = function (value, key) { anchorX = value; boxAttr(key, mathRound(value) - crispAdjust - wrapperX); }; wrapper.anchorYSetter = function (value, key) { anchorY = value; boxAttr(key, value - wrapperY); }; // rename attributes wrapper.xSetter = function (value) { wrapper.x = value; // for animation getter if (alignFactor) { value -= alignFactor * ((width || bBox.width) + 2 * padding); } wrapperX = mathRound(value); wrapper.attr('translateX', wrapperX); }; wrapper.ySetter = function (value) { wrapperY = wrapper.y = mathRound(value); wrapper.attr('translateY', wrapperY); }; // Redirect certain methods to either the box or the text var baseCss = wrapper.css; return extend(wrapper, { /** * Pick up some properties and apply them to the text instead of the wrapper */ css: function (styles) { if (styles) { var textStyles = {}; styles = merge(styles); // create a copy to avoid altering the original object (#537) each(wrapper.textProps, function (prop) { if (styles[prop] !== UNDEFINED) { textStyles[prop] = styles[prop]; delete styles[prop]; } }); text.css(textStyles); } return baseCss.call(wrapper, styles); }, /** * Return the bounding box of the box, not the group */ getBBox: function () { return { width: bBox.width + 2 * padding, height: bBox.height + 2 * padding, x: bBox.x - padding, y: bBox.y - padding }; }, /** * Apply the shadow to the box */ shadow: function (b) { if (box) { box.shadow(b); } return wrapper; }, /** * Destroy and release memory. */ destroy: function () { // Added by button implementation removeEvent(wrapper.element, 'mouseenter'); removeEvent(wrapper.element, 'mouseleave'); if (text) { text = text.destroy(); } if (box) { box = box.destroy(); } // Call base implementation to destroy the rest SVGElement.prototype.destroy.call(wrapper); // Release local pointers (#1298) wrapper = renderer = updateBoxSize = updateTextPadding = boxAttr = null; } }); } }; // end SVGRenderer // general renderer Renderer = SVGRenderer; // extend SvgElement for useHTML option extend(SVGElement.prototype, { /** * Apply CSS to HTML elements. This is used in text within SVG rendering and * by the VML renderer */ htmlCss: function (styles) { var wrapper = this, element = wrapper.element, textWidth = styles && element.tagName === 'SPAN' && styles.width; if (textWidth) { delete styles.width; wrapper.textWidth = textWidth; wrapper.updateTransform(); } if (styles && styles.textOverflow === 'ellipsis') { styles.whiteSpace = 'nowrap'; styles.overflow = 'hidden'; } wrapper.styles = extend(wrapper.styles, styles); css(wrapper.element, styles); return wrapper; }, /** * VML and useHTML method for calculating the bounding box based on offsets * @param {Boolean} refresh Whether to force a fresh value from the DOM or to * use the cached value * * @return {Object} A hash containing values for x, y, width and height */ htmlGetBBox: function () { var wrapper = this, element = wrapper.element; // faking getBBox in exported SVG in legacy IE // faking getBBox in exported SVG in legacy IE (is this a duplicate of the fix for #1079?) if (element.nodeName === 'text') { element.style.position = ABSOLUTE; } return { x: element.offsetLeft, y: element.offsetTop, width: element.offsetWidth, height: element.offsetHeight }; }, /** * VML override private method to update elements based on internal * properties based on SVG transform */ htmlUpdateTransform: function () { // aligning non added elements is expensive if (!this.added) { this.alignOnAdd = true; return; } var wrapper = this, renderer = wrapper.renderer, elem = wrapper.element, translateX = wrapper.translateX || 0, translateY = wrapper.translateY || 0, x = wrapper.x || 0, y = wrapper.y || 0, align = wrapper.textAlign || 'left', alignCorrection = { left: 0, center: 0.5, right: 1 }[align], shadows = wrapper.shadows, styles = wrapper.styles; // apply translate css(elem, { marginLeft: translateX, marginTop: translateY }); if (shadows) { // used in labels/tooltip each(shadows, function (shadow) { css(shadow, { marginLeft: translateX + 1, marginTop: translateY + 1 }); }); } // apply inversion if (wrapper.inverted) { // wrapper is a group each(elem.childNodes, function (child) { renderer.invertChild(child, elem); }); } if (elem.tagName === 'SPAN') { var rotation = wrapper.rotation, baseline, textWidth = pInt(wrapper.textWidth), whiteSpace = styles && styles.whiteSpace, currentTextTransform = [rotation, align, elem.innerHTML, wrapper.textWidth, wrapper.textAlign].join(','); if (currentTextTransform !== wrapper.cTT) { // do the calculations and DOM access only if properties changed baseline = renderer.fontMetrics(elem.style.fontSize).b; // Renderer specific handling of span rotation if (defined(rotation)) { wrapper.setSpanRotation(rotation, alignCorrection, baseline); } // Update textWidth if (elem.offsetWidth > textWidth && /[ \-]/.test(elem.textContent || elem.innerText)) { // #983, #1254 css(elem, { width: textWidth + PX, display: 'block', whiteSpace: whiteSpace || 'normal' // #3331 }); wrapper.hasTextWidth = true; } else if (wrapper.hasTextWidth) { // #4928 css(elem, { width: '', display: '', whiteSpace: whiteSpace || 'nowrap' }); wrapper.hasTextWidth = false; } wrapper.getSpanCorrection(wrapper.hasTextWidth ? textWidth : elem.offsetWidth, baseline, alignCorrection, rotation, align); } // apply position with correction css(elem, { left: (x + (wrapper.xCorr || 0)) + PX, top: (y + (wrapper.yCorr || 0)) + PX }); // force reflow in webkit to apply the left and top on useHTML element (#1249) if (isWebKit) { baseline = elem.offsetHeight; // assigned to baseline for lint purpose } // record current text transform wrapper.cTT = currentTextTransform; } }, /** * Set the rotation of an individual HTML span */ setSpanRotation: function (rotation, alignCorrection, baseline) { var rotationStyle = {}, cssTransformKey = isMS ? '-ms-transform' : isWebKit ? '-webkit-transform' : isFirefox ? 'MozTransform' : isOpera ? '-o-transform' : ''; rotationStyle[cssTransformKey] = rotationStyle.transform = 'rotate(' + rotation + 'deg)'; rotationStyle[cssTransformKey + (isFirefox ? 'Origin' : '-origin')] = rotationStyle.transformOrigin = (alignCorrection * 100) + '% ' + baseline + 'px'; css(this.element, rotationStyle); }, /** * Get the correction in X and Y positioning as the element is rotated. */ getSpanCorrection: function (width, baseline, alignCorrection) { this.xCorr = -width * alignCorrection; this.yCorr = -baseline; } }); // Extend SvgRenderer for useHTML option. extend(SVGRenderer.prototype, { /** * Create HTML text node. This is used by the VML renderer as well as the SVG * renderer through the useHTML option. * * @param {String} str * @param {Number} x * @param {Number} y */ html: function (str, x, y) { var wrapper = this.createElement('span'), element = wrapper.element, renderer = wrapper.renderer, addSetters = function (element, style) { // These properties are set as attributes on the SVG group, and as // identical CSS properties on the div. (#3542) each(['opacity', 'visibility'], function (prop) { wrap(element, prop + 'Setter', function (proceed, value, key, elem) { proceed.call(this, value, key, elem); style[key] = value; }); }); }; // Text setter wrapper.textSetter = function (value) { if (value !== element.innerHTML) { delete this.bBox; } element.innerHTML = this.textStr = value; wrapper.htmlUpdateTransform(); }; addSetters(wrapper, wrapper.element.style); // Various setters which rely on update transform wrapper.xSetter = wrapper.ySetter = wrapper.alignSetter = wrapper.rotationSetter = function (value, key) { if (key === 'align') { key = 'textAlign'; // Do not overwrite the SVGElement.align method. Same as VML. } wrapper[key] = value; wrapper.htmlUpdateTransform(); }; // Set the default attributes wrapper .attr({ text: str, x: mathRound(x), y: mathRound(y) }) .css({ position: ABSOLUTE, fontFamily: this.style.fontFamily, fontSize: this.style.fontSize }); // Keep the whiteSpace style outside the wrapper.styles collection element.style.whiteSpace = 'nowrap'; // Use the HTML specific .css method wrapper.css = wrapper.htmlCss; // This is specific for HTML within SVG if (renderer.isSVG) { wrapper.add = function (svgGroupWrapper) { var htmlGroup, container = renderer.box.parentNode, parentGroup, parents = []; this.parentGroup = svgGroupWrapper; // Create a mock group to hold the HTML elements if (svgGroupWrapper) { htmlGroup = svgGroupWrapper.div; if (!htmlGroup) { // Read the parent chain into an array and read from top down parentGroup = svgGroupWrapper; while (parentGroup) { parents.push(parentGroup); // Move up to the next parent group parentGroup = parentGroup.parentGroup; } // Ensure dynamically updating position when any parent is translated each(parents.reverse(), function (parentGroup) { var htmlGroupStyle, cls = attr(parentGroup.element, 'class'); if (cls) { cls = { className: cls }; } // else null // Create a HTML div and append it to the parent div to emulate // the SVG group structure htmlGroup = parentGroup.div = parentGroup.div || createElement(DIV, cls, { position: ABSOLUTE, left: (parentGroup.translateX || 0) + PX, top: (parentGroup.translateY || 0) + PX }, htmlGroup || container); // the top group is appended to container // Shortcut htmlGroupStyle = htmlGroup.style; // Set listeners to update the HTML div's position whenever the SVG group // position is changed extend(parentGroup, { translateXSetter: function (value, key) { htmlGroupStyle.left = value + PX; parentGroup[key] = value; parentGroup.doTransform = true; }, translateYSetter: function (value, key) { htmlGroupStyle.top = value + PX; parentGroup[key] = value; parentGroup.doTransform = true; } }); addSetters(parentGroup, htmlGroupStyle); }); } } else { htmlGroup = container; } htmlGroup.appendChild(element); // Shared with VML: wrapper.added = true; if (wrapper.alignOnAdd) { wrapper.htmlUpdateTransform(); } return wrapper; }; } return wrapper; } }); /* **************************************************************************** * * * START OF INTERNET EXPLORER <= 8 SPECIFIC CODE * * * * For applications and websites that don't need IE support, like platform * * targeted mobile apps and web apps, this code can be removed. * * * *****************************************************************************/ /** * @constructor */ var VMLRenderer, VMLElement; if (!hasSVG && !useCanVG) { /** * The VML element wrapper. */ VMLElement = { /** * Initialize a new VML element wrapper. It builds the markup as a string * to minimize DOM traffic. * @param {Object} renderer * @param {Object} nodeName */ init: function (renderer, nodeName) { var wrapper = this, markup = ['<', nodeName, ' filled="f" stroked="f"'], style = ['position: ', ABSOLUTE, ';'], isDiv = nodeName === DIV; // divs and shapes need size if (nodeName === 'shape' || isDiv) { style.push('left:0;top:0;width:1px;height:1px;'); } style.push('visibility: ', isDiv ? HIDDEN : VISIBLE); markup.push(' style="', style.join(''), '"/>'); // create element with default attributes and style if (nodeName) { markup = isDiv || nodeName === 'span' || nodeName === 'img' ? markup.join('') : renderer.prepVML(markup); wrapper.element = createElement(markup); } wrapper.renderer = renderer; }, /** * Add the node to the given parent * @param {Object} parent */ add: function (parent) { var wrapper = this, renderer = wrapper.renderer, element = wrapper.element, box = renderer.box, inverted = parent && parent.inverted, // get the parent node parentNode = parent ? parent.element || parent : box; if (parent) { this.parentGroup = parent; } // if the parent group is inverted, apply inversion on all children if (inverted) { // only on groups renderer.invertChild(element, parentNode); } // append it parentNode.appendChild(element); // align text after adding to be able to read offset wrapper.added = true; if (wrapper.alignOnAdd && !wrapper.deferUpdateTransform) { wrapper.updateTransform(); } // fire an event for internal hooks if (wrapper.onAdd) { wrapper.onAdd(); } return wrapper; }, /** * VML always uses htmlUpdateTransform */ updateTransform: SVGElement.prototype.htmlUpdateTransform, /** * Set the rotation of a span with oldIE's filter */ setSpanRotation: function () { // Adjust for alignment and rotation. Rotation of useHTML content is not yet implemented // but it can probably be implemented for Firefox 3.5+ on user request. FF3.5+ // has support for CSS3 transform. The getBBox method also needs to be updated // to compensate for the rotation, like it currently does for SVG. // Test case: http://jsfiddle.net/highcharts/Ybt44/ var rotation = this.rotation, costheta = mathCos(rotation * deg2rad), sintheta = mathSin(rotation * deg2rad); css(this.element, { filter: rotation ? ['progid:DXImageTransform.Microsoft.Matrix(M11=', costheta, ', M12=', -sintheta, ', M21=', sintheta, ', M22=', costheta, ', sizingMethod=\'auto expand\')'].join('') : NONE }); }, /** * Get the positioning correction for the span after rotating. */ getSpanCorrection: function (width, baseline, alignCorrection, rotation, align) { var costheta = rotation ? mathCos(rotation * deg2rad) : 1, sintheta = rotation ? mathSin(rotation * deg2rad) : 0, height = pick(this.elemHeight, this.element.offsetHeight), quad, nonLeft = align && align !== 'left'; // correct x and y this.xCorr = costheta < 0 && -width; this.yCorr = sintheta < 0 && -height; // correct for baseline and corners spilling out after rotation quad = costheta * sintheta < 0; this.xCorr += sintheta * baseline * (quad ? 1 - alignCorrection : alignCorrection); this.yCorr -= costheta * baseline * (rotation ? (quad ? alignCorrection : 1 - alignCorrection) : 1); // correct for the length/height of the text if (nonLeft) { this.xCorr -= width * alignCorrection * (costheta < 0 ? -1 : 1); if (rotation) { this.yCorr -= height * alignCorrection * (sintheta < 0 ? -1 : 1); } css(this.element, { textAlign: align }); } }, /** * Converts a subset of an SVG path definition to its VML counterpart. Takes an array * as the parameter and returns a string. */ pathToVML: function (value) { // convert paths var i = value.length, path = []; while (i--) { // Multiply by 10 to allow subpixel precision. // Substracting half a pixel seems to make the coordinates // align with SVG, but this hasn't been tested thoroughly if (isNumber(value[i])) { path[i] = mathRound(value[i] * 10) - 5; } else if (value[i] === 'Z') { // close the path path[i] = 'x'; } else { path[i] = value[i]; // When the start X and end X coordinates of an arc are too close, // they are rounded to the same value above. In this case, substract or // add 1 from the end X and Y positions. #186, #760, #1371, #1410. if (value.isArc && (value[i] === 'wa' || value[i] === 'at')) { // Start and end X if (path[i + 5] === path[i + 7]) { path[i + 7] += value[i + 7] > value[i + 5] ? 1 : -1; } // Start and end Y if (path[i + 6] === path[i + 8]) { path[i + 8] += value[i + 8] > value[i + 6] ? 1 : -1; } } } } // Loop up again to handle path shortcuts (#2132) /*while (i++ < path.length) { if (path[i] === 'H') { // horizontal line to path[i] = 'L'; path.splice(i + 2, 0, path[i - 1]); } else if (path[i] === 'V') { // vertical line to path[i] = 'L'; path.splice(i + 1, 0, path[i - 2]); } }*/ return path.join(' ') || 'x'; }, /** * Set the element's clipping to a predefined rectangle * * @param {String} id The id of the clip rectangle */ clip: function (clipRect) { var wrapper = this, clipMembers, cssRet; if (clipRect) { clipMembers = clipRect.members; erase(clipMembers, wrapper); // Ensure unique list of elements (#1258) clipMembers.push(wrapper); wrapper.destroyClip = function () { erase(clipMembers, wrapper); }; cssRet = clipRect.getCSS(wrapper); } else { if (wrapper.destroyClip) { wrapper.destroyClip(); } cssRet = { clip: docMode8 ? 'inherit' : 'rect(auto)' }; // #1214 } return wrapper.css(cssRet); }, /** * Set styles for the element * @param {Object} styles */ css: SVGElement.prototype.htmlCss, /** * Removes a child either by removeChild or move to garbageBin. * Issue 490; in VML removeChild results in Orphaned nodes according to sIEve, discardElement does not. */ safeRemoveChild: function (element) { // discardElement will detach the node from its parent before attaching it // to the garbage bin. Therefore it is important that the node is attached and have parent. if (element.parentNode) { discardElement(element); } }, /** * Extend element.destroy by removing it from the clip members array */ destroy: function () { if (this.destroyClip) { this.destroyClip(); } return SVGElement.prototype.destroy.apply(this); }, /** * Add an event listener. VML override for normalizing event parameters. * @param {String} eventType * @param {Function} handler */ on: function (eventType, handler) { // simplest possible event model for internal use this.element['on' + eventType] = function () { var evt = win.event; evt.target = evt.srcElement; handler(evt); }; return this; }, /** * In stacked columns, cut off the shadows so that they don't overlap */ cutOffPath: function (path, length) { var len; path = path.split(/[ ,]/); len = path.length; if (len === 9 || len === 11) { path[len - 4] = path[len - 2] = pInt(path[len - 2]) - 10 * length; } return path.join(' '); }, /** * Apply a drop shadow by copying elements and giving them different strokes * @param {Boolean|Object} shadowOptions */ shadow: function (shadowOptions, group, cutOff) { var shadows = [], i, element = this.element, renderer = this.renderer, shadow, elemStyle = element.style, markup, path = element.path, strokeWidth, modifiedPath, shadowWidth, shadowElementOpacity; // some times empty paths are not strings if (path && typeof path.value !== 'string') { path = 'x'; } modifiedPath = path; if (shadowOptions) { shadowWidth = pick(shadowOptions.width, 3); shadowElementOpacity = (shadowOptions.opacity || 0.15) / shadowWidth; for (i = 1; i <= 3; i++) { strokeWidth = (shadowWidth * 2) + 1 - (2 * i); // Cut off shadows for stacked column items if (cutOff) { modifiedPath = this.cutOffPath(path.value, strokeWidth + 0.5); } markup = ['<shape isShadow="true" strokeweight="', strokeWidth, '" filled="false" path="', modifiedPath, '" coordsize="10 10" style="', element.style.cssText, '" />']; shadow = createElement(renderer.prepVML(markup), null, { left: pInt(elemStyle.left) + pick(shadowOptions.offsetX, 1), top: pInt(elemStyle.top) + pick(shadowOptions.offsetY, 1) } ); if (cutOff) { shadow.cutOff = strokeWidth + 1; } // apply the opacity markup = ['<stroke color="', shadowOptions.color || 'black', '" opacity="', shadowElementOpacity * i, '"/>']; createElement(renderer.prepVML(markup), null, null, shadow); // insert it if (group) { group.element.appendChild(shadow); } else { element.parentNode.insertBefore(shadow, element); } // record it shadows.push(shadow); } this.shadows = shadows; } return this; }, updateShadows: noop, // Used in SVG only setAttr: function (key, value) { if (docMode8) { // IE8 setAttribute bug this.element[key] = value; } else { this.element.setAttribute(key, value); } }, classSetter: function (value) { // IE8 Standards mode has problems retrieving the className unless set like this this.element.className = value; }, dashstyleSetter: function (value, key, element) { var strokeElem = element.getElementsByTagName('stroke')[0] || createElement(this.renderer.prepVML(['<stroke/>']), null, null, element); strokeElem[key] = value || 'solid'; this[key] = value; /* because changing stroke-width will change the dash length and cause an epileptic effect */ }, dSetter: function (value, key, element) { var i, shadows = this.shadows; value = value || []; this.d = value.join && value.join(' '); // used in getter for animation element.path = value = this.pathToVML(value); // update shadows if (shadows) { i = shadows.length; while (i--) { shadows[i].path = shadows[i].cutOff ? this.cutOffPath(value, shadows[i].cutOff) : value; } } this.setAttr(key, value); }, fillSetter: function (value, key, element) { var nodeName = element.nodeName; if (nodeName === 'SPAN') { // text color element.style.color = value; } else if (nodeName !== 'IMG') { // #1336 element.filled = value !== NONE; this.setAttr('fillcolor', this.renderer.color(value, element, key, this)); } }, 'fill-opacitySetter': function (value, key, element) { createElement( this.renderer.prepVML(['<', key.split('-')[0], ' opacity="', value, '"/>']), null, null, element ); }, opacitySetter: noop, // Don't bother - animation is too slow and filters introduce artifacts rotationSetter: function (value, key, element) { var style = element.style; this[key] = style[key] = value; // style is for #1873 // Correction for the 1x1 size of the shape container. Used in gauge needles. style.left = -mathRound(mathSin(value * deg2rad) + 1) + PX; style.top = mathRound(mathCos(value * deg2rad)) + PX; }, strokeSetter: function (value, key, element) { this.setAttr('strokecolor', this.renderer.color(value, element, key, this)); }, 'stroke-widthSetter': function (value, key, element) { element.stroked = !!value; // VML "stroked" attribute this[key] = value; // used in getter, issue #113 if (isNumber(value)) { value += PX; } this.setAttr('strokeweight', value); }, titleSetter: function (value, key) { this.setAttr(key, value); }, visibilitySetter: function (value, key, element) { // Handle inherited visibility if (value === 'inherit') { value = VISIBLE; } // Let the shadow follow the main element if (this.shadows) { each(this.shadows, function (shadow) { shadow.style[key] = value; }); } // Instead of toggling the visibility CSS property, move the div out of the viewport. // This works around #61 and #586 if (element.nodeName === 'DIV') { value = value === HIDDEN ? '-999em' : 0; // In order to redraw, IE7 needs the div to be visible when tucked away // outside the viewport. So the visibility is actually opposite of // the expected value. This applies to the tooltip only. if (!docMode8) { element.style[key] = value ? VISIBLE : HIDDEN; } key = 'top'; } element.style[key] = value; }, xSetter: function (value, key, element) { this[key] = value; // used in getter if (key === 'x') { key = 'left'; } else if (key === 'y') { key = 'top'; }/* else { value = mathMax(0, value); // don't set width or height below zero (#311) }*/ // clipping rectangle special if (this.updateClipping) { this[key] = value; // the key is now 'left' or 'top' for 'x' and 'y' this.updateClipping(); } else { // normal element.style[key] = value; } }, zIndexSetter: function (value, key, element) { element.style[key] = value; } }; VMLElement['stroke-opacitySetter'] = VMLElement['fill-opacitySetter']; Highcharts.VMLElement = VMLElement = extendClass(SVGElement, VMLElement); // Some shared setters VMLElement.prototype.ySetter = VMLElement.prototype.widthSetter = VMLElement.prototype.heightSetter = VMLElement.prototype.xSetter; /** * The VML renderer */ var VMLRendererExtension = { // inherit SVGRenderer Element: VMLElement, isIE8: userAgent.indexOf('MSIE 8.0') > -1, /** * Initialize the VMLRenderer * @param {Object} container * @param {Number} width * @param {Number} height */ init: function (container, width, height, style) { var renderer = this, boxWrapper, box, css; renderer.alignedObjects = []; boxWrapper = renderer.createElement(DIV) .css(extend(this.getStyle(style), { position: 'relative' })); box = boxWrapper.element; container.appendChild(boxWrapper.element); // generate the containing box renderer.isVML = true; renderer.box = box; renderer.boxWrapper = boxWrapper; renderer.gradients = {}; renderer.cache = {}; // Cache for numerical bounding boxes renderer.cacheKeys = []; renderer.imgCount = 0; renderer.setSize(width, height, false); // The only way to make IE6 and IE7 print is to use a global namespace. However, // with IE8 the only way to make the dynamic shapes visible in screen and print mode // seems to be to add the xmlns attribute and the behaviour style inline. if (!doc.namespaces.hcv) { doc.namespaces.add('hcv', 'urn:schemas-microsoft-com:vml'); // Setup default CSS (#2153, #2368, #2384) css = 'hcv\\:fill, hcv\\:path, hcv\\:shape, hcv\\:stroke' + '{ behavior:url(#default#VML); display: inline-block; } '; try { doc.createStyleSheet().cssText = css; } catch (e) { doc.styleSheets[0].cssText += css; } } }, /** * Detect whether the renderer is hidden. This happens when one of the parent elements * has display: none */ isHidden: function () { return !this.box.offsetWidth; }, /** * Define a clipping rectangle. In VML it is accomplished by storing the values * for setting the CSS style to all associated members. * * @param {Number} x * @param {Number} y * @param {Number} width * @param {Number} height */ clipRect: function (x, y, width, height) { // create a dummy element var clipRect = this.createElement(), isObj = isObject(x); // mimic a rectangle with its style object for automatic updating in attr return extend(clipRect, { members: [], count: 0, left: (isObj ? x.x : x) + 1, top: (isObj ? x.y : y) + 1, width: (isObj ? x.width : width) - 1, height: (isObj ? x.height : height) - 1, getCSS: function (wrapper) { var element = wrapper.element, nodeName = element.nodeName, isShape = nodeName === 'shape', inverted = wrapper.inverted, rect = this, top = rect.top - (isShape ? element.offsetTop : 0), left = rect.left, right = left + rect.width, bottom = top + rect.height, ret = { clip: 'rect(' + mathRound(inverted ? left : top) + 'px,' + mathRound(inverted ? bottom : right) + 'px,' + mathRound(inverted ? right : bottom) + 'px,' + mathRound(inverted ? top : left) + 'px)' }; // issue 74 workaround if (!inverted && docMode8 && nodeName === 'DIV') { extend(ret, { width: right + PX, height: bottom + PX }); } return ret; }, // used in attr and animation to update the clipping of all members updateClipping: function () { each(clipRect.members, function (member) { if (member.element) { // Deleted series, like in stock/members/series-remove demo. Should be removed from members, but this will do. member.css(clipRect.getCSS(member)); } }); } }); }, /** * Take a color and return it if it's a string, make it a gradient if it's a * gradient configuration object, and apply opacity. * * @param {Object} color The color or config object */ color: function (color, elem, prop, wrapper) { var renderer = this, colorObject, regexRgba = /^rgba/, markup, fillType, ret = NONE; // Check for linear or radial gradient if (color && color.linearGradient) { fillType = 'gradient'; } else if (color && color.radialGradient) { fillType = 'pattern'; } if (fillType) { var stopColor, stopOpacity, gradient = color.linearGradient || color.radialGradient, x1, y1, x2, y2, opacity1, opacity2, color1, color2, fillAttr = '', stops = color.stops, firstStop, lastStop, colors = [], addFillNode = function () { // Add the fill subnode. When colors attribute is used, the meanings of opacity and o:opacity2 // are reversed. markup = ['<fill colors="' + colors.join(',') + '" opacity="', opacity2, '" o:opacity2="', opacity1, '" type="', fillType, '" ', fillAttr, 'focus="100%" method="any" />']; createElement(renderer.prepVML(markup), null, null, elem); }; // Extend from 0 to 1 firstStop = stops[0]; lastStop = stops[stops.length - 1]; if (firstStop[0] > 0) { stops.unshift([ 0, firstStop[1] ]); } if (lastStop[0] < 1) { stops.push([ 1, lastStop[1] ]); } // Compute the stops each(stops, function (stop, i) { if (regexRgba.test(stop[1])) { colorObject = Color(stop[1]); stopColor = colorObject.get('rgb'); stopOpacity = colorObject.get('a'); } else { stopColor = stop[1]; stopOpacity = 1; } // Build the color attribute colors.push((stop[0] * 100) + '% ' + stopColor); // Only start and end opacities are allowed, so we use the first and the last if (!i) { opacity1 = stopOpacity; color2 = stopColor; } else { opacity2 = stopOpacity; color1 = stopColor; } }); // Apply the gradient to fills only. if (prop === 'fill') { // Handle linear gradient angle if (fillType === 'gradient') { x1 = gradient.x1 || gradient[0] || 0; y1 = gradient.y1 || gradient[1] || 0; x2 = gradient.x2 || gradient[2] || 0; y2 = gradient.y2 || gradient[3] || 0; fillAttr = 'angle="' + (90 - math.atan( (y2 - y1) / // y vector (x2 - x1) // x vector ) * 180 / mathPI) + '"'; addFillNode(); // Radial (circular) gradient } else { var r = gradient.r, sizex = r * 2, sizey = r * 2, cx = gradient.cx, cy = gradient.cy, radialReference = elem.radialReference, bBox, applyRadialGradient = function () { if (radialReference) { bBox = wrapper.getBBox(); cx += (radialReference[0] - bBox.x) / bBox.width - 0.5; cy += (radialReference[1] - bBox.y) / bBox.height - 0.5; sizex *= radialReference[2] / bBox.width; sizey *= radialReference[2] / bBox.height; } fillAttr = 'src="' + defaultOptions.global.VMLRadialGradientURL + '" ' + 'size="' + sizex + ',' + sizey + '" ' + 'origin="0.5,0.5" ' + 'position="' + cx + ',' + cy + '" ' + 'color2="' + color2 + '" '; addFillNode(); }; // Apply radial gradient if (wrapper.added) { applyRadialGradient(); } else { // We need to know the bounding box to get the size and position right wrapper.onAdd = applyRadialGradient; } // The fill element's color attribute is broken in IE8 standards mode, so we // need to set the parent shape's fillcolor attribute instead. ret = color1; } // Gradients are not supported for VML stroke, return the first color. #722. } else { ret = stopColor; } // If the color is an rgba color, split it and add a fill node // to hold the opacity component } else if (regexRgba.test(color) && elem.tagName !== 'IMG') { colorObject = Color(color); wrapper[prop + '-opacitySetter'](colorObject.get('a'), prop, elem); ret = colorObject.get('rgb'); } else { var propNodes = elem.getElementsByTagName(prop); // 'stroke' or 'fill' node if (propNodes.length) { propNodes[0].opacity = 1; propNodes[0].type = 'solid'; } ret = color; } return ret; }, /** * Take a VML string and prepare it for either IE8 or IE6/IE7. * @param {Array} markup A string array of the VML markup to prepare */ prepVML: function (markup) { var vmlStyle = 'display:inline-block;behavior:url(#default#VML);', isIE8 = this.isIE8; markup = markup.join(''); if (isIE8) { // add xmlns and style inline markup = markup.replace('/>', ' xmlns="urn:schemas-microsoft-com:vml" />'); if (markup.indexOf('style="') === -1) { markup = markup.replace('/>', ' style="' + vmlStyle + '" />'); } else { markup = markup.replace('style="', 'style="' + vmlStyle); } } else { // add namespace markup = markup.replace('<', '<hcv:'); } return markup; }, /** * Create rotated and aligned text * @param {String} str * @param {Number} x * @param {Number} y */ text: SVGRenderer.prototype.html, /** * Create and return a path element * @param {Array} path */ path: function (path) { var attr = { // subpixel precision down to 0.1 (width and height = 1px) coordsize: '10 10' }; if (isArray(path)) { attr.d = path; } else if (isObject(path)) { // attributes extend(attr, path); } // create the shape return this.createElement('shape').attr(attr); }, /** * Create and return a circle element. In VML circles are implemented as * shapes, which is faster than v:oval * @param {Number} x * @param {Number} y * @param {Number} r */ circle: function (x, y, r) { var circle = this.symbol('circle'); if (isObject(x)) { r = x.r; y = x.y; x = x.x; } circle.isCircle = true; // Causes x and y to mean center (#1682) circle.r = r; return circle.attr({ x: x, y: y }); }, /** * Create a group using an outer div and an inner v:group to allow rotating * and flipping. A simple v:group would have problems with positioning * child HTML elements and CSS clip. * * @param {String} name The name of the group */ g: function (name) { var wrapper, attribs; // set the class name if (name) { attribs = { 'className': PREFIX + name, 'class': PREFIX + name }; } // the div to hold HTML and clipping wrapper = this.createElement(DIV).attr(attribs); return wrapper; }, /** * VML override to create a regular HTML image * @param {String} src * @param {Number} x * @param {Number} y * @param {Number} width * @param {Number} height */ image: function (src, x, y, width, height) { var obj = this.createElement('img') .attr({ src: src }); if (arguments.length > 1) { obj.attr({ x: x, y: y, width: width, height: height }); } return obj; }, /** * For rectangles, VML uses a shape for rect to overcome bugs and rotation problems */ createElement: function (nodeName) { return nodeName === 'rect' ? this.symbol(nodeName) : SVGRenderer.prototype.createElement.call(this, nodeName); }, /** * In the VML renderer, each child of an inverted div (group) is inverted * @param {Object} element * @param {Object} parentNode */ invertChild: function (element, parentNode) { var ren = this, parentStyle = parentNode.style, imgStyle = element.tagName === 'IMG' && element.style; // #1111 css(element, { flip: 'x', left: pInt(parentStyle.width) - (imgStyle ? pInt(imgStyle.top) : 1), top: pInt(parentStyle.height) - (imgStyle ? pInt(imgStyle.left) : 1), rotation: -90 }); // Recursively invert child elements, needed for nested composite shapes like box plots and error bars. #1680, #1806. each(element.childNodes, function (child) { ren.invertChild(child, element); }); }, /** * Symbol definitions that override the parent SVG renderer's symbols * */ symbols: { // VML specific arc function arc: function (x, y, w, h, options) { var start = options.start, end = options.end, radius = options.r || w || h, innerRadius = options.innerR, cosStart = mathCos(start), sinStart = mathSin(start), cosEnd = mathCos(end), sinEnd = mathSin(end), ret; if (end - start === 0) { // no angle, don't show it. return ['x']; } ret = [ 'wa', // clockwise arc to x - radius, // left y - radius, // top x + radius, // right y + radius, // bottom x + radius * cosStart, // start x y + radius * sinStart, // start y x + radius * cosEnd, // end x y + radius * sinEnd // end y ]; if (options.open && !innerRadius) { ret.push( 'e', M, x, // - innerRadius, y// - innerRadius ); } ret.push( 'at', // anti clockwise arc to x - innerRadius, // left y - innerRadius, // top x + innerRadius, // right y + innerRadius, // bottom x + innerRadius * cosEnd, // start x y + innerRadius * sinEnd, // start y x + innerRadius * cosStart, // end x y + innerRadius * sinStart, // end y 'x', // finish path 'e' // close ); ret.isArc = true; return ret; }, // Add circle symbol path. This performs significantly faster than v:oval. circle: function (x, y, w, h, wrapper) { if (wrapper) { w = h = 2 * wrapper.r; } // Center correction, #1682 if (wrapper && wrapper.isCircle) { x -= w / 2; y -= h / 2; } // Return the path return [ 'wa', // clockwisearcto x, // left y, // top x + w, // right y + h, // bottom x + w, // start x y + h / 2, // start y x + w, // end x y + h / 2, // end y //'x', // finish path 'e' // close ]; }, /** * Add rectangle symbol path which eases rotation and omits arcsize problems * compared to the built-in VML roundrect shape. When borders are not rounded, * use the simpler square path, else use the callout path without the arrow. */ rect: function (x, y, w, h, options) { return SVGRenderer.prototype.symbols[ !defined(options) || !options.r ? 'square' : 'callout' ].call(0, x, y, w, h, options); } } }; Highcharts.VMLRenderer = VMLRenderer = function () { this.init.apply(this, arguments); }; VMLRenderer.prototype = merge(SVGRenderer.prototype, VMLRendererExtension); // general renderer Renderer = VMLRenderer; } // This method is used with exporting in old IE, when emulating SVG (see #2314) SVGRenderer.prototype.measureSpanWidth = function (text, styles) { var measuringSpan = doc.createElement('span'), offsetWidth, textNode = doc.createTextNode(text); measuringSpan.appendChild(textNode); css(measuringSpan, styles); this.box.appendChild(measuringSpan); offsetWidth = measuringSpan.offsetWidth; discardElement(measuringSpan); // #2463 return offsetWidth; }; /* **************************************************************************** * * * END OF INTERNET EXPLORER <= 8 SPECIFIC CODE * * * *****************************************************************************/ /* **************************************************************************** * * * START OF ANDROID < 3 SPECIFIC CODE. THIS CAN BE REMOVED IF YOU'RE NOT * * TARGETING THAT SYSTEM. * * * *****************************************************************************/ var CanVGRenderer, CanVGController; /** * Downloads a script and executes a callback when done. * @param {String} scriptLocation * @param {Function} callback */ function getScript(scriptLocation, callback) { var head = doc.getElementsByTagName('head')[0], script = doc.createElement('script'); script.type = 'text/javascript'; script.src = scriptLocation; script.onload = callback; head.appendChild(script); } if (useCanVG) { /** * The CanVGRenderer is empty from start to keep the source footprint small. * When requested, the CanVGController downloads the rest of the source packaged * together with the canvg library. */ Highcharts.CanVGRenderer = CanVGRenderer = function () { // Override the global SVG namespace to fake SVG/HTML that accepts CSS SVG_NS = 'http://www.w3.org/1999/xhtml'; }; /** * Start with an empty symbols object. This is needed when exporting is used (exporting.src.js will add a few symbols), but * the implementation from SvgRenderer will not be merged in until first render. */ CanVGRenderer.prototype.symbols = {}; /** * Handles on demand download of canvg rendering support. */ CanVGController = (function () { // List of renderering calls var deferredRenderCalls = []; /** * When downloaded, we are ready to draw deferred charts. */ function drawDeferred() { var callLength = deferredRenderCalls.length, callIndex; // Draw all pending render calls for (callIndex = 0; callIndex < callLength; callIndex++) { deferredRenderCalls[callIndex](); } // Clear the list deferredRenderCalls = []; } return { push: function (func, scriptLocation) { // Only get the script once if (deferredRenderCalls.length === 0) { getScript(scriptLocation, drawDeferred); } // Register render call deferredRenderCalls.push(func); } }; }()); Renderer = CanVGRenderer; } // end CanVGRenderer /* **************************************************************************** * * * END OF ANDROID < 3 SPECIFIC CODE * * * *****************************************************************************/ /** * The Tick class */ function Tick(axis, pos, type, noLabel) { this.axis = axis; this.pos = pos; this.type = type || ''; this.isNew = true; if (!type && !noLabel) { this.addLabel(); } } Tick.prototype = { /** * Write the tick label */ addLabel: function () { var tick = this, axis = tick.axis, options = axis.options, chart = axis.chart, categories = axis.categories, names = axis.names, pos = tick.pos, labelOptions = options.labels, str, tickPositions = axis.tickPositions, isFirst = pos === tickPositions[0], isLast = pos === tickPositions[tickPositions.length - 1], value = categories ? pick(categories[pos], names[pos], pos) : pos, label = tick.label, tickPositionInfo = tickPositions.info, dateTimeLabelFormat; // Set the datetime label format. If a higher rank is set for this position, use that. If not, // use the general format. if (axis.isDatetimeAxis && tickPositionInfo) { dateTimeLabelFormat = options.dateTimeLabelFormats[tickPositionInfo.higherRanks[pos] || tickPositionInfo.unitName]; } // set properties for access in render method tick.isFirst = isFirst; tick.isLast = isLast; // get the string str = axis.labelFormatter.call({ axis: axis, chart: chart, isFirst: isFirst, isLast: isLast, dateTimeLabelFormat: dateTimeLabelFormat, value: axis.isLog ? correctFloat(lin2log(value)) : value }); // prepare CSS //css = width && { width: mathMax(1, mathRound(width - 2 * (labelOptions.padding || 10))) + PX }; // first call if (!defined(label)) { tick.label = label = defined(str) && labelOptions.enabled ? chart.renderer.text( str, 0, 0, labelOptions.useHTML ) //.attr(attr) // without position absolute, IE export sometimes is wrong .css(merge(labelOptions.style)) .add(axis.labelGroup) : null; tick.labelLength = label && label.getBBox().width; // Un-rotated length tick.rotation = 0; // Base value to detect change for new calls to getBBox // update } else if (label) { label.attr({ text: str }); } }, /** * Get the offset height or width of the label */ getLabelSize: function () { return this.label ? this.label.getBBox()[this.axis.horiz ? 'height' : 'width'] : 0; }, /** * Handle the label overflow by adjusting the labels to the left and right edge, or * hide them if they collide into the neighbour label. */ handleOverflow: function (xy) { var axis = this.axis, pxPos = xy.x, chartWidth = axis.chart.chartWidth, spacing = axis.chart.spacing, leftBound = pick(axis.labelLeft, mathMin(axis.pos, spacing[3])), rightBound = pick(axis.labelRight, mathMax(axis.pos + axis.len, chartWidth - spacing[1])), label = this.label, rotation = this.rotation, factor = { left: 0, center: 0.5, right: 1 }[axis.labelAlign], labelWidth = label.getBBox().width, slotWidth = axis.slotWidth, xCorrection = factor, goRight = 1, leftPos, rightPos, textWidth, css = {}; // Check if the label overshoots the chart spacing box. If it does, move it. // If it now overshoots the slotWidth, add ellipsis. if (!rotation) { leftPos = pxPos - factor * labelWidth; rightPos = pxPos + (1 - factor) * labelWidth; if (leftPos < leftBound) { slotWidth = xy.x + slotWidth * (1 - factor) - leftBound; } else if (rightPos > rightBound) { slotWidth = rightBound - xy.x + slotWidth * factor; goRight = -1; } slotWidth = mathMin(axis.slotWidth, slotWidth); // #4177 if (slotWidth < axis.slotWidth && axis.labelAlign === 'center') { xy.x += goRight * (axis.slotWidth - slotWidth - xCorrection * (axis.slotWidth - mathMin(labelWidth, slotWidth))); } // If the label width exceeds the available space, set a text width to be // picked up below. Also, if a width has been set before, we need to set a new // one because the reported labelWidth will be limited by the box (#3938). if (labelWidth > slotWidth || (axis.autoRotation && label.styles.width)) { textWidth = slotWidth; } // Add ellipsis to prevent rotated labels to be clipped against the edge of the chart } else if (rotation < 0 && pxPos - factor * labelWidth < leftBound) { textWidth = mathRound(pxPos / mathCos(rotation * deg2rad) - leftBound); } else if (rotation > 0 && pxPos + factor * labelWidth > rightBound) { textWidth = mathRound((chartWidth - pxPos) / mathCos(rotation * deg2rad)); } if (textWidth) { css.width = textWidth; if (!axis.options.labels.style.textOverflow) { css.textOverflow = 'ellipsis'; } label.css(css); } }, /** * Get the x and y position for ticks and labels */ getPosition: function (horiz, pos, tickmarkOffset, old) { var axis = this.axis, chart = axis.chart, cHeight = (old && chart.oldChartHeight) || chart.chartHeight; return { x: horiz ? axis.translate(pos + tickmarkOffset, null, null, old) + axis.transB : axis.left + axis.offset + (axis.opposite ? ((old && chart.oldChartWidth) || chart.chartWidth) - axis.right - axis.left : 0), y: horiz ? cHeight - axis.bottom + axis.offset - (axis.opposite ? axis.height : 0) : cHeight - axis.translate(pos + tickmarkOffset, null, null, old) - axis.transB }; }, /** * Get the x, y position of the tick label */ getLabelPosition: function (x, y, label, horiz, labelOptions, tickmarkOffset, index, step) { var axis = this.axis, transA = axis.transA, reversed = axis.reversed, staggerLines = axis.staggerLines, rotCorr = axis.tickRotCorr || { x: 0, y: 0 }, yOffset = labelOptions.y, line; if (!defined(yOffset)) { yOffset = axis.side === 2 ? rotCorr.y + 8 : // #3140, #3140 yOffset = mathCos(label.rotation * deg2rad) * (rotCorr.y - label.getBBox(false, 0).height / 2); } x = x + labelOptions.x + rotCorr.x - (tickmarkOffset && horiz ? tickmarkOffset * transA * (reversed ? -1 : 1) : 0); y = y + yOffset - (tickmarkOffset && !horiz ? tickmarkOffset * transA * (reversed ? 1 : -1) : 0); // Correct for staggered labels if (staggerLines) { line = (index / (step || 1) % staggerLines); if (axis.opposite) { line = staggerLines - line - 1; } y += line * (axis.labelOffset / staggerLines); } return { x: x, y: mathRound(y) }; }, /** * Extendible method to return the path of the marker */ getMarkPath: function (x, y, tickLength, tickWidth, horiz, renderer) { return renderer.crispLine([ M, x, y, L, x + (horiz ? 0 : -tickLength), y + (horiz ? tickLength : 0) ], tickWidth); }, /** * Put everything in place * * @param index {Number} * @param old {Boolean} Use old coordinates to prepare an animation into new position */ render: function (index, old, opacity) { var tick = this, axis = tick.axis, options = axis.options, chart = axis.chart, renderer = chart.renderer, horiz = axis.horiz, type = tick.type, label = tick.label, pos = tick.pos, labelOptions = options.labels, gridLine = tick.gridLine, gridPrefix = type ? type + 'Grid' : 'grid', tickPrefix = type ? type + 'Tick' : 'tick', gridLineWidth = options[gridPrefix + 'LineWidth'], gridLineColor = options[gridPrefix + 'LineColor'], dashStyle = options[gridPrefix + 'LineDashStyle'], tickLength = options[tickPrefix + 'Length'], tickWidth = pick(options[tickPrefix + 'Width'], !type && axis.isXAxis ? 1 : 0), // X axis defaults to 1 tickColor = options[tickPrefix + 'Color'], tickPosition = options[tickPrefix + 'Position'], gridLinePath, mark = tick.mark, markPath, step = /*axis.labelStep || */labelOptions.step, attribs, show = true, tickmarkOffset = axis.tickmarkOffset, xy = tick.getPosition(horiz, pos, tickmarkOffset, old), x = xy.x, y = xy.y, reverseCrisp = ((horiz && x === axis.pos + axis.len) || (!horiz && y === axis.pos)) ? -1 : 1; // #1480, #1687 opacity = pick(opacity, 1); this.isActive = true; // create the grid line if (gridLineWidth) { gridLinePath = axis.getPlotLinePath(pos + tickmarkOffset, gridLineWidth * reverseCrisp, old, true); if (gridLine === UNDEFINED) { attribs = { stroke: gridLineColor, 'stroke-width': gridLineWidth }; if (dashStyle) { attribs.dashstyle = dashStyle; } if (!type) { attribs.zIndex = 1; } if (old) { attribs.opacity = 0; } tick.gridLine = gridLine = gridLineWidth ? renderer.path(gridLinePath) .attr(attribs).add(axis.gridGroup) : null; } // If the parameter 'old' is set, the current call will be followed // by another call, therefore do not do any animations this time if (!old && gridLine && gridLinePath) { gridLine[tick.isNew ? 'attr' : 'animate']({ d: gridLinePath, opacity: opacity }); } } // create the tick mark if (tickWidth && tickLength) { // negate the length if (tickPosition === 'inside') { tickLength = -tickLength; } if (axis.opposite) { tickLength = -tickLength; } markPath = tick.getMarkPath(x, y, tickLength, tickWidth * reverseCrisp, horiz, renderer); if (mark) { // updating mark.animate({ d: markPath, opacity: opacity }); } else { // first time tick.mark = renderer.path( markPath ).attr({ stroke: tickColor, 'stroke-width': tickWidth, opacity: opacity }).add(axis.axisGroup); } } // the label is created on init - now move it into place if (label && !isNaN(x)) { label.xy = xy = tick.getLabelPosition(x, y, label, horiz, labelOptions, tickmarkOffset, index, step); // Apply show first and show last. If the tick is both first and last, it is // a single centered tick, in which case we show the label anyway (#2100). if ((tick.isFirst && !tick.isLast && !pick(options.showFirstLabel, 1)) || (tick.isLast && !tick.isFirst && !pick(options.showLastLabel, 1))) { show = false; // Handle label overflow and show or hide accordingly } else if (horiz && !axis.isRadial && !labelOptions.step && !labelOptions.rotation && !old && opacity !== 0) { tick.handleOverflow(xy); } // apply step if (step && index % step) { // show those indices dividable by step show = false; } // Set the new position, and show or hide if (show && !isNaN(xy.y)) { xy.opacity = opacity; label[tick.isNew ? 'attr' : 'animate'](xy); tick.isNew = false; } else { label.attr('y', -9999); // #1338 } } }, /** * Destructor for the tick prototype */ destroy: function () { destroyObjectProperties(this, this.axis); } }; /** * Create a new axis object * @param {Object} chart * @param {Object} options */ var Axis = Highcharts.Axis = function () { this.init.apply(this, arguments); }; Axis.prototype = { /** * Default options for the X axis - the Y axis has extended defaults */ defaultOptions: { // allowDecimals: null, // alternateGridColor: null, // categories: [], dateTimeLabelFormats: { millisecond: '%H:%M:%S.%L', second: '%H:%M:%S', minute: '%H:%M', hour: '%H:%M', day: '%e. %b', week: '%e. %b', month: '%b \'%y', year: '%Y' }, endOnTick: false, gridLineColor: '#D8D8D8', // gridLineDashStyle: 'solid', // gridLineWidth: 0, // reversed: false, labels: { enabled: true, // rotation: 0, // align: 'center', // step: null, style: { color: '#606060', cursor: 'default', fontSize: '11px' }, x: 0, y: 15 /*formatter: function () { return this.value; },*/ }, lineColor: '#C0D0E0', lineWidth: 1, //linkedTo: null, //max: undefined, //min: undefined, minPadding: 0.01, maxPadding: 0.01, //minRange: null, minorGridLineColor: '#E0E0E0', // minorGridLineDashStyle: null, minorGridLineWidth: 1, minorTickColor: '#A0A0A0', //minorTickInterval: null, minorTickLength: 2, minorTickPosition: 'outside', // inside or outside //minorTickWidth: 0, //opposite: false, //offset: 0, //plotBands: [{ // events: {}, // zIndex: 1, // labels: { align, x, verticalAlign, y, style, rotation, textAlign } //}], //plotLines: [{ // events: {} // dashStyle: {} // zIndex: // labels: { align, x, verticalAlign, y, style, rotation, textAlign } //}], //reversed: false, // showFirstLabel: true, // showLastLabel: true, startOfWeek: 1, startOnTick: false, tickColor: '#C0D0E0', //tickInterval: null, tickLength: 10, tickmarkPlacement: 'between', // on or between tickPixelInterval: 100, tickPosition: 'outside', //tickWidth: 1, title: { //text: null, align: 'middle', // low, middle or high //margin: 0 for horizontal, 10 for vertical axes, //rotation: 0, //side: 'outside', style: { color: '#707070' } //x: 0, //y: 0 }, type: 'linear' // linear, logarithmic or datetime //visible: true }, /** * This options set extends the defaultOptions for Y axes */ defaultYAxisOptions: { endOnTick: true, gridLineWidth: 1, tickPixelInterval: 72, showLastLabel: true, labels: { x: -8, y: 3 }, lineWidth: 0, maxPadding: 0.05, minPadding: 0.05, startOnTick: true, //tickWidth: 0, title: { rotation: 270, text: 'Values' }, stackLabels: { enabled: false, //align: dynamic, //y: dynamic, //x: dynamic, //verticalAlign: dynamic, //textAlign: dynamic, //rotation: 0, formatter: function () { return Highcharts.numberFormat(this.total, -1); }, style: merge(defaultPlotOptions.line.dataLabels.style, { color: '#000000' }) } }, /** * These options extend the defaultOptions for left axes */ defaultLeftAxisOptions: { labels: { x: -15, y: null }, title: { rotation: 270 } }, /** * These options extend the defaultOptions for right axes */ defaultRightAxisOptions: { labels: { x: 15, y: null }, title: { rotation: 90 } }, /** * These options extend the defaultOptions for bottom axes */ defaultBottomAxisOptions: { labels: { autoRotation: [-45], x: 0, y: null // based on font size // overflow: undefined, // staggerLines: null }, title: { rotation: 0 } }, /** * These options extend the defaultOptions for top axes */ defaultTopAxisOptions: { labels: { autoRotation: [-45], x: 0, y: -15 // overflow: undefined // staggerLines: null }, title: { rotation: 0 } }, /** * Initialize the axis */ init: function (chart, userOptions) { var isXAxis = userOptions.isX, axis = this; axis.chart = chart; // Flag, is the axis horizontal axis.horiz = chart.inverted ? !isXAxis : isXAxis; // Flag, isXAxis axis.isXAxis = isXAxis; axis.coll = isXAxis ? 'xAxis' : 'yAxis'; axis.opposite = userOptions.opposite; // needed in setOptions axis.side = userOptions.side || (axis.horiz ? (axis.opposite ? 0 : 2) : // top : bottom (axis.opposite ? 1 : 3)); // right : left axis.setOptions(userOptions); var options = this.options, type = options.type, isDatetimeAxis = type === 'datetime'; axis.labelFormatter = options.labels.formatter || axis.defaultLabelFormatter; // can be overwritten by dynamic format // Flag, stagger lines or not axis.userOptions = userOptions; //axis.axisTitleMargin = UNDEFINED,// = options.title.margin, axis.minPixelPadding = 0; axis.reversed = options.reversed; axis.visible = options.visible !== false; axis.zoomEnabled = options.zoomEnabled !== false; // Initial categories axis.categories = options.categories || type === 'category'; axis.names = axis.names || []; // Preserve on update (#3830) // Elements //axis.axisGroup = UNDEFINED; //axis.gridGroup = UNDEFINED; //axis.axisTitle = UNDEFINED; //axis.axisLine = UNDEFINED; // Shorthand types axis.isLog = type === 'logarithmic'; axis.isDatetimeAxis = isDatetimeAxis; // Flag, if axis is linked to another axis axis.isLinked = defined(options.linkedTo); // Linked axis. //axis.linkedParent = UNDEFINED; // Tick positions //axis.tickPositions = UNDEFINED; // array containing predefined positions // Tick intervals //axis.tickInterval = UNDEFINED; //axis.minorTickInterval = UNDEFINED; // Major ticks axis.ticks = {}; axis.labelEdge = []; // Minor ticks axis.minorTicks = {}; // List of plotLines/Bands axis.plotLinesAndBands = []; // Alternate bands axis.alternateBands = {}; // Axis metrics //axis.left = UNDEFINED; //axis.top = UNDEFINED; //axis.width = UNDEFINED; //axis.height = UNDEFINED; //axis.bottom = UNDEFINED; //axis.right = UNDEFINED; //axis.transA = UNDEFINED; //axis.transB = UNDEFINED; //axis.oldTransA = UNDEFINED; axis.len = 0; //axis.oldMin = UNDEFINED; //axis.oldMax = UNDEFINED; //axis.oldUserMin = UNDEFINED; //axis.oldUserMax = UNDEFINED; //axis.oldAxisLength = UNDEFINED; axis.minRange = axis.userMinRange = options.minRange || options.maxZoom; axis.range = options.range; axis.offset = options.offset || 0; // Dictionary for stacks axis.stacks = {}; axis.oldStacks = {}; axis.stacksTouched = 0; // Min and max in the data //axis.dataMin = UNDEFINED, //axis.dataMax = UNDEFINED, // The axis range axis.max = null; axis.min = null; // User set min and max //axis.userMin = UNDEFINED, //axis.userMax = UNDEFINED, // Crosshair options axis.crosshair = pick(options.crosshair, splat(chart.options.tooltip.crosshairs)[isXAxis ? 0 : 1], false); // Run Axis var eventType, events = axis.options.events; // Register if (inArray(axis, chart.axes) === -1) { // don't add it again on Axis.update() if (isXAxis && !this.isColorAxis) { // #2713 chart.axes.splice(chart.xAxis.length, 0, axis); } else { chart.axes.push(axis); } chart[axis.coll].push(axis); } axis.series = axis.series || []; // populated by Series // inverted charts have reversed xAxes as default if (chart.inverted && isXAxis && axis.reversed === UNDEFINED) { axis.reversed = true; } axis.removePlotBand = axis.removePlotBandOrLine; axis.removePlotLine = axis.removePlotBandOrLine; // register event listeners for (eventType in events) { addEvent(axis, eventType, events[eventType]); } // extend logarithmic axis if (axis.isLog) { axis.val2lin = log2lin; axis.lin2val = lin2log; } }, /** * Merge and set options */ setOptions: function (userOptions) { this.options = merge( this.defaultOptions, this.isXAxis ? {} : this.defaultYAxisOptions, [this.defaultTopAxisOptions, this.defaultRightAxisOptions, this.defaultBottomAxisOptions, this.defaultLeftAxisOptions][this.side], merge( defaultOptions[this.coll], // if set in setOptions (#1053) userOptions ) ); }, /** * The default label formatter. The context is a special config object for the label. */ defaultLabelFormatter: function () { var axis = this.axis, value = this.value, categories = axis.categories, dateTimeLabelFormat = this.dateTimeLabelFormat, numericSymbols = defaultOptions.lang.numericSymbols, i = numericSymbols && numericSymbols.length, multi, ret, formatOption = axis.options.labels.format, // make sure the same symbol is added for all labels on a linear axis numericSymbolDetector = axis.isLog ? value : axis.tickInterval; if (formatOption) { ret = format(formatOption, this); } else if (categories) { ret = value; } else if (dateTimeLabelFormat) { // datetime axis ret = dateFormat(dateTimeLabelFormat, value); } else if (i && numericSymbolDetector >= 1000) { // Decide whether we should add a numeric symbol like k (thousands) or M (millions). // If we are to enable this in tooltip or other places as well, we can move this // logic to the numberFormatter and enable it by a parameter. while (i-- && ret === UNDEFINED) { multi = Math.pow(1000, i + 1); if (numericSymbolDetector >= multi && (value * 10) % multi === 0 && numericSymbols[i] !== null) { ret = Highcharts.numberFormat(value / multi, -1) + numericSymbols[i]; } } } if (ret === UNDEFINED) { if (mathAbs(value) >= 10000) { // add thousands separators ret = Highcharts.numberFormat(value, -1); } else { // small numbers ret = Highcharts.numberFormat(value, -1, UNDEFINED, ''); // #2466 } } return ret; }, /** * Get the minimum and maximum for the series of each axis */ getSeriesExtremes: function () { var axis = this, chart = axis.chart; axis.hasVisibleSeries = false; // Reset properties in case we're redrawing (#3353) axis.dataMin = axis.dataMax = axis.threshold = null; axis.softThreshold = !axis.isXAxis; if (axis.buildStacks) { axis.buildStacks(); } // loop through this axis' series each(axis.series, function (series) { if (series.visible || !chart.options.chart.ignoreHiddenSeries) { var seriesOptions = series.options, xData, threshold = seriesOptions.threshold, seriesDataMin, seriesDataMax; axis.hasVisibleSeries = true; // Validate threshold in logarithmic axes if (axis.isLog && threshold <= 0) { threshold = null; } // Get dataMin and dataMax for X axes if (axis.isXAxis) { xData = series.xData; if (xData.length) { axis.dataMin = mathMin(pick(axis.dataMin, xData[0]), arrayMin(xData)); axis.dataMax = mathMax(pick(axis.dataMax, xData[0]), arrayMax(xData)); } // Get dataMin and dataMax for Y axes, as well as handle stacking and processed data } else { // Get this particular series extremes series.getExtremes(); seriesDataMax = series.dataMax; seriesDataMin = series.dataMin; // Get the dataMin and dataMax so far. If percentage is used, the min and max are // always 0 and 100. If seriesDataMin and seriesDataMax is null, then series // doesn't have active y data, we continue with nulls if (defined(seriesDataMin) && defined(seriesDataMax)) { axis.dataMin = mathMin(pick(axis.dataMin, seriesDataMin), seriesDataMin); axis.dataMax = mathMax(pick(axis.dataMax, seriesDataMax), seriesDataMax); } // Adjust to threshold if (defined(threshold)) { axis.threshold = threshold; } // If any series has a hard threshold, it takes precedence if (!seriesOptions.softThreshold || axis.isLog) { axis.softThreshold = false; } } } }); }, /** * Translate from axis value to pixel position on the chart, or back * */ translate: function (val, backwards, cvsCoord, old, handleLog, pointPlacement) { var axis = this.linkedParent || this, // #1417 sign = 1, cvsOffset = 0, localA = old ? axis.oldTransA : axis.transA, localMin = old ? axis.oldMin : axis.min, returnValue, minPixelPadding = axis.minPixelPadding, doPostTranslate = (axis.isOrdinal || axis.isBroken || (axis.isLog && handleLog)) && axis.lin2val; if (!localA) { localA = axis.transA; } // In vertical axes, the canvas coordinates start from 0 at the top like in // SVG. if (cvsCoord) { sign *= -1; // canvas coordinates inverts the value cvsOffset = axis.len; } // Handle reversed axis if (axis.reversed) { sign *= -1; cvsOffset -= sign * (axis.sector || axis.len); } // From pixels to value if (backwards) { // reverse translation val = val * sign + cvsOffset; val -= minPixelPadding; returnValue = val / localA + localMin; // from chart pixel to value if (doPostTranslate) { // log and ordinal axes returnValue = axis.lin2val(returnValue); } // From value to pixels } else { if (doPostTranslate) { // log and ordinal axes val = axis.val2lin(val); } if (pointPlacement === 'between') { pointPlacement = 0.5; } returnValue = sign * (val - localMin) * localA + cvsOffset + (sign * minPixelPadding) + (isNumber(pointPlacement) ? localA * pointPlacement * axis.pointRange : 0); } return returnValue; }, /** * Utility method to translate an axis value to pixel position. * @param {Number} value A value in terms of axis units * @param {Boolean} paneCoordinates Whether to return the pixel coordinate relative to the chart * or just the axis/pane itself. */ toPixels: function (value, paneCoordinates) { return this.translate(value, false, !this.horiz, null, true) + (paneCoordinates ? 0 : this.pos); }, /* * Utility method to translate a pixel position in to an axis value * @param {Number} pixel The pixel value coordinate * @param {Boolean} paneCoordiantes Whether the input pixel is relative to the chart or just the * axis/pane itself. */ toValue: function (pixel, paneCoordinates) { return this.translate(pixel - (paneCoordinates ? 0 : this.pos), true, !this.horiz, null, true); }, /** * Create the path for a plot line that goes from the given value on * this axis, across the plot to the opposite side * @param {Number} value * @param {Number} lineWidth Used for calculation crisp line * @param {Number] old Use old coordinates (for resizing and rescaling) */ getPlotLinePath: function (value, lineWidth, old, force, translatedValue) { var axis = this, chart = axis.chart, axisLeft = axis.left, axisTop = axis.top, x1, y1, x2, y2, cHeight = (old && chart.oldChartHeight) || chart.chartHeight, cWidth = (old && chart.oldChartWidth) || chart.chartWidth, skip, transB = axis.transB, /** * Check if x is between a and b. If not, either move to a/b or skip, * depending on the force parameter. */ between = function (x, a, b) { if (x < a || x > b) { if (force) { x = mathMin(mathMax(a, x), b); } else { skip = true; } } return x; }; translatedValue = pick(translatedValue, axis.translate(value, null, null, old)); x1 = x2 = mathRound(translatedValue + transB); y1 = y2 = mathRound(cHeight - translatedValue - transB); if (isNaN(translatedValue)) { // no min or max skip = true; } else if (axis.horiz) { y1 = axisTop; y2 = cHeight - axis.bottom; x1 = x2 = between(x1, axisLeft, axisLeft + axis.width); } else { x1 = axisLeft; x2 = cWidth - axis.right; y1 = y2 = between(y1, axisTop, axisTop + axis.height); } return skip && !force ? null : chart.renderer.crispLine([M, x1, y1, L, x2, y2], lineWidth || 1); }, /** * Set the tick positions of a linear axis to round values like whole tens or every five. */ getLinearTickPositions: function (tickInterval, min, max) { var pos, lastPos, roundedMin = correctFloat(mathFloor(min / tickInterval) * tickInterval), roundedMax = correctFloat(mathCeil(max / tickInterval) * tickInterval), tickPositions = []; // For single points, add a tick regardless of the relative position (#2662) if (min === max && isNumber(min)) { return [min]; } // Populate the intermediate values pos = roundedMin; while (pos <= roundedMax) { // Place the tick on the rounded value tickPositions.push(pos); // Always add the raw tickInterval, not the corrected one. pos = correctFloat(pos + tickInterval); // If the interval is not big enough in the current min - max range to actually increase // the loop variable, we need to break out to prevent endless loop. Issue #619 if (pos === lastPos) { break; } // Record the last value lastPos = pos; } return tickPositions; }, /** * Return the minor tick positions. For logarithmic axes, reuse the same logic * as for major ticks. */ getMinorTickPositions: function () { var axis = this, options = axis.options, tickPositions = axis.tickPositions, minorTickInterval = axis.minorTickInterval, minorTickPositions = [], pos, i, pointRangePadding = axis.pointRangePadding || 0, min = axis.min - pointRangePadding, // #1498 max = axis.max + pointRangePadding, // #1498 range = max - min, len; // If minor ticks get too dense, they are hard to read, and may cause long running script. So we don't draw them. if (range && range / minorTickInterval < axis.len / 3) { // #3875 if (axis.isLog) { len = tickPositions.length; for (i = 1; i < len; i++) { minorTickPositions = minorTickPositions.concat( axis.getLogTickPositions(minorTickInterval, tickPositions[i - 1], tickPositions[i], true) ); } } else if (axis.isDatetimeAxis && options.minorTickInterval === 'auto') { // #1314 minorTickPositions = minorTickPositions.concat( axis.getTimeTicks( axis.normalizeTimeTickInterval(minorTickInterval), min, max, options.startOfWeek ) ); } else { for (pos = min + (tickPositions[0] - min) % minorTickInterval; pos <= max; pos += minorTickInterval) { minorTickPositions.push(pos); } } } if (minorTickPositions.length !== 0) { // don't change the extremes, when there is no minor ticks axis.trimTicks(minorTickPositions, options.startOnTick, options.endOnTick); // #3652 #3743 #1498 } return minorTickPositions; }, /** * Adjust the min and max for the minimum range. Keep in mind that the series data is * not yet processed, so we don't have information on data cropping and grouping, or * updated axis.pointRange or series.pointRange. The data can't be processed until * we have finally established min and max. */ adjustForMinRange: function () { var axis = this, options = axis.options, min = axis.min, max = axis.max, zoomOffset, spaceAvailable = axis.dataMax - axis.dataMin >= axis.minRange, closestDataRange, i, distance, xData, loopLength, minArgs, maxArgs, minRange; // Set the automatic minimum range based on the closest point distance if (axis.isXAxis && axis.minRange === UNDEFINED && !axis.isLog) { if (defined(options.min) || defined(options.max)) { axis.minRange = null; // don't do this again } else { // Find the closest distance between raw data points, as opposed to // closestPointRange that applies to processed points (cropped and grouped) each(axis.series, function (series) { xData = series.xData; loopLength = series.xIncrement ? 1 : xData.length - 1; for (i = loopLength; i > 0; i--) { distance = xData[i] - xData[i - 1]; if (closestDataRange === UNDEFINED || distance < closestDataRange) { closestDataRange = distance; } } }); axis.minRange = mathMin(closestDataRange * 5, axis.dataMax - axis.dataMin); } } // if minRange is exceeded, adjust if (max - min < axis.minRange) { minRange = axis.minRange; zoomOffset = (minRange - max + min) / 2; // if min and max options have been set, don't go beyond it minArgs = [min - zoomOffset, pick(options.min, min - zoomOffset)]; if (spaceAvailable) { // if space is available, stay within the data range minArgs[2] = axis.dataMin; } min = arrayMax(minArgs); maxArgs = [min + minRange, pick(options.max, min + minRange)]; if (spaceAvailable) { // if space is availabe, stay within the data range maxArgs[2] = axis.dataMax; } max = arrayMin(maxArgs); // now if the max is adjusted, adjust the min back if (max - min < minRange) { minArgs[0] = max - minRange; minArgs[1] = pick(options.min, max - minRange); min = arrayMax(minArgs); } } // Record modified extremes axis.min = min; axis.max = max; }, /** * Update translation information */ setAxisTranslation: function (saveOld) { var axis = this, range = axis.max - axis.min, pointRange = axis.axisPointRange || 0, closestPointRange, minPointOffset = 0, pointRangePadding = 0, linkedParent = axis.linkedParent, ordinalCorrection, hasCategories = !!axis.categories, transA = axis.transA, isXAxis = axis.isXAxis; // Adjust translation for padding. Y axis with categories need to go through the same (#1784). if (isXAxis || hasCategories || pointRange) { if (linkedParent) { minPointOffset = linkedParent.minPointOffset; pointRangePadding = linkedParent.pointRangePadding; } else { // Find the closestPointRange across all series each(axis.series, function (series) { var seriesClosest = series.closestPointRange; if (!series.noSharedTooltip && defined(seriesClosest)) { closestPointRange = defined(closestPointRange) ? mathMin(closestPointRange, seriesClosest) : seriesClosest; } }); each(axis.series, function (series) { var seriesPointRange = hasCategories ? 1 : (isXAxis ? pick(series.options.pointRange, closestPointRange, 0) : (axis.axisPointRange || 0)), // #2806 pointPlacement = series.options.pointPlacement; pointRange = mathMax(pointRange, seriesPointRange); if (!axis.single) { // minPointOffset is the value padding to the left of the axis in order to make // room for points with a pointRange, typically columns. When the pointPlacement option // is 'between' or 'on', this padding does not apply. minPointOffset = mathMax( minPointOffset, isString(pointPlacement) ? 0 : seriesPointRange / 2 ); // Determine the total padding needed to the length of the axis to make room for the // pointRange. If the series' pointPlacement is 'on', no padding is added. pointRangePadding = mathMax( pointRangePadding, pointPlacement === 'on' ? 0 : seriesPointRange ); } }); } // Record minPointOffset and pointRangePadding ordinalCorrection = axis.ordinalSlope && closestPointRange ? axis.ordinalSlope / closestPointRange : 1; // #988, #1853 axis.minPointOffset = minPointOffset = minPointOffset * ordinalCorrection; axis.pointRangePadding = pointRangePadding = pointRangePadding * ordinalCorrection; // pointRange means the width reserved for each point, like in a column chart axis.pointRange = mathMin(pointRange, range); // closestPointRange means the closest distance between points. In columns // it is mostly equal to pointRange, but in lines pointRange is 0 while closestPointRange // is some other value if (isXAxis) { axis.closestPointRange = closestPointRange; } } // Secondary values if (saveOld) { axis.oldTransA = transA; } axis.translationSlope = axis.transA = transA = axis.len / ((range + pointRangePadding) || 1); axis.transB = axis.horiz ? axis.left : axis.bottom; // translation addend axis.minPixelPadding = transA * minPointOffset; }, minFromRange: function () { return this.max - this.range; }, /** * Set the tick positions to round values and optionally extend the extremes * to the nearest tick */ setTickInterval: function (secondPass) { var axis = this, chart = axis.chart, options = axis.options, isLog = axis.isLog, isDatetimeAxis = axis.isDatetimeAxis, isXAxis = axis.isXAxis, isLinked = axis.isLinked, maxPadding = options.maxPadding, minPadding = options.minPadding, length, linkedParentExtremes, tickIntervalOption = options.tickInterval, minTickInterval, tickPixelIntervalOption = options.tickPixelInterval, categories = axis.categories, threshold = axis.threshold, softThreshold = axis.softThreshold, thresholdMin, thresholdMax, hardMin, hardMax; if (!isDatetimeAxis && !categories && !isLinked) { this.getTickAmount(); } // Min or max set either by zooming/setExtremes or initial options hardMin = pick(axis.userMin, options.min); hardMax = pick(axis.userMax, options.max); // Linked axis gets the extremes from the parent axis if (isLinked) { axis.linkedParent = chart[axis.coll][options.linkedTo]; linkedParentExtremes = axis.linkedParent.getExtremes(); axis.min = pick(linkedParentExtremes.min, linkedParentExtremes.dataMin); axis.max = pick(linkedParentExtremes.max, linkedParentExtremes.dataMax); if (options.type !== axis.linkedParent.options.type) { error(11, 1); // Can't link axes of different type } // Initial min and max from the extreme data values } else { // Adjust to hard threshold if (!softThreshold && defined(threshold)) { if (axis.dataMin >= threshold) { thresholdMin = threshold; minPadding = 0; } else if (axis.dataMax <= threshold) { thresholdMax = threshold; maxPadding = 0; } } axis.min = pick(hardMin, thresholdMin, axis.dataMin); axis.max = pick(hardMax, thresholdMax, axis.dataMax); } if (isLog) { if (!secondPass && mathMin(axis.min, pick(axis.dataMin, axis.min)) <= 0) { // #978 error(10, 1); // Can't plot negative values on log axis } // The correctFloat cures #934, float errors on full tens. But it // was too aggressive for #4360 because of conversion back to lin, // therefore use precision 15. axis.min = correctFloat(log2lin(axis.min), 15); axis.max = correctFloat(log2lin(axis.max), 15); } // handle zoomed range if (axis.range && defined(axis.max)) { axis.userMin = axis.min = hardMin = mathMax(axis.min, axis.minFromRange()); // #618 axis.userMax = hardMax = axis.max; axis.range = null; // don't use it when running setExtremes } // Hook for adjusting this.min and this.max. Used by bubble series. if (axis.beforePadding) { axis.beforePadding(); } // adjust min and max for the minimum range axis.adjustForMinRange(); // Pad the values to get clear of the chart's edges. To avoid tickInterval taking the padding // into account, we do this after computing tick interval (#1337). if (!categories && !axis.axisPointRange && !axis.usePercentage && !isLinked && defined(axis.min) && defined(axis.max)) { length = axis.max - axis.min; if (length) { if (!defined(hardMin) && minPadding) { axis.min -= length * minPadding; } if (!defined(hardMax) && maxPadding) { axis.max += length * maxPadding; } } } // Stay within floor and ceiling if (isNumber(options.floor)) { axis.min = mathMax(axis.min, options.floor); } if (isNumber(options.ceiling)) { axis.max = mathMin(axis.max, options.ceiling); } // When the threshold is soft, adjust the extreme value only if // the data extreme and the padded extreme land on either side of the threshold. For example, // a series of [0, 1, 2, 3] would make the yAxis add a tick for -1 because of the // default minPadding and startOnTick options. This is prevented by the softThreshold // option. if (softThreshold && defined(axis.dataMin)) { threshold = threshold || 0; if (!defined(hardMin) && axis.min < threshold && axis.dataMin >= threshold) { axis.min = threshold; } else if (!defined(hardMax) && axis.max > threshold && axis.dataMax <= threshold) { axis.max = threshold; } } // get tickInterval if (axis.min === axis.max || axis.min === undefined || axis.max === undefined) { axis.tickInterval = 1; } else if (isLinked && !tickIntervalOption && tickPixelIntervalOption === axis.linkedParent.options.tickPixelInterval) { axis.tickInterval = tickIntervalOption = axis.linkedParent.tickInterval; } else { axis.tickInterval = pick( tickIntervalOption, this.tickAmount ? ((axis.max - axis.min) / mathMax(this.tickAmount - 1, 1)) : undefined, categories ? // for categoried axis, 1 is default, for linear axis use tickPix 1 : // don't let it be more than the data range (axis.max - axis.min) * tickPixelIntervalOption / mathMax(axis.len, tickPixelIntervalOption) ); } // Now we're finished detecting min and max, crop and group series data. This // is in turn needed in order to find tick positions in ordinal axes. if (isXAxis && !secondPass) { each(axis.series, function (series) { series.processData(axis.min !== axis.oldMin || axis.max !== axis.oldMax); }); } // set the translation factor used in translate function axis.setAxisTranslation(true); // hook for ordinal axes and radial axes if (axis.beforeSetTickPositions) { axis.beforeSetTickPositions(); } // hook for extensions, used in Highstock ordinal axes if (axis.postProcessTickInterval) { axis.tickInterval = axis.postProcessTickInterval(axis.tickInterval); } // In column-like charts, don't cramp in more ticks than there are points (#1943, #4184) if (axis.pointRange && !tickIntervalOption) { axis.tickInterval = mathMax(axis.pointRange, axis.tickInterval); } // Before normalizing the tick interval, handle minimum tick interval. This applies only if tickInterval is not defined. minTickInterval = pick(options.minTickInterval, axis.isDatetimeAxis && axis.closestPointRange); if (!tickIntervalOption && axis.tickInterval < minTickInterval) { axis.tickInterval = minTickInterval; } // for linear axes, get magnitude and normalize the interval if (!isDatetimeAxis && !isLog && !tickIntervalOption) { axis.tickInterval = normalizeTickInterval( axis.tickInterval, null, getMagnitude(axis.tickInterval), // If the tick interval is between 0.5 and 5 and the axis max is in the order of // thousands, chances are we are dealing with years. Don't allow decimals. #3363. pick(options.allowDecimals, !(axis.tickInterval > 0.5 && axis.tickInterval < 5 && axis.max > 1000 && axis.max < 9999)), !!this.tickAmount ); } // Prevent ticks from getting so close that we can't draw the labels if (!this.tickAmount && this.len) { // Color axis with disabled legend has no length axis.tickInterval = axis.unsquish(); } this.setTickPositions(); }, /** * Now we have computed the normalized tickInterval, get the tick positions */ setTickPositions: function () { var options = this.options, tickPositions, tickPositionsOption = options.tickPositions, tickPositioner = options.tickPositioner, startOnTick = options.startOnTick, endOnTick = options.endOnTick, single; // Set the tickmarkOffset this.tickmarkOffset = (this.categories && options.tickmarkPlacement === 'between' && this.tickInterval === 1) ? 0.5 : 0; // #3202 // get minorTickInterval this.minorTickInterval = options.minorTickInterval === 'auto' && this.tickInterval ? this.tickInterval / 5 : options.minorTickInterval; // Find the tick positions this.tickPositions = tickPositions = tickPositionsOption && tickPositionsOption.slice(); // Work on a copy (#1565) if (!tickPositions) { if (this.isDatetimeAxis) { tickPositions = this.getTimeTicks( this.normalizeTimeTickInterval(this.tickInterval, options.units), this.min, this.max, options.startOfWeek, this.ordinalPositions, this.closestPointRange, true ); } else if (this.isLog) { tickPositions = this.getLogTickPositions(this.tickInterval, this.min, this.max); } else { tickPositions = this.getLinearTickPositions(this.tickInterval, this.min, this.max); } // Too dense ticks, keep only the first and last (#4477) if (tickPositions.length > this.len) { tickPositions = [tickPositions[0], tickPositions.pop()]; } this.tickPositions = tickPositions; // Run the tick positioner callback, that allows modifying auto tick positions. if (tickPositioner) { tickPositioner = tickPositioner.apply(this, [this.min, this.max]); if (tickPositioner) { this.tickPositions = tickPositions = tickPositioner; } } } if (!this.isLinked) { // reset min/max or remove extremes based on start/end on tick this.trimTicks(tickPositions, startOnTick, endOnTick); // When there is only one point, or all points have the same value on this axis, then min // and max are equal and tickPositions.length is 0 or 1. In this case, add some padding // in order to center the point, but leave it with one tick. #1337. if (this.min === this.max && defined(this.min) && !this.tickAmount) { // Substract half a unit (#2619, #2846, #2515, #3390) single = true; this.min -= 0.5; this.max += 0.5; } this.single = single; if (!tickPositionsOption && !tickPositioner) { this.adjustTickAmount(); } } }, /** * Handle startOnTick and endOnTick by either adapting to padding min/max or rounded min/max */ trimTicks: function (tickPositions, startOnTick, endOnTick) { var roundedMin = tickPositions[0], roundedMax = tickPositions[tickPositions.length - 1], minPointOffset = this.minPointOffset || 0; if (startOnTick) { this.min = roundedMin; } else { while (this.min - minPointOffset > tickPositions[0]) { tickPositions.shift(); } } if (endOnTick) { this.max = roundedMax; } else { while (this.max + minPointOffset < tickPositions[tickPositions.length - 1]) { tickPositions.pop(); } } // If no tick are left, set one tick in the middle (#3195) if (tickPositions.length === 0 && defined(roundedMin)) { tickPositions.push((roundedMax + roundedMin) / 2); } }, /** * Check if there are multiple axes in the same pane * @returns {Boolean} There are other axes */ alignToOthers: function () { var others = {}, // Whether there is another axis to pair with this one hasOther, options = this.options; if (this.chart.options.chart.alignTicks !== false && options.alignTicks !== false) { each(this.chart[this.coll], function (axis) { var otherOptions = axis.options, horiz = axis.horiz, key = [ horiz ? otherOptions.left : otherOptions.top, otherOptions.width, otherOptions.height, otherOptions.pane ].join(','); if (axis.series.length) { // #4442 if (others[key]) { hasOther = true; // #4201 } else { others[key] = 1; } } }); } return hasOther; }, /** * Set the max ticks of either the x and y axis collection */ getTickAmount: function () { var options = this.options, tickAmount = options.tickAmount, tickPixelInterval = options.tickPixelInterval; if (!defined(options.tickInterval) && this.len < tickPixelInterval && !this.isRadial && !this.isLog && options.startOnTick && options.endOnTick) { tickAmount = 2; } if (!tickAmount && this.alignToOthers()) { // Add 1 because 4 tick intervals require 5 ticks (including first and last) tickAmount = mathCeil(this.len / tickPixelInterval) + 1; } // For tick amounts of 2 and 3, compute five ticks and remove the intermediate ones. This // prevents the axis from adding ticks that are too far away from the data extremes. if (tickAmount < 4) { this.finalTickAmt = tickAmount; tickAmount = 5; } this.tickAmount = tickAmount; }, /** * When using multiple axes, adjust the number of ticks to match the highest * number of ticks in that group */ adjustTickAmount: function () { var tickInterval = this.tickInterval, tickPositions = this.tickPositions, tickAmount = this.tickAmount, finalTickAmt = this.finalTickAmt, currentTickAmount = tickPositions && tickPositions.length, i, len; if (currentTickAmount < tickAmount) { while (tickPositions.length < tickAmount) { tickPositions.push(correctFloat( tickPositions[tickPositions.length - 1] + tickInterval )); } this.transA *= (currentTickAmount - 1) / (tickAmount - 1); this.max = tickPositions[tickPositions.length - 1]; // We have too many ticks, run second pass to try to reduce ticks } else if (currentTickAmount > tickAmount) { this.tickInterval *= 2; this.setTickPositions(); } // The finalTickAmt property is set in getTickAmount if (defined(finalTickAmt)) { i = len = tickPositions.length; while (i--) { if ( (finalTickAmt === 3 && i % 2 === 1) || // Remove every other tick (finalTickAmt <= 2 && i > 0 && i < len - 1) // Remove all but first and last ) { tickPositions.splice(i, 1); } } this.finalTickAmt = UNDEFINED; } }, /** * Set the scale based on data min and max, user set min and max or options * */ setScale: function () { var axis = this, isDirtyData, isDirtyAxisLength; axis.oldMin = axis.min; axis.oldMax = axis.max; axis.oldAxisLength = axis.len; // set the new axisLength axis.setAxisSize(); //axisLength = horiz ? axisWidth : axisHeight; isDirtyAxisLength = axis.len !== axis.oldAxisLength; // is there new data? each(axis.series, function (series) { if (series.isDirtyData || series.isDirty || series.xAxis.isDirty) { // when x axis is dirty, we need new data extremes for y as well isDirtyData = true; } }); // do we really need to go through all this? if (isDirtyAxisLength || isDirtyData || axis.isLinked || axis.forceRedraw || axis.userMin !== axis.oldUserMin || axis.userMax !== axis.oldUserMax || axis.alignToOthers()) { if (axis.resetStacks) { axis.resetStacks(); } axis.forceRedraw = false; // get data extremes if needed axis.getSeriesExtremes(); // get fixed positions based on tickInterval axis.setTickInterval(); // record old values to decide whether a rescale is necessary later on (#540) axis.oldUserMin = axis.userMin; axis.oldUserMax = axis.userMax; // Mark as dirty if it is not already set to dirty and extremes have changed. #595. if (!axis.isDirty) { axis.isDirty = isDirtyAxisLength || axis.min !== axis.oldMin || axis.max !== axis.oldMax; } } else if (axis.cleanStacks) { axis.cleanStacks(); } }, /** * Set the extremes and optionally redraw * @param {Number} newMin * @param {Number} newMax * @param {Boolean} redraw * @param {Boolean|Object} animation Whether to apply animation, and optionally animation * configuration * @param {Object} eventArguments * */ setExtremes: function (newMin, newMax, redraw, animation, eventArguments) { var axis = this, chart = axis.chart; redraw = pick(redraw, true); // defaults to true each(axis.series, function (serie) { delete serie.kdTree; }); // Extend the arguments with min and max eventArguments = extend(eventArguments, { min: newMin, max: newMax }); // Fire the event fireEvent(axis, 'setExtremes', eventArguments, function () { // the default event handler axis.userMin = newMin; axis.userMax = newMax; axis.eventArgs = eventArguments; if (redraw) { chart.redraw(animation); } }); }, /** * Overridable method for zooming chart. Pulled out in a separate method to allow overriding * in stock charts. */ zoom: function (newMin, newMax) { var dataMin = this.dataMin, dataMax = this.dataMax, options = this.options, min = mathMin(dataMin, pick(options.min, dataMin)), max = mathMax(dataMax, pick(options.max, dataMax)); // Prevent pinch zooming out of range. Check for defined is for #1946. #1734. if (!this.allowZoomOutside) { if (defined(dataMin) && newMin <= min) { newMin = min; } if (defined(dataMax) && newMax >= max) { newMax = max; } } // In full view, displaying the reset zoom button is not required this.displayBtn = newMin !== UNDEFINED || newMax !== UNDEFINED; // Do it this.setExtremes( newMin, newMax, false, UNDEFINED, { trigger: 'zoom' } ); return true; }, /** * Update the axis metrics */ setAxisSize: function () { var chart = this.chart, options = this.options, offsetLeft = options.offsetLeft || 0, offsetRight = options.offsetRight || 0, horiz = this.horiz, width = pick(options.width, chart.plotWidth - offsetLeft + offsetRight), height = pick(options.height, chart.plotHeight), top = pick(options.top, chart.plotTop), left = pick(options.left, chart.plotLeft + offsetLeft), percentRegex = /%$/; // Check for percentage based input values. Rounding fixes problems with // column overflow and plot line filtering (#4898, #4899) if (percentRegex.test(height)) { height = Math.round(parseFloat(height) / 100 * chart.plotHeight); } if (percentRegex.test(top)) { top = Math.round(parseFloat(top) / 100 * chart.plotHeight + chart.plotTop); } // Expose basic values to use in Series object and navigator this.left = left; this.top = top; this.width = width; this.height = height; this.bottom = chart.chartHeight - height - top; this.right = chart.chartWidth - width - left; // Direction agnostic properties this.len = mathMax(horiz ? width : height, 0); // mathMax fixes #905 this.pos = horiz ? left : top; // distance from SVG origin }, /** * Get the actual axis extremes */ getExtremes: function () { var axis = this, isLog = axis.isLog; return { min: isLog ? correctFloat(lin2log(axis.min)) : axis.min, max: isLog ? correctFloat(lin2log(axis.max)) : axis.max, dataMin: axis.dataMin, dataMax: axis.dataMax, userMin: axis.userMin, userMax: axis.userMax }; }, /** * Get the zero plane either based on zero or on the min or max value. * Used in bar and area plots */ getThreshold: function (threshold) { var axis = this, isLog = axis.isLog, realMin = isLog ? lin2log(axis.min) : axis.min, realMax = isLog ? lin2log(axis.max) : axis.max; // With a threshold of null, make the columns/areas rise from the top or bottom // depending on the value, assuming an actual threshold of 0 (#4233). if (threshold === null) { threshold = realMax < 0 ? realMax : realMin; } else if (realMin > threshold) { threshold = realMin; } else if (realMax < threshold) { threshold = realMax; } return axis.translate(threshold, 0, 1, 0, 1); }, /** * Compute auto alignment for the axis label based on which side the axis is on * and the given rotation for the label */ autoLabelAlign: function (rotation) { var ret, angle = (pick(rotation, 0) - (this.side * 90) + 720) % 360; if (angle > 15 && angle < 165) { ret = 'right'; } else if (angle > 195 && angle < 345) { ret = 'left'; } else { ret = 'center'; } return ret; }, /** * Prevent the ticks from getting so close we can't draw the labels. On a horizontal * axis, this is handled by rotating the labels, removing ticks and adding ellipsis. * On a vertical axis remove ticks and add ellipsis. */ unsquish: function () { var chart = this.chart, ticks = this.ticks, labelOptions = this.options.labels, horiz = this.horiz, tickInterval = this.tickInterval, newTickInterval = tickInterval, slotSize = this.len / (((this.categories ? 1 : 0) + this.max - this.min) / tickInterval), rotation, rotationOption = labelOptions.rotation, labelMetrics = chart.renderer.fontMetrics(labelOptions.style.fontSize, ticks[0] && ticks[0].label), step, bestScore = Number.MAX_VALUE, autoRotation, // Return the multiple of tickInterval that is needed to avoid collision getStep = function (spaceNeeded) { var step = spaceNeeded / (slotSize || 1); step = step > 1 ? mathCeil(step) : 1; return step * tickInterval; }; if (horiz) { autoRotation = !labelOptions.staggerLines && !labelOptions.step && ( // #3971 defined(rotationOption) ? [rotationOption] : slotSize < pick(labelOptions.autoRotationLimit, 80) && labelOptions.autoRotation ); if (autoRotation) { // Loop over the given autoRotation options, and determine which gives the best score. The // best score is that with the lowest number of steps and a rotation closest to horizontal. each(autoRotation, function (rot) { var score; if (rot === rotationOption || (rot && rot >= -90 && rot <= 90)) { // #3891 step = getStep(mathAbs(labelMetrics.h / mathSin(deg2rad * rot))); score = step + mathAbs(rot / 360); if (score < bestScore) { bestScore = score; rotation = rot; newTickInterval = step; } } }); } } else if (!labelOptions.step) { // #4411 newTickInterval = getStep(labelMetrics.h); } this.autoRotation = autoRotation; this.labelRotation = pick(rotation, rotationOption); return newTickInterval; }, renderUnsquish: function () { var chart = this.chart, renderer = chart.renderer, tickPositions = this.tickPositions, ticks = this.ticks, labelOptions = this.options.labels, horiz = this.horiz, margin = chart.margin, slotCount = this.categories ? tickPositions.length : tickPositions.length - 1, slotWidth = this.slotWidth = (horiz && (labelOptions.step || 0) < 2 && !labelOptions.rotation && // #4415 ((this.staggerLines || 1) * chart.plotWidth) / slotCount) || (!horiz && ((margin[3] && (margin[3] - chart.spacing[3])) || chart.chartWidth * 0.33)), // #1580, #1931, innerWidth = mathMax(1, mathRound(slotWidth - 2 * (labelOptions.padding || 5))), attr = {}, labelMetrics = renderer.fontMetrics(labelOptions.style.fontSize, ticks[0] && ticks[0].label), textOverflowOption = labelOptions.style.textOverflow, css, labelLength = 0, label, i, pos; // Set rotation option unless it is "auto", like in gauges if (!isString(labelOptions.rotation)) { attr.rotation = labelOptions.rotation || 0; // #4443 } // Handle auto rotation on horizontal axis if (this.autoRotation) { // Get the longest label length each(tickPositions, function (tick) { tick = ticks[tick]; if (tick && tick.labelLength > labelLength) { labelLength = tick.labelLength; } }); // Apply rotation only if the label is too wide for the slot, and // the label is wider than its height. if (labelLength > innerWidth && labelLength > labelMetrics.h) { attr.rotation = this.labelRotation; } else { this.labelRotation = 0; } // Handle word-wrap or ellipsis on vertical axis } else if (slotWidth) { // For word-wrap or ellipsis css = { width: innerWidth + PX }; if (!textOverflowOption) { css.textOverflow = 'clip'; // On vertical axis, only allow word wrap if there is room for more lines. i = tickPositions.length; while (!horiz && i--) { pos = tickPositions[i]; label = ticks[pos].label; if (label) { // Reset ellipsis in order to get the correct bounding box (#4070) if (label.styles.textOverflow === 'ellipsis') { label.css({ textOverflow: 'clip' }); } if (label.getBBox().height > this.len / tickPositions.length - (labelMetrics.h - labelMetrics.f) || ticks[pos].labelLength > slotWidth) { // #4678 label.specCss = { textOverflow: 'ellipsis' }; } } } } } // Add ellipsis if the label length is significantly longer than ideal if (attr.rotation) { css = { width: (labelLength > chart.chartHeight * 0.5 ? chart.chartHeight * 0.33 : chart.chartHeight) + PX }; if (!textOverflowOption) { css.textOverflow = 'ellipsis'; } } // Set the explicit or automatic label alignment this.labelAlign = labelOptions.align || this.autoLabelAlign(this.labelRotation); if (this.labelAlign) { attr.align = this.labelAlign; } // Apply general and specific CSS each(tickPositions, function (pos) { var tick = ticks[pos], label = tick && tick.label; if (label) { label.attr(attr); // This needs to go before the CSS in old IE (#4502) if (css) { label.css(merge(css, label.specCss)); } delete label.specCss; tick.rotation = attr.rotation; } }); // Note: Why is this not part of getLabelPosition? this.tickRotCorr = renderer.rotCorr(labelMetrics.b, this.labelRotation || 0, this.side !== 0); }, /** * Return true if the axis has associated data */ hasData: function () { return this.hasVisibleSeries || (defined(this.min) && defined(this.max) && !!this.tickPositions); }, /** * Render the tick labels to a preliminary position to get their sizes */ getOffset: function () { var axis = this, chart = axis.chart, renderer = chart.renderer, options = axis.options, tickPositions = axis.tickPositions, ticks = axis.ticks, horiz = axis.horiz, side = axis.side, invertedSide = chart.inverted ? [1, 0, 3, 2][side] : side, hasData, showAxis, titleOffset = 0, titleOffsetOption, titleMargin = 0, axisTitleOptions = options.title, labelOptions = options.labels, labelOffset = 0, // reset labelOffsetPadded, opposite = axis.opposite, axisOffset = chart.axisOffset, clipOffset = chart.clipOffset, clip, directionFactor = [-1, 1, 1, -1][side], n, axisParent = axis.axisParent, // Used in color axis lineHeightCorrection; // For reuse in Axis.render hasData = axis.hasData(); axis.showAxis = showAxis = hasData || pick(options.showEmpty, true); // Set/reset staggerLines axis.staggerLines = axis.horiz && labelOptions.staggerLines; // Create the axisGroup and gridGroup elements on first iteration if (!axis.axisGroup) { axis.gridGroup = renderer.g('grid') .attr({ zIndex: options.gridZIndex || 1 }) .add(axisParent); axis.axisGroup = renderer.g('axis') .attr({ zIndex: options.zIndex || 2 }) .add(axisParent); axis.labelGroup = renderer.g('axis-labels') .attr({ zIndex: labelOptions.zIndex || 7 }) .addClass(PREFIX + axis.coll.toLowerCase() + '-labels') .add(axisParent); } if (hasData || axis.isLinked) { // Generate ticks each(tickPositions, function (pos) { if (!ticks[pos]) { ticks[pos] = new Tick(axis, pos); } else { ticks[pos].addLabel(); // update labels depending on tick interval } }); axis.renderUnsquish(); // Left side must be align: right and right side must have align: left for labels if (labelOptions.reserveSpace !== false && (side === 0 || side === 2 || { 1: 'left', 3: 'right' }[side] === axis.labelAlign || axis.labelAlign === 'center')) { each(tickPositions, function (pos) { // get the highest offset labelOffset = mathMax( ticks[pos].getLabelSize(), labelOffset ); }); } if (axis.staggerLines) { labelOffset *= axis.staggerLines; axis.labelOffset = labelOffset * (axis.opposite ? -1 : 1); } } else { // doesn't have data for (n in ticks) { ticks[n].destroy(); delete ticks[n]; } } if (axisTitleOptions && axisTitleOptions.text && axisTitleOptions.enabled !== false) { if (!axis.axisTitle) { axis.axisTitle = renderer.text( axisTitleOptions.text, 0, 0, axisTitleOptions.useHTML ) .attr({ zIndex: 7, rotation: axisTitleOptions.rotation || 0, align: axisTitleOptions.textAlign || { low: opposite ? 'right' : 'left', middle: 'center', high: opposite ? 'left' : 'right' }[axisTitleOptions.align] }) .addClass(PREFIX + this.coll.toLowerCase() + '-title') .css(axisTitleOptions.style) .add(axis.axisGroup); axis.axisTitle.isNew = true; } if (showAxis) { titleOffset = axis.axisTitle.getBBox()[horiz ? 'height' : 'width']; titleOffsetOption = axisTitleOptions.offset; titleMargin = defined(titleOffsetOption) ? 0 : pick(axisTitleOptions.margin, horiz ? 5 : 10); } // hide or show the title depending on whether showEmpty is set axis.axisTitle[showAxis ? 'show' : 'hide'](true); } // handle automatic or user set offset axis.offset = directionFactor * pick(options.offset, axisOffset[side]); axis.tickRotCorr = axis.tickRotCorr || { x: 0, y: 0 }; // polar lineHeightCorrection = side === 2 ? axis.tickRotCorr.y : 0; labelOffsetPadded = Math.abs(labelOffset) + titleMargin + (labelOffset && (directionFactor * (horiz ? pick(labelOptions.y, axis.tickRotCorr.y + 8) : labelOptions.x) - lineHeightCorrection)); axis.axisTitleMargin = pick(titleOffsetOption, labelOffsetPadded); axisOffset[side] = mathMax( axisOffset[side], axis.axisTitleMargin + titleOffset + directionFactor * axis.offset, labelOffsetPadded // #3027 ); // Decide the clipping needed to keep the graph inside the plot area and axis lines clip = options.offset ? 0 : mathFloor(options.lineWidth / 2) * 2; // #4308, #4371 clipOffset[invertedSide] = mathMax(clipOffset[invertedSide], clip); }, /** * Get the path for the axis line */ getLinePath: function (lineWidth) { var chart = this.chart, opposite = this.opposite, offset = this.offset, horiz = this.horiz, lineLeft = this.left + (opposite ? this.width : 0) + offset, lineTop = chart.chartHeight - this.bottom - (opposite ? this.height : 0) + offset; if (opposite) { lineWidth *= -1; // crispify the other way - #1480, #1687 } return chart.renderer .crispLine([ M, horiz ? this.left : lineLeft, horiz ? lineTop : this.top, L, horiz ? chart.chartWidth - this.right : lineLeft, horiz ? lineTop : chart.chartHeight - this.bottom ], lineWidth); }, /** * Position the title */ getTitlePosition: function () { // compute anchor points for each of the title align options var horiz = this.horiz, axisLeft = this.left, axisTop = this.top, axisLength = this.len, axisTitleOptions = this.options.title, margin = horiz ? axisLeft : axisTop, opposite = this.opposite, offset = this.offset, xOption = axisTitleOptions.x || 0, yOption = axisTitleOptions.y || 0, fontSize = pInt(axisTitleOptions.style.fontSize || 12), // the position in the length direction of the axis alongAxis = { low: margin + (horiz ? 0 : axisLength), middle: margin + axisLength / 2, high: margin + (horiz ? axisLength : 0) }[axisTitleOptions.align], // the position in the perpendicular direction of the axis offAxis = (horiz ? axisTop + this.height : axisLeft) + (horiz ? 1 : -1) * // horizontal axis reverses the margin (opposite ? -1 : 1) * // so does opposite axes this.axisTitleMargin + (this.side === 2 ? fontSize : 0); return { x: horiz ? alongAxis + xOption : offAxis + (opposite ? this.width : 0) + offset + xOption, y: horiz ? offAxis + yOption - (opposite ? this.height : 0) + offset : alongAxis + yOption }; }, /** * Render the axis */ render: function () { var axis = this, chart = axis.chart, renderer = chart.renderer, options = axis.options, isLog = axis.isLog, isLinked = axis.isLinked, tickPositions = axis.tickPositions, axisTitle = axis.axisTitle, ticks = axis.ticks, minorTicks = axis.minorTicks, alternateBands = axis.alternateBands, stackLabelOptions = options.stackLabels, alternateGridColor = options.alternateGridColor, tickmarkOffset = axis.tickmarkOffset, lineWidth = options.lineWidth, linePath, hasRendered = chart.hasRendered, slideInTicks = hasRendered && defined(axis.oldMin) && !isNaN(axis.oldMin), showAxis = axis.showAxis, globalAnimation = renderer.globalAnimation, from, to; // Reset axis.labelEdge.length = 0; //axis.justifyToPlot = overflow === 'justify'; axis.overlap = false; // Mark all elements inActive before we go over and mark the active ones each([ticks, minorTicks, alternateBands], function (coll) { var pos; for (pos in coll) { coll[pos].isActive = false; } }); // If the series has data draw the ticks. Else only the line and title if (axis.hasData() || isLinked) { // minor ticks if (axis.minorTickInterval && !axis.categories) { each(axis.getMinorTickPositions(), function (pos) { if (!minorTicks[pos]) { minorTicks[pos] = new Tick(axis, pos, 'minor'); } // render new ticks in old position if (slideInTicks && minorTicks[pos].isNew) { minorTicks[pos].render(null, true); } minorTicks[pos].render(null, false, 1); }); } // Major ticks. Pull out the first item and render it last so that // we can get the position of the neighbour label. #808. if (tickPositions.length) { // #1300 each(tickPositions, function (pos, i) { // linked axes need an extra check to find out if if (!isLinked || (pos >= axis.min && pos <= axis.max)) { if (!ticks[pos]) { ticks[pos] = new Tick(axis, pos); } // render new ticks in old position if (slideInTicks && ticks[pos].isNew) { ticks[pos].render(i, true, 0.1); } ticks[pos].render(i); } }); // In a categorized axis, the tick marks are displayed between labels. So // we need to add a tick mark and grid line at the left edge of the X axis. if (tickmarkOffset && (axis.min === 0 || axis.single)) { if (!ticks[-1]) { ticks[-1] = new Tick(axis, -1, null, true); } ticks[-1].render(-1); } } // alternate grid color if (alternateGridColor) { each(tickPositions, function (pos, i) { to = tickPositions[i + 1] !== UNDEFINED ? tickPositions[i + 1] + tickmarkOffset : axis.max - tickmarkOffset; if (i % 2 === 0 && pos < axis.max && to <= axis.max + (chart.polar ? -tickmarkOffset : tickmarkOffset)) { // #2248, #4660 if (!alternateBands[pos]) { alternateBands[pos] = new Highcharts.PlotLineOrBand(axis); } from = pos + tickmarkOffset; // #949 alternateBands[pos].options = { from: isLog ? lin2log(from) : from, to: isLog ? lin2log(to) : to, color: alternateGridColor }; alternateBands[pos].render(); alternateBands[pos].isActive = true; } }); } // custom plot lines and bands if (!axis._addedPlotLB) { // only first time each((options.plotLines || []).concat(options.plotBands || []), function (plotLineOptions) { axis.addPlotBandOrLine(plotLineOptions); }); axis._addedPlotLB = true; } } // end if hasData // Remove inactive ticks each([ticks, minorTicks, alternateBands], function (coll) { var pos, i, forDestruction = [], delay = globalAnimation ? globalAnimation.duration || 500 : 0, destroyInactiveItems = function () { i = forDestruction.length; while (i--) { // When resizing rapidly, the same items may be destroyed in different timeouts, // or the may be reactivated if (coll[forDestruction[i]] && !coll[forDestruction[i]].isActive) { coll[forDestruction[i]].destroy(); delete coll[forDestruction[i]]; } } }; for (pos in coll) { if (!coll[pos].isActive) { // Render to zero opacity coll[pos].render(pos, false, 0); coll[pos].isActive = false; forDestruction.push(pos); } } // When the objects are finished fading out, destroy them syncTimeout( destroyInactiveItems, coll === alternateBands || !chart.hasRendered || !delay ? 0 : delay ); }); // Static items. As the axis group is cleared on subsequent calls // to render, these items are added outside the group. // axis line if (lineWidth) { linePath = axis.getLinePath(lineWidth); if (!axis.axisLine) { axis.axisLine = renderer.path(linePath) .attr({ stroke: options.lineColor, 'stroke-width': lineWidth, zIndex: 7 }) .add(axis.axisGroup); } else { axis.axisLine.animate({ d: linePath }); } // show or hide the line depending on options.showEmpty axis.axisLine[showAxis ? 'show' : 'hide'](true); } if (axisTitle && showAxis) { axisTitle[axisTitle.isNew ? 'attr' : 'animate']( axis.getTitlePosition() ); axisTitle.isNew = false; } // Stacked totals: if (stackLabelOptions && stackLabelOptions.enabled) { axis.renderStackTotals(); } // End stacked totals axis.isDirty = false; }, /** * Redraw the axis to reflect changes in the data or axis extremes */ redraw: function () { if (this.visible) { // render the axis this.render(); // move plot lines and bands each(this.plotLinesAndBands, function (plotLine) { plotLine.render(); }); } // mark associated series as dirty and ready for redraw each(this.series, function (series) { series.isDirty = true; }); }, /** * Destroys an Axis instance. */ destroy: function (keepEvents) { var axis = this, stacks = axis.stacks, stackKey, plotLinesAndBands = axis.plotLinesAndBands, i; // Remove the events if (!keepEvents) { removeEvent(axis); } // Destroy each stack total for (stackKey in stacks) { destroyObjectProperties(stacks[stackKey]); stacks[stackKey] = null; } // Destroy collections each([axis.ticks, axis.minorTicks, axis.alternateBands], function (coll) { destroyObjectProperties(coll); }); i = plotLinesAndBands.length; while (i--) { // #1975 plotLinesAndBands[i].destroy(); } // Destroy local variables each(['stackTotalGroup', 'axisLine', 'axisTitle', 'axisGroup', 'cross', 'gridGroup', 'labelGroup'], function (prop) { if (axis[prop]) { axis[prop] = axis[prop].destroy(); } }); // Destroy crosshair if (this.cross) { this.cross.destroy(); } }, /** * Draw the crosshair * * @param {Object} e The event arguments from the modified pointer event * @param {Object} point The Point object */ drawCrosshair: function (e, point) { var path, options = this.crosshair, pos, attribs, categorized, strokeWidth; if ( // Disabled in options !this.crosshair || // Snap ((defined(point) || !pick(options.snap, true)) === false) ) { this.hideCrosshair(); } else { // Get the path if (!pick(options.snap, true)) { pos = (this.horiz ? e.chartX - this.pos : this.len - e.chartY + this.pos); } else if (defined(point)) { pos = this.isXAxis ? point.plotX : this.len - point.plotY; // #3834 } if (this.isRadial) { path = this.getPlotLinePath(this.isXAxis ? point.x : pick(point.stackY, point.y)) || null; // #3189 } else { path = this.getPlotLinePath(null, null, null, null, pos) || null; // #3189 } if (path === null) { this.hideCrosshair(); return; } categorized = this.categories && !this.isRadial; strokeWidth = pick(options.width, (categorized ? this.transA : 1)); // Draw the cross if (this.cross) { this.cross .attr({ d: path, visibility: 'visible', 'stroke-width': strokeWidth // #4737 }); } else { attribs = { 'stroke-width': strokeWidth, stroke: options.color || (categorized ? 'rgba(155,200,255,0.2)' : '#C0C0C0'), zIndex: pick(options.zIndex, 2) }; if (options.dashStyle) { attribs.dashstyle = options.dashStyle; } this.cross = this.chart.renderer.path(path).attr(attribs).add(); } } }, /** * Hide the crosshair. */ hideCrosshair: function () { if (this.cross) { this.cross.hide(); } } }; // end Axis extend(Axis.prototype, AxisPlotLineOrBandExtension); /** * Methods defined on the Axis prototype */ /** * Set the tick positions of a logarithmic axis */ Axis.prototype.getLogTickPositions = function (interval, min, max, minor) { var axis = this, options = axis.options, axisLength = axis.len, // Since we use this method for both major and minor ticks, // use a local variable and return the result positions = []; // Reset if (!minor) { axis._minorAutoInterval = null; } // First case: All ticks fall on whole logarithms: 1, 10, 100 etc. if (interval >= 0.5) { interval = mathRound(interval); positions = axis.getLinearTickPositions(interval, min, max); // Second case: We need intermediary ticks. For example // 1, 2, 4, 6, 8, 10, 20, 40 etc. } else if (interval >= 0.08) { var roundedMin = mathFloor(min), intermediate, i, j, len, pos, lastPos, break2; if (interval > 0.3) { intermediate = [1, 2, 4]; } else if (interval > 0.15) { // 0.2 equals five minor ticks per 1, 10, 100 etc intermediate = [1, 2, 4, 6, 8]; } else { // 0.1 equals ten minor ticks per 1, 10, 100 etc intermediate = [1, 2, 3, 4, 5, 6, 7, 8, 9]; } for (i = roundedMin; i < max + 1 && !break2; i++) { len = intermediate.length; for (j = 0; j < len && !break2; j++) { pos = log2lin(lin2log(i) * intermediate[j]); if (pos > min && (!minor || lastPos <= max) && lastPos !== UNDEFINED) { // #1670, lastPos is #3113 positions.push(lastPos); } if (lastPos > max) { break2 = true; } lastPos = pos; } } // Third case: We are so deep in between whole logarithmic values that // we might as well handle the tick positions like a linear axis. For // example 1.01, 1.02, 1.03, 1.04. } else { var realMin = lin2log(min), realMax = lin2log(max), tickIntervalOption = options[minor ? 'minorTickInterval' : 'tickInterval'], filteredTickIntervalOption = tickIntervalOption === 'auto' ? null : tickIntervalOption, tickPixelIntervalOption = options.tickPixelInterval / (minor ? 5 : 1), totalPixelLength = minor ? axisLength / axis.tickPositions.length : axisLength; interval = pick( filteredTickIntervalOption, axis._minorAutoInterval, (realMax - realMin) * tickPixelIntervalOption / (totalPixelLength || 1) ); interval = normalizeTickInterval( interval, null, getMagnitude(interval) ); positions = map(axis.getLinearTickPositions( interval, realMin, realMax ), log2lin); if (!minor) { axis._minorAutoInterval = interval / 5; } } // Set the axis-level tickInterval variable if (!minor) { axis.tickInterval = interval; } return positions; };/** * The tooltip object * @param {Object} chart The chart instance * @param {Object} options Tooltip options */ var Tooltip = Highcharts.Tooltip = function () { this.init.apply(this, arguments); }; Tooltip.prototype = { init: function (chart, options) { var borderWidth = options.borderWidth, style = options.style, padding = pInt(style.padding); // Save the chart and options this.chart = chart; this.options = options; // Keep track of the current series //this.currentSeries = UNDEFINED; // List of crosshairs this.crosshairs = []; // Current values of x and y when animating this.now = { x: 0, y: 0 }; // The tooltip is initially hidden this.isHidden = true; // create the label this.label = chart.renderer.label('', 0, 0, options.shape || 'callout', null, null, options.useHTML, null, 'tooltip') .attr({ padding: padding, fill: options.backgroundColor, 'stroke-width': borderWidth, r: options.borderRadius, zIndex: 8 }) .css(style) .css({ padding: 0 }) // Remove it from VML, the padding is applied as an attribute instead (#1117) .add() .attr({ y: -9999 }); // #2301, #2657 // When using canVG the shadow shows up as a gray circle // even if the tooltip is hidden. if (!useCanVG) { this.label.shadow(options.shadow); } // Public property for getting the shared state. this.shared = options.shared; }, /** * Destroy the tooltip and its elements. */ destroy: function () { // Destroy and clear local variables if (this.label) { this.label = this.label.destroy(); } clearTimeout(this.hideTimer); clearTimeout(this.tooltipTimeout); }, /** * Provide a soft movement for the tooltip * * @param {Number} x * @param {Number} y * @private */ move: function (x, y, anchorX, anchorY) { var tooltip = this, now = tooltip.now, animate = tooltip.options.animation !== false && !tooltip.isHidden && // When we get close to the target position, abort animation and land on the right place (#3056) (mathAbs(x - now.x) > 1 || mathAbs(y - now.y) > 1), skipAnchor = tooltip.followPointer || tooltip.len > 1; // Get intermediate values for animation extend(now, { x: animate ? (2 * now.x + x) / 3 : x, y: animate ? (now.y + y) / 2 : y, anchorX: skipAnchor ? UNDEFINED : animate ? (2 * now.anchorX + anchorX) / 3 : anchorX, anchorY: skipAnchor ? UNDEFINED : animate ? (now.anchorY + anchorY) / 2 : anchorY }); // Move to the intermediate value tooltip.label.attr(now); // Run on next tick of the mouse tracker if (animate) { // Never allow two timeouts clearTimeout(this.tooltipTimeout); // Set the fixed interval ticking for the smooth tooltip this.tooltipTimeout = setTimeout(function () { // The interval function may still be running during destroy, so check that the chart is really there before calling. if (tooltip) { tooltip.move(x, y, anchorX, anchorY); } }, 32); } }, /** * Hide the tooltip */ hide: function (delay) { var tooltip = this; clearTimeout(this.hideTimer); // disallow duplicate timers (#1728, #1766) delay = pick(delay, this.options.hideDelay, 500); if (!this.isHidden) { this.hideTimer = syncTimeout(function () { tooltip.label[delay ? 'fadeOut' : 'hide'](); tooltip.isHidden = true; }, delay); } }, /** * Extendable method to get the anchor position of the tooltip * from a point or set of points */ getAnchor: function (points, mouseEvent) { var ret, chart = this.chart, inverted = chart.inverted, plotTop = chart.plotTop, plotLeft = chart.plotLeft, plotX = 0, plotY = 0, yAxis, xAxis; points = splat(points); // Pie uses a special tooltipPos ret = points[0].tooltipPos; // When tooltip follows mouse, relate the position to the mouse if (this.followPointer && mouseEvent) { if (mouseEvent.chartX === UNDEFINED) { mouseEvent = chart.pointer.normalize(mouseEvent); } ret = [ mouseEvent.chartX - chart.plotLeft, mouseEvent.chartY - plotTop ]; } // When shared, use the average position if (!ret) { each(points, function (point) { yAxis = point.series.yAxis; xAxis = point.series.xAxis; plotX += point.plotX + (!inverted && xAxis ? xAxis.left - plotLeft : 0); plotY += (point.plotLow ? (point.plotLow + point.plotHigh) / 2 : point.plotY) + (!inverted && yAxis ? yAxis.top - plotTop : 0); // #1151 }); plotX /= points.length; plotY /= points.length; ret = [ inverted ? chart.plotWidth - plotY : plotX, this.shared && !inverted && points.length > 1 && mouseEvent ? mouseEvent.chartY - plotTop : // place shared tooltip next to the mouse (#424) inverted ? chart.plotHeight - plotX : plotY ]; } return map(ret, mathRound); }, /** * Place the tooltip in a chart without spilling over * and not covering the point it self. */ getPosition: function (boxWidth, boxHeight, point) { var chart = this.chart, distance = this.distance, ret = {}, h = point.h || 0, // #4117 swapped, first = ['y', chart.chartHeight, boxHeight, point.plotY + chart.plotTop, chart.plotTop, chart.plotTop + chart.plotHeight], second = ['x', chart.chartWidth, boxWidth, point.plotX + chart.plotLeft, chart.plotLeft, chart.plotLeft + chart.plotWidth], // The far side is right or bottom preferFarSide = pick(point.ttBelow, (chart.inverted && !point.negative) || (!chart.inverted && point.negative)), /** * Handle the preferred dimension. When the preferred dimension is tooltip * on top or bottom of the point, it will look for space there. */ firstDimension = function (dim, outerSize, innerSize, point, min, max) { var roomLeft = innerSize < point - distance, roomRight = point + distance + innerSize < outerSize, alignedLeft = point - distance - innerSize, alignedRight = point + distance; if (preferFarSide && roomRight) { ret[dim] = alignedRight; } else if (!preferFarSide && roomLeft) { ret[dim] = alignedLeft; } else if (roomLeft) { ret[dim] = mathMin(max - innerSize, alignedLeft - h < 0 ? alignedLeft : alignedLeft - h); } else if (roomRight) { ret[dim] = mathMax(min, alignedRight + h + innerSize > outerSize ? alignedRight : alignedRight + h); } else { return false; } }, /** * Handle the secondary dimension. If the preferred dimension is tooltip * on top or bottom of the point, the second dimension is to align the tooltip * above the point, trying to align center but allowing left or right * align within the chart box. */ secondDimension = function (dim, outerSize, innerSize, point) { var retVal; // Too close to the edge, return false and swap dimensions if (point < distance || point > outerSize - distance) { retVal = false; // Align left/top } else if (point < innerSize / 2) { ret[dim] = 1; // Align right/bottom } else if (point > outerSize - innerSize / 2) { ret[dim] = outerSize - innerSize - 2; // Align center } else { ret[dim] = point - innerSize / 2; } return retVal; }, /** * Swap the dimensions */ swap = function (count) { var temp = first; first = second; second = temp; swapped = count; }, run = function () { if (firstDimension.apply(0, first) !== false) { if (secondDimension.apply(0, second) === false && !swapped) { swap(true); run(); } } else if (!swapped) { swap(true); run(); } else { ret.x = ret.y = 0; } }; // Under these conditions, prefer the tooltip on the side of the point if (chart.inverted || this.len > 1) { swap(); } run(); return ret; }, /** * In case no user defined formatter is given, this will be used. Note that the context * here is an object holding point, series, x, y etc. */ defaultFormatter: function (tooltip) { var items = this.points || splat(this), s; // build the header s = [tooltip.tooltipFooterHeaderFormatter(items[0])]; //#3397: abstraction to enable formatting of footer and header // build the values s = s.concat(tooltip.bodyFormatter(items)); // footer s.push(tooltip.tooltipFooterHeaderFormatter(items[0], true)); //#3397: abstraction to enable formatting of footer and header return s.join(''); }, /** * Refresh the tooltip's text and position. * @param {Object} point */ refresh: function (point, mouseEvent) { var tooltip = this, chart = tooltip.chart, label = tooltip.label, options = tooltip.options, x, y, anchor, textConfig = {}, text, pointConfig = [], formatter = options.formatter || tooltip.defaultFormatter, hoverPoints = chart.hoverPoints, borderColor, shared = tooltip.shared, currentSeries; clearTimeout(this.hideTimer); // get the reference point coordinates (pie charts use tooltipPos) tooltip.followPointer = splat(point)[0].series.tooltipOptions.followPointer; anchor = tooltip.getAnchor(point, mouseEvent); x = anchor[0]; y = anchor[1]; // shared tooltip, array is sent over if (shared && !(point.series && point.series.noSharedTooltip)) { // hide previous hoverPoints and set new chart.hoverPoints = point; if (hoverPoints) { each(hoverPoints, function (point) { point.setState(); }); } each(point, function (item) { item.setState(HOVER_STATE); pointConfig.push(item.getLabelConfig()); }); textConfig = { x: point[0].category, y: point[0].y }; textConfig.points = pointConfig; this.len = pointConfig.length; point = point[0]; // single point tooltip } else { textConfig = point.getLabelConfig(); } text = formatter.call(textConfig, tooltip); // register the current series currentSeries = point.series; this.distance = pick(currentSeries.tooltipOptions.distance, 16); // update the inner HTML if (text === false) { this.hide(); } else { // show it if (tooltip.isHidden) { stop(label); label.attr('opacity', 1).show(); } // update text label.attr({ text: text }); // set the stroke color of the box borderColor = options.borderColor || point.color || currentSeries.color || '#606060'; label.attr({ stroke: borderColor }); tooltip.updatePosition({ plotX: x, plotY: y, negative: point.negative, ttBelow: point.ttBelow, h: anchor[2] || 0 }); this.isHidden = false; } fireEvent(chart, 'tooltipRefresh', { text: text, x: x + chart.plotLeft, y: y + chart.plotTop, borderColor: borderColor }); }, /** * Find the new position and perform the move */ updatePosition: function (point) { var chart = this.chart, label = this.label, pos = (this.options.positioner || this.getPosition).call( this, label.width, label.height, point ); // do the move this.move( mathRound(pos.x), mathRound(pos.y || 0), // can be undefined (#3977) point.plotX + chart.plotLeft, point.plotY + chart.plotTop ); }, /** * Get the best X date format based on the closest point range on the axis. */ getXDateFormat: function (point, options, xAxis) { var xDateFormat, dateTimeLabelFormats = options.dateTimeLabelFormats, closestPointRange = xAxis && xAxis.closestPointRange, n, blank = '01-01 00:00:00.000', strpos = { millisecond: 15, second: 12, minute: 9, hour: 6, day: 3 }, date, lastN = 'millisecond'; // for sub-millisecond data, #4223 if (closestPointRange) { date = dateFormat('%m-%d %H:%M:%S.%L', point.x); for (n in timeUnits) { // If the range is exactly one week and we're looking at a Sunday/Monday, go for the week format if (closestPointRange === timeUnits.week && +dateFormat('%w', point.x) === xAxis.options.startOfWeek && date.substr(6) === blank.substr(6)) { n = 'week'; break; } // The first format that is too great for the range if (timeUnits[n] > closestPointRange) { n = lastN; break; } // If the point is placed every day at 23:59, we need to show // the minutes as well. #2637. if (strpos[n] && date.substr(strpos[n]) !== blank.substr(strpos[n])) { break; } // Weeks are outside the hierarchy, only apply them on Mondays/Sundays like in the first condition if (n !== 'week') { lastN = n; } } if (n) { xDateFormat = dateTimeLabelFormats[n]; } } else { xDateFormat = dateTimeLabelFormats.day; } return xDateFormat || dateTimeLabelFormats.year; // #2546, 2581 }, /** * Format the footer/header of the tooltip * #3397: abstraction to enable formatting of footer and header */ tooltipFooterHeaderFormatter: function (point, isFooter) { var footOrHead = isFooter ? 'footer' : 'header', series = point.series, tooltipOptions = series.tooltipOptions, xDateFormat = tooltipOptions.xDateFormat, xAxis = series.xAxis, isDateTime = xAxis && xAxis.options.type === 'datetime' && isNumber(point.key), formatString = tooltipOptions[footOrHead + 'Format']; // Guess the best date format based on the closest point distance (#568, #3418) if (isDateTime && !xDateFormat) { xDateFormat = this.getXDateFormat(point, tooltipOptions, xAxis); } // Insert the footer date format if any if (isDateTime && xDateFormat) { formatString = formatString.replace('{point.key}', '{point.key:' + xDateFormat + '}'); } return format(formatString, { point: point, series: series }); }, /** * Build the body (lines) of the tooltip by iterating over the items and returning one entry for each item, * abstracting this functionality allows to easily overwrite and extend it. */ bodyFormatter: function (items) { return map(items, function (item) { var tooltipOptions = item.series.tooltipOptions; return (tooltipOptions.pointFormatter || item.point.tooltipFormatter).call(item.point, tooltipOptions.pointFormat); }); } }; var hoverChartIndex; // Global flag for touch support hasTouch = doc && doc.documentElement.ontouchstart !== UNDEFINED; /** * The mouse tracker object. All methods starting with "on" are primary DOM event handlers. * Subsequent methods should be named differently from what they are doing. * @param {Object} chart The Chart instance * @param {Object} options The root options object */ var Pointer = Highcharts.Pointer = function (chart, options) { this.init(chart, options); }; Pointer.prototype = { /** * Initialize Pointer */ init: function (chart, options) { var chartOptions = options.chart, chartEvents = chartOptions.events, zoomType = useCanVG ? '' : chartOptions.zoomType, inverted = chart.inverted, zoomX, zoomY; // Store references this.options = options; this.chart = chart; // Zoom status this.zoomX = zoomX = /x/.test(zoomType); this.zoomY = zoomY = /y/.test(zoomType); this.zoomHor = (zoomX && !inverted) || (zoomY && inverted); this.zoomVert = (zoomY && !inverted) || (zoomX && inverted); this.hasZoom = zoomX || zoomY; // Do we need to handle click on a touch device? this.runChartClick = chartEvents && !!chartEvents.click; this.pinchDown = []; this.lastValidTouch = {}; if (Highcharts.Tooltip && options.tooltip.enabled) { chart.tooltip = new Tooltip(chart, options.tooltip); this.followTouchMove = pick(options.tooltip.followTouchMove, true); } this.setDOMEvents(); }, /** * Add crossbrowser support for chartX and chartY * @param {Object} e The event object in standard browsers */ normalize: function (e, chartPosition) { var chartX, chartY, ePos; // IE normalizing e = e || win.event; if (!e.target) { e.target = e.srcElement; } // iOS (#2757) ePos = e.touches ? (e.touches.length ? e.touches.item(0) : e.changedTouches[0]) : e; // Get mouse position if (!chartPosition) { this.chartPosition = chartPosition = offset(this.chart.container); } // chartX and chartY if (ePos.pageX === UNDEFINED) { // IE < 9. #886. chartX = mathMax(e.x, e.clientX - chartPosition.left); // #2005, #2129: the second case is // for IE10 quirks mode within framesets chartY = e.y; } else { chartX = ePos.pageX - chartPosition.left; chartY = ePos.pageY - chartPosition.top; } return extend(e, { chartX: mathRound(chartX), chartY: mathRound(chartY) }); }, /** * Get the click position in terms of axis values. * * @param {Object} e A pointer event */ getCoordinates: function (e) { var coordinates = { xAxis: [], yAxis: [] }; each(this.chart.axes, function (axis) { coordinates[axis.isXAxis ? 'xAxis' : 'yAxis'].push({ axis: axis, value: axis.toValue(e[axis.horiz ? 'chartX' : 'chartY']) }); }); return coordinates; }, /** * With line type charts with a single tracker, get the point closest to the mouse. * Run Point.onMouseOver and display tooltip for the point or points. */ runPointActions: function (e) { var pointer = this, chart = pointer.chart, series = chart.series, tooltip = chart.tooltip, shared = tooltip ? tooltip.shared : false, followPointer, hoverPoint = chart.hoverPoint, hoverSeries = chart.hoverSeries, i, distance = [Number.MAX_VALUE, Number.MAX_VALUE], // #4511 anchor, noSharedTooltip, stickToHoverSeries, directTouch, kdpoints = [], kdpoint = [], kdpointT; // For hovering over the empty parts of the plot area (hoverSeries is undefined). // If there is one series with point tracking (combo chart), don't go to nearest neighbour. if (!shared && !hoverSeries) { for (i = 0; i < series.length; i++) { if (series[i].directTouch || !series[i].options.stickyTracking) { series = []; } } } // If it has a hoverPoint and that series requires direct touch (like columns, #3899), or we're on // a noSharedTooltip series among shared tooltip series (#4546), use the hoverPoint . Otherwise, // search the k-d tree. stickToHoverSeries = hoverSeries && (shared ? hoverSeries.noSharedTooltip : hoverSeries.directTouch); if (stickToHoverSeries && hoverPoint) { kdpoint = [hoverPoint]; // Handle shared tooltip or cases where a series is not yet hovered } else { // Find nearest points on all series each(series, function (s) { // Skip hidden series noSharedTooltip = s.noSharedTooltip && shared; directTouch = !shared && s.directTouch; if (s.visible && !noSharedTooltip && !directTouch && pick(s.options.enableMouseTracking, true)) { // #3821 kdpointT = s.searchPoint(e, !noSharedTooltip && s.kdDimensions === 1); // #3828 if (kdpointT) { kdpoints.push(kdpointT); } } }); // Find absolute nearest point each(kdpoints, function (p) { if (p) { // Store both closest points, using point.dist and point.distX comparisons (#4645): each(['dist', 'distX'], function (dist, k) { if (typeof p[dist] === 'number' && p[dist] < distance[k]) { distance[k] = p[dist]; kdpoint[k] = p; } }); } }); } // Remove points with different x-positions, required for shared tooltip and crosshairs (#4645): if (shared) { i = kdpoints.length; while (i--) { if (kdpoints[i].clientX !== kdpoint[1].clientX || kdpoints[i].series.noSharedTooltip) { kdpoints.splice(i, 1); } } } // Refresh tooltip for kdpoint if new hover point or tooltip was hidden // #3926, #4200 if (kdpoint[0] && (kdpoint[0] !== this.prevKDPoint || (tooltip && tooltip.isHidden))) { // Draw tooltip if necessary if (shared && !kdpoint[0].series.noSharedTooltip) { if (kdpoints.length && tooltip) { tooltip.refresh(kdpoints, e); } // Do mouseover on all points (#3919, #3985, #4410) each(kdpoints, function (point) { point.onMouseOver(e, point !== ((hoverSeries && hoverSeries.directTouch && hoverPoint) || kdpoint[0])); }); this.prevKDPoint = kdpoint[1]; } else { if (tooltip) { tooltip.refresh(kdpoint[0], e); } if (!hoverSeries || !hoverSeries.directTouch) { // #4448 kdpoint[0].onMouseOver(e); } this.prevKDPoint = kdpoint[0]; } // Update positions (regardless of kdpoint or hoverPoint) } else { followPointer = hoverSeries && hoverSeries.tooltipOptions.followPointer; if (tooltip && followPointer && !tooltip.isHidden) { anchor = tooltip.getAnchor([{}], e); tooltip.updatePosition({ plotX: anchor[0], plotY: anchor[1] }); } } // Start the event listener to pick up the tooltip and crosshairs if (!pointer._onDocumentMouseMove) { pointer._onDocumentMouseMove = function (e) { if (charts[hoverChartIndex]) { charts[hoverChartIndex].pointer.onDocumentMouseMove(e); } }; addEvent(doc, 'mousemove', pointer._onDocumentMouseMove); } // Crosshair each(shared ? kdpoints : [pick(kdpoint[1], hoverPoint)], function (point) { var series = point && point.series; if (series) { each(['xAxis', 'yAxis', 'colorAxis'], function (coll) { if (series[coll]) { series[coll].drawCrosshair(e, point); } }); } }); }, /** * Reset the tracking by hiding the tooltip, the hover series state and the hover point * * @param allowMove {Boolean} Instead of destroying the tooltip altogether, allow moving it if possible */ reset: function (allowMove, delay) { var pointer = this, chart = pointer.chart, hoverSeries = chart.hoverSeries, hoverPoint = chart.hoverPoint, hoverPoints = chart.hoverPoints, tooltip = chart.tooltip, tooltipPoints = tooltip && tooltip.shared ? hoverPoints : hoverPoint; // Narrow in allowMove allowMove = allowMove && tooltip && tooltipPoints; // Check if the points have moved outside the plot area (#1003, #4736) if (allowMove) { each(splat(tooltipPoints), function (point) { if (point.plotX === undefined) { allowMove = false; } }); } // Just move the tooltip, #349 if (allowMove) { tooltip.refresh(tooltipPoints); if (hoverPoint) { // #2500 hoverPoint.setState(hoverPoint.state, true); each(chart.axes, function (axis) { if (pick(axis.options.crosshair && axis.options.crosshair.snap, true)) { axis.drawCrosshair(null, hoverPoint); } else { axis.hideCrosshair(); } }); } // Full reset } else { if (hoverPoint) { hoverPoint.onMouseOut(); } if (hoverPoints) { each(hoverPoints, function (point) { point.setState(); }); } if (hoverSeries) { hoverSeries.onMouseOut(); } if (tooltip) { tooltip.hide(delay); } if (pointer._onDocumentMouseMove) { removeEvent(doc, 'mousemove', pointer._onDocumentMouseMove); pointer._onDocumentMouseMove = null; } // Remove crosshairs each(chart.axes, function (axis) { axis.hideCrosshair(); }); pointer.hoverX = chart.hoverPoints = chart.hoverPoint = null; } }, /** * Scale series groups to a certain scale and translation */ scaleGroups: function (attribs, clip) { var chart = this.chart, seriesAttribs; // Scale each series each(chart.series, function (series) { seriesAttribs = attribs || series.getPlotBox(); // #1701 if (series.xAxis && series.xAxis.zoomEnabled) { series.group.attr(seriesAttribs); if (series.markerGroup) { series.markerGroup.attr(seriesAttribs); series.markerGroup.clip(clip ? chart.clipRect : null); } if (series.dataLabelsGroup) { series.dataLabelsGroup.attr(seriesAttribs); } } }); // Clip chart.clipRect.attr(clip || chart.clipBox); }, /** * Start a drag operation */ dragStart: function (e) { var chart = this.chart; // Record the start position chart.mouseIsDown = e.type; chart.cancelClick = false; chart.mouseDownX = this.mouseDownX = e.chartX; chart.mouseDownY = this.mouseDownY = e.chartY; }, /** * Perform a drag operation in response to a mousemove event while the mouse is down */ drag: function (e) { var chart = this.chart, chartOptions = chart.options.chart, chartX = e.chartX, chartY = e.chartY, zoomHor = this.zoomHor, zoomVert = this.zoomVert, plotLeft = chart.plotLeft, plotTop = chart.plotTop, plotWidth = chart.plotWidth, plotHeight = chart.plotHeight, clickedInside, size, selectionMarker = this.selectionMarker, mouseDownX = this.mouseDownX, mouseDownY = this.mouseDownY, panKey = chartOptions.panKey && e[chartOptions.panKey + 'Key']; // If the device supports both touch and mouse (like IE11), and we are touch-dragging // inside the plot area, don't handle the mouse event. #4339. if (selectionMarker && selectionMarker.touch) { return; } // If the mouse is outside the plot area, adjust to cooordinates // inside to prevent the selection marker from going outside if (chartX < plotLeft) { chartX = plotLeft; } else if (chartX > plotLeft + plotWidth) { chartX = plotLeft + plotWidth; } if (chartY < plotTop) { chartY = plotTop; } else if (chartY > plotTop + plotHeight) { chartY = plotTop + plotHeight; } // determine if the mouse has moved more than 10px this.hasDragged = Math.sqrt( Math.pow(mouseDownX - chartX, 2) + Math.pow(mouseDownY - chartY, 2) ); if (this.hasDragged > 10) { clickedInside = chart.isInsidePlot(mouseDownX - plotLeft, mouseDownY - plotTop); // make a selection if (chart.hasCartesianSeries && (this.zoomX || this.zoomY) && clickedInside && !panKey) { if (!selectionMarker) { this.selectionMarker = selectionMarker = chart.renderer.rect( plotLeft, plotTop, zoomHor ? 1 : plotWidth, zoomVert ? 1 : plotHeight, 0 ) .attr({ fill: chartOptions.selectionMarkerFill || 'rgba(69,114,167,0.25)', zIndex: 7 }) .add(); } } // adjust the width of the selection marker if (selectionMarker && zoomHor) { size = chartX - mouseDownX; selectionMarker.attr({ width: mathAbs(size), x: (size > 0 ? 0 : size) + mouseDownX }); } // adjust the height of the selection marker if (selectionMarker && zoomVert) { size = chartY - mouseDownY; selectionMarker.attr({ height: mathAbs(size), y: (size > 0 ? 0 : size) + mouseDownY }); } // panning if (clickedInside && !selectionMarker && chartOptions.panning) { chart.pan(e, chartOptions.panning); } } }, /** * On mouse up or touch end across the entire document, drop the selection. */ drop: function (e) { var pointer = this, chart = this.chart, hasPinched = this.hasPinched; if (this.selectionMarker) { var selectionData = { originalEvent: e, // #4890 xAxis: [], yAxis: [] }, selectionBox = this.selectionMarker, selectionLeft = selectionBox.attr ? selectionBox.attr('x') : selectionBox.x, selectionTop = selectionBox.attr ? selectionBox.attr('y') : selectionBox.y, selectionWidth = selectionBox.attr ? selectionBox.attr('width') : selectionBox.width, selectionHeight = selectionBox.attr ? selectionBox.attr('height') : selectionBox.height, runZoom; // a selection has been made if (this.hasDragged || hasPinched) { // record each axis' min and max each(chart.axes, function (axis) { if (axis.zoomEnabled && defined(axis.min) && (hasPinched || pointer[{ xAxis: 'zoomX', yAxis: 'zoomY' }[axis.coll]])) { // #859, #3569 var horiz = axis.horiz, minPixelPadding = e.type === 'touchend' ? axis.minPixelPadding : 0, // #1207, #3075 selectionMin = axis.toValue((horiz ? selectionLeft : selectionTop) + minPixelPadding), selectionMax = axis.toValue((horiz ? selectionLeft + selectionWidth : selectionTop + selectionHeight) - minPixelPadding); selectionData[axis.coll].push({ axis: axis, min: mathMin(selectionMin, selectionMax), // for reversed axes max: mathMax(selectionMin, selectionMax) }); runZoom = true; } }); if (runZoom) { fireEvent(chart, 'selection', selectionData, function (args) { chart.zoom(extend(args, hasPinched ? { animation: false } : null)); }); } } this.selectionMarker = this.selectionMarker.destroy(); // Reset scaling preview if (hasPinched) { this.scaleGroups(); } } // Reset all if (chart) { // it may be destroyed on mouse up - #877 css(chart.container, { cursor: chart._cursor }); chart.cancelClick = this.hasDragged > 10; // #370 chart.mouseIsDown = this.hasDragged = this.hasPinched = false; this.pinchDown = []; } }, onContainerMouseDown: function (e) { e = this.normalize(e); // issue #295, dragging not always working in Firefox if (e.preventDefault) { e.preventDefault(); } this.dragStart(e); }, onDocumentMouseUp: function (e) { if (charts[hoverChartIndex]) { charts[hoverChartIndex].pointer.drop(e); } }, /** * Special handler for mouse move that will hide the tooltip when the mouse leaves the plotarea. * Issue #149 workaround. The mouseleave event does not always fire. */ onDocumentMouseMove: function (e) { var chart = this.chart, chartPosition = this.chartPosition; e = this.normalize(e, chartPosition); // If we're outside, hide the tooltip if (chartPosition && !this.inClass(e.target, 'highcharts-tracker') && !chart.isInsidePlot(e.chartX - chart.plotLeft, e.chartY - chart.plotTop)) { this.reset(); } }, /** * When mouse leaves the container, hide the tooltip. */ onContainerMouseLeave: function (e) { var chart = charts[hoverChartIndex]; if (chart && (e.relatedTarget || e.toElement)) { // #4886, MS Touch end fires mouseleave but with no related target chart.pointer.reset(); chart.pointer.chartPosition = null; // also reset the chart position, used in #149 fix } }, // The mousemove, touchmove and touchstart event handler onContainerMouseMove: function (e) { var chart = this.chart; if (!defined(hoverChartIndex) || !charts[hoverChartIndex] || !charts[hoverChartIndex].mouseIsDown) { hoverChartIndex = chart.index; } e = this.normalize(e); e.returnValue = false; // #2251, #3224 if (chart.mouseIsDown === 'mousedown') { this.drag(e); } // Show the tooltip and run mouse over events (#977) if ((this.inClass(e.target, 'highcharts-tracker') || chart.isInsidePlot(e.chartX - chart.plotLeft, e.chartY - chart.plotTop)) && !chart.openMenu) { this.runPointActions(e); } }, /** * Utility to detect whether an element has, or has a parent with, a specific * class name. Used on detection of tracker objects and on deciding whether * hovering the tooltip should cause the active series to mouse out. */ inClass: function (element, className) { var elemClassName; while (element) { elemClassName = attr(element, 'class'); if (elemClassName) { if (elemClassName.indexOf(className) !== -1) { return true; } if (elemClassName.indexOf(PREFIX + 'container') !== -1) { return false; } } element = element.parentNode; } }, onTrackerMouseOut: function (e) { var series = this.chart.hoverSeries, relatedTarget = e.relatedTarget || e.toElement; if (series && relatedTarget && !series.options.stickyTracking && // #4886 !this.inClass(relatedTarget, PREFIX + 'tooltip') && !this.inClass(relatedTarget, PREFIX + 'series-' + series.index)) { // #2499, #4465 series.onMouseOut(); } }, onContainerClick: function (e) { var chart = this.chart, hoverPoint = chart.hoverPoint, plotLeft = chart.plotLeft, plotTop = chart.plotTop; e = this.normalize(e); if (!chart.cancelClick) { // On tracker click, fire the series and point events. #783, #1583 if (hoverPoint && this.inClass(e.target, PREFIX + 'tracker')) { // the series click event fireEvent(hoverPoint.series, 'click', extend(e, { point: hoverPoint })); // the point click event if (chart.hoverPoint) { // it may be destroyed (#1844) hoverPoint.firePointEvent('click', e); } // When clicking outside a tracker, fire a chart event } else { extend(e, this.getCoordinates(e)); // fire a click event in the chart if (chart.isInsidePlot(e.chartX - plotLeft, e.chartY - plotTop)) { fireEvent(chart, 'click', e); } } } }, /** * Set the JS DOM events on the container and document. This method should contain * a one-to-one assignment between methods and their handlers. Any advanced logic should * be moved to the handler reflecting the event's name. */ setDOMEvents: function () { var pointer = this, container = pointer.chart.container; container.onmousedown = function (e) { pointer.onContainerMouseDown(e); }; container.onmousemove = function (e) { pointer.onContainerMouseMove(e); }; container.onclick = function (e) { pointer.onContainerClick(e); }; addEvent(container, 'mouseleave', pointer.onContainerMouseLeave); if (chartCount === 1) { addEvent(doc, 'mouseup', pointer.onDocumentMouseUp); } if (hasTouch) { container.ontouchstart = function (e) { pointer.onContainerTouchStart(e); }; container.ontouchmove = function (e) { pointer.onContainerTouchMove(e); }; if (chartCount === 1) { addEvent(doc, 'touchend', pointer.onDocumentTouchEnd); } } }, /** * Destroys the Pointer object and disconnects DOM events. */ destroy: function () { var prop; removeEvent(this.chart.container, 'mouseleave', this.onContainerMouseLeave); if (!chartCount) { removeEvent(doc, 'mouseup', this.onDocumentMouseUp); removeEvent(doc, 'touchend', this.onDocumentTouchEnd); } // memory and CPU leak clearInterval(this.tooltipTimeout); for (prop in this) { this[prop] = null; } } }; /* Support for touch devices */ extend(Highcharts.Pointer.prototype, { /** * Run translation operations */ pinchTranslate: function (pinchDown, touches, transform, selectionMarker, clip, lastValidTouch) { if (this.zoomHor || this.pinchHor) { this.pinchTranslateDirection(true, pinchDown, touches, transform, selectionMarker, clip, lastValidTouch); } if (this.zoomVert || this.pinchVert) { this.pinchTranslateDirection(false, pinchDown, touches, transform, selectionMarker, clip, lastValidTouch); } }, /** * Run translation operations for each direction (horizontal and vertical) independently */ pinchTranslateDirection: function (horiz, pinchDown, touches, transform, selectionMarker, clip, lastValidTouch, forcedScale) { var chart = this.chart, xy = horiz ? 'x' : 'y', XY = horiz ? 'X' : 'Y', sChartXY = 'chart' + XY, wh = horiz ? 'width' : 'height', plotLeftTop = chart['plot' + (horiz ? 'Left' : 'Top')], selectionWH, selectionXY, clipXY, scale = forcedScale || 1, inverted = chart.inverted, bounds = chart.bounds[horiz ? 'h' : 'v'], singleTouch = pinchDown.length === 1, touch0Start = pinchDown[0][sChartXY], touch0Now = touches[0][sChartXY], touch1Start = !singleTouch && pinchDown[1][sChartXY], touch1Now = !singleTouch && touches[1][sChartXY], outOfBounds, transformScale, scaleKey, setScale = function () { if (!singleTouch && mathAbs(touch0Start - touch1Start) > 20) { // Don't zoom if fingers are too close on this axis scale = forcedScale || mathAbs(touch0Now - touch1Now) / mathAbs(touch0Start - touch1Start); } clipXY = ((plotLeftTop - touch0Now) / scale) + touch0Start; selectionWH = chart['plot' + (horiz ? 'Width' : 'Height')] / scale; }; // Set the scale, first pass setScale(); selectionXY = clipXY; // the clip position (x or y) is altered if out of bounds, the selection position is not // Out of bounds if (selectionXY < bounds.min) { selectionXY = bounds.min; outOfBounds = true; } else if (selectionXY + selectionWH > bounds.max) { selectionXY = bounds.max - selectionWH; outOfBounds = true; } // Is the chart dragged off its bounds, determined by dataMin and dataMax? if (outOfBounds) { // Modify the touchNow position in order to create an elastic drag movement. This indicates // to the user that the chart is responsive but can't be dragged further. touch0Now -= 0.8 * (touch0Now - lastValidTouch[xy][0]); if (!singleTouch) { touch1Now -= 0.8 * (touch1Now - lastValidTouch[xy][1]); } // Set the scale, second pass to adapt to the modified touchNow positions setScale(); } else { lastValidTouch[xy] = [touch0Now, touch1Now]; } // Set geometry for clipping, selection and transformation if (!inverted) { clip[xy] = clipXY - plotLeftTop; clip[wh] = selectionWH; } scaleKey = inverted ? (horiz ? 'scaleY' : 'scaleX') : 'scale' + XY; transformScale = inverted ? 1 / scale : scale; selectionMarker[wh] = selectionWH; selectionMarker[xy] = selectionXY; transform[scaleKey] = scale; transform['translate' + XY] = (transformScale * plotLeftTop) + (touch0Now - (transformScale * touch0Start)); }, /** * Handle touch events with two touches */ pinch: function (e) { var self = this, chart = self.chart, pinchDown = self.pinchDown, touches = e.touches, touchesLength = touches.length, lastValidTouch = self.lastValidTouch, hasZoom = self.hasZoom, selectionMarker = self.selectionMarker, transform = {}, fireClickEvent = touchesLength === 1 && ((self.inClass(e.target, PREFIX + 'tracker') && chart.runTrackerClick) || self.runChartClick), clip = {}; // Don't initiate panning until the user has pinched. This prevents us from // blocking page scrolling as users scroll down a long page (#4210). if (touchesLength > 1) { self.initiated = true; } // On touch devices, only proceed to trigger click if a handler is defined if (hasZoom && self.initiated && !fireClickEvent) { e.preventDefault(); } // Normalize each touch map(touches, function (e) { return self.normalize(e); }); // Register the touch start position if (e.type === 'touchstart') { each(touches, function (e, i) { pinchDown[i] = { chartX: e.chartX, chartY: e.chartY }; }); lastValidTouch.x = [pinchDown[0].chartX, pinchDown[1] && pinchDown[1].chartX]; lastValidTouch.y = [pinchDown[0].chartY, pinchDown[1] && pinchDown[1].chartY]; // Identify the data bounds in pixels each(chart.axes, function (axis) { if (axis.zoomEnabled) { var bounds = chart.bounds[axis.horiz ? 'h' : 'v'], minPixelPadding = axis.minPixelPadding, min = axis.toPixels(pick(axis.options.min, axis.dataMin)), max = axis.toPixels(pick(axis.options.max, axis.dataMax)), absMin = mathMin(min, max), absMax = mathMax(min, max); // Store the bounds for use in the touchmove handler bounds.min = mathMin(axis.pos, absMin - minPixelPadding); bounds.max = mathMax(axis.pos + axis.len, absMax + minPixelPadding); } }); self.res = true; // reset on next move // Event type is touchmove, handle panning and pinching } else if (pinchDown.length) { // can be 0 when releasing, if touchend fires first // Set the marker if (!selectionMarker) { self.selectionMarker = selectionMarker = extend({ destroy: noop, touch: true }, chart.plotBox); } self.pinchTranslate(pinchDown, touches, transform, selectionMarker, clip, lastValidTouch); self.hasPinched = hasZoom; // Scale and translate the groups to provide visual feedback during pinching self.scaleGroups(transform, clip); // Optionally move the tooltip on touchmove if (!hasZoom && self.followTouchMove && touchesLength === 1) { this.runPointActions(self.normalize(e)); } else if (self.res) { self.res = false; this.reset(false, 0); } } }, /** * General touch handler shared by touchstart and touchmove. */ touch: function (e, start) { var chart = this.chart; hoverChartIndex = chart.index; if (e.touches.length === 1) { e = this.normalize(e); if (chart.isInsidePlot(e.chartX - chart.plotLeft, e.chartY - chart.plotTop) && !chart.openMenu) { // Run mouse events and display tooltip etc if (start) { this.runPointActions(e); } this.pinch(e); } else if (start) { // Hide the tooltip on touching outside the plot area (#1203) this.reset(); } } else if (e.touches.length === 2) { this.pinch(e); } }, onContainerTouchStart: function (e) { this.touch(e, true); }, onContainerTouchMove: function (e) { this.touch(e); }, onDocumentTouchEnd: function (e) { if (charts[hoverChartIndex]) { charts[hoverChartIndex].pointer.drop(e); } } }); if (win.PointerEvent || win.MSPointerEvent) { // The touches object keeps track of the points being touched at all times var touches = {}, hasPointerEvent = !!win.PointerEvent, getWebkitTouches = function () { var key, fake = []; fake.item = function (i) { return this[i]; }; for (key in touches) { if (touches.hasOwnProperty(key)) { fake.push({ pageX: touches[key].pageX, pageY: touches[key].pageY, target: touches[key].target }); } } return fake; }, translateMSPointer = function (e, method, wktype, func) { var p; if ((e.pointerType === 'touch' || e.pointerType === e.MSPOINTER_TYPE_TOUCH) && charts[hoverChartIndex]) { func(e); p = charts[hoverChartIndex].pointer; p[method]({ type: wktype, target: e.currentTarget, preventDefault: noop, touches: getWebkitTouches() }); } }; /** * Extend the Pointer prototype with methods for each event handler and more */ extend(Pointer.prototype, { onContainerPointerDown: function (e) { translateMSPointer(e, 'onContainerTouchStart', 'touchstart', function (e) { touches[e.pointerId] = { pageX: e.pageX, pageY: e.pageY, target: e.currentTarget }; }); }, onContainerPointerMove: function (e) { translateMSPointer(e, 'onContainerTouchMove', 'touchmove', function (e) { touches[e.pointerId] = { pageX: e.pageX, pageY: e.pageY }; if (!touches[e.pointerId].target) { touches[e.pointerId].target = e.currentTarget; } }); }, onDocumentPointerUp: function (e) { translateMSPointer(e, 'onDocumentTouchEnd', 'touchend', function (e) { delete touches[e.pointerId]; }); }, /** * Add or remove the MS Pointer specific events */ batchMSEvents: function (fn) { fn(this.chart.container, hasPointerEvent ? 'pointerdown' : 'MSPointerDown', this.onContainerPointerDown); fn(this.chart.container, hasPointerEvent ? 'pointermove' : 'MSPointerMove', this.onContainerPointerMove); fn(doc, hasPointerEvent ? 'pointerup' : 'MSPointerUp', this.onDocumentPointerUp); } }); // Disable default IE actions for pinch and such on chart element wrap(Pointer.prototype, 'init', function (proceed, chart, options) { proceed.call(this, chart, options); if (this.hasZoom) { // #4014 css(chart.container, { '-ms-touch-action': NONE, 'touch-action': NONE }); } }); // Add IE specific touch events to chart wrap(Pointer.prototype, 'setDOMEvents', function (proceed) { proceed.apply(this); if (this.hasZoom || this.followTouchMove) { this.batchMSEvents(addEvent); } }); // Destroy MS events also wrap(Pointer.prototype, 'destroy', function (proceed) { this.batchMSEvents(removeEvent); proceed.call(this); }); } /** * The overview of the chart's series */ var Legend = Highcharts.Legend = function (chart, options) { this.init(chart, options); }; Legend.prototype = { /** * Initialize the legend */ init: function (chart, options) { var legend = this, itemStyle = options.itemStyle, padding, itemMarginTop = options.itemMarginTop || 0; this.options = options; if (!options.enabled) { return; } legend.itemStyle = itemStyle; legend.itemHiddenStyle = merge(itemStyle, options.itemHiddenStyle); legend.itemMarginTop = itemMarginTop; legend.padding = padding = pick(options.padding, 8); legend.initialItemX = padding; legend.initialItemY = padding - 5; // 5 is the number of pixels above the text legend.maxItemWidth = 0; legend.chart = chart; legend.itemHeight = 0; legend.symbolWidth = pick(options.symbolWidth, 16); legend.pages = []; // Render it legend.render(); // move checkboxes addEvent(legend.chart, 'endResize', function () { legend.positionCheckboxes(); }); }, /** * Set the colors for the legend item * @param {Object} item A Series or Point instance * @param {Object} visible Dimmed or colored */ colorizeItem: function (item, visible) { var legend = this, options = legend.options, legendItem = item.legendItem, legendLine = item.legendLine, legendSymbol = item.legendSymbol, hiddenColor = legend.itemHiddenStyle.color, textColor = visible ? options.itemStyle.color : hiddenColor, symbolColor = visible ? (item.legendColor || item.color || '#CCC') : hiddenColor, markerOptions = item.options && item.options.marker, symbolAttr = { fill: symbolColor }, key, val; if (legendItem) { legendItem.css({ fill: textColor, color: textColor }); // color for #1553, oldIE } if (legendLine) { legendLine.attr({ stroke: symbolColor }); } if (legendSymbol) { // Apply marker options if (markerOptions && legendSymbol.isMarker) { // #585 symbolAttr.stroke = symbolColor; markerOptions = item.convertAttribs(markerOptions); for (key in markerOptions) { val = markerOptions[key]; if (val !== UNDEFINED) { symbolAttr[key] = val; } } } legendSymbol.attr(symbolAttr); } }, /** * Position the legend item * @param {Object} item A Series or Point instance */ positionItem: function (item) { var legend = this, options = legend.options, symbolPadding = options.symbolPadding, ltr = !options.rtl, legendItemPos = item._legendItemPos, itemX = legendItemPos[0], itemY = legendItemPos[1], checkbox = item.checkbox, legendGroup = item.legendGroup; if (legendGroup && legendGroup.element) { legendGroup.translate( ltr ? itemX : legend.legendWidth - itemX - 2 * symbolPadding - 4, itemY ); } if (checkbox) { checkbox.x = itemX; checkbox.y = itemY; } }, /** * Destroy a single legend item * @param {Object} item The series or point */ destroyItem: function (item) { var checkbox = item.checkbox; // destroy SVG elements each(['legendItem', 'legendLine', 'legendSymbol', 'legendGroup'], function (key) { if (item[key]) { item[key] = item[key].destroy(); } }); if (checkbox) { discardElement(item.checkbox); } }, /** * Destroys the legend. */ destroy: function () { var legend = this, legendGroup = legend.group, box = legend.box; if (box) { legend.box = box.destroy(); } if (legendGroup) { legend.group = legendGroup.destroy(); } }, /** * Position the checkboxes after the width is determined */ positionCheckboxes: function (scrollOffset) { var alignAttr = this.group.alignAttr, translateY, clipHeight = this.clipHeight || this.legendHeight, titleHeight = this.titleHeight; if (alignAttr) { translateY = alignAttr.translateY; each(this.allItems, function (item) { var checkbox = item.checkbox, top; if (checkbox) { top = translateY + titleHeight + checkbox.y + (scrollOffset || 0) + 3; css(checkbox, { left: (alignAttr.translateX + item.checkboxOffset + checkbox.x - 20) + PX, top: top + PX, display: top > translateY - 6 && top < translateY + clipHeight - 6 ? '' : NONE }); } }); } }, /** * Render the legend title on top of the legend */ renderTitle: function () { var options = this.options, padding = this.padding, titleOptions = options.title, titleHeight = 0, bBox; if (titleOptions.text) { if (!this.title) { this.title = this.chart.renderer.label(titleOptions.text, padding - 3, padding - 4, null, null, null, null, null, 'legend-title') .attr({ zIndex: 1 }) .css(titleOptions.style) .add(this.group); } bBox = this.title.getBBox(); titleHeight = bBox.height; this.offsetWidth = bBox.width; // #1717 this.contentGroup.attr({ translateY: titleHeight }); } this.titleHeight = titleHeight; }, /** * Set the legend item text */ setText: function (item) { var options = this.options; item.legendItem.attr({ text: options.labelFormat ? format(options.labelFormat, item) : options.labelFormatter.call(item) }); }, /** * Render a single specific legend item * @param {Object} item A series or point */ renderItem: function (item) { var legend = this, chart = legend.chart, renderer = chart.renderer, options = legend.options, horizontal = options.layout === 'horizontal', symbolWidth = legend.symbolWidth, symbolPadding = options.symbolPadding, itemStyle = legend.itemStyle, itemHiddenStyle = legend.itemHiddenStyle, padding = legend.padding, itemDistance = horizontal ? pick(options.itemDistance, 20) : 0, ltr = !options.rtl, itemHeight, widthOption = options.width, itemMarginBottom = options.itemMarginBottom || 0, itemMarginTop = legend.itemMarginTop, initialItemX = legend.initialItemX, bBox, itemWidth, li = item.legendItem, series = item.series && item.series.drawLegendSymbol ? item.series : item, seriesOptions = series.options, showCheckbox = legend.createCheckboxForItem && seriesOptions && seriesOptions.showCheckbox, useHTML = options.useHTML; if (!li) { // generate it once, later move it // Generate the group box // A group to hold the symbol and text. Text is to be appended in Legend class. item.legendGroup = renderer.g('legend-item') .attr({ zIndex: 1 }) .add(legend.scrollGroup); // Generate the list item text and add it to the group item.legendItem = li = renderer.text( '', ltr ? symbolWidth + symbolPadding : -symbolPadding, legend.baseline || 0, useHTML ) .css(merge(item.visible ? itemStyle : itemHiddenStyle)) // merge to prevent modifying original (#1021) .attr({ align: ltr ? 'left' : 'right', zIndex: 2 }) .add(item.legendGroup); // Get the baseline for the first item - the font size is equal for all if (!legend.baseline) { legend.fontMetrics = renderer.fontMetrics(itemStyle.fontSize, li); legend.baseline = legend.fontMetrics.f + 3 + itemMarginTop; li.attr('y', legend.baseline); } // Draw the legend symbol inside the group box series.drawLegendSymbol(legend, item); if (legend.setItemEvents) { legend.setItemEvents(item, li, useHTML, itemStyle, itemHiddenStyle); } // add the HTML checkbox on top if (showCheckbox) { legend.createCheckboxForItem(item); } } // Colorize the items legend.colorizeItem(item, item.visible); // Always update the text legend.setText(item); // calculate the positions for the next line bBox = li.getBBox(); itemWidth = item.checkboxOffset = options.itemWidth || item.legendItemWidth || symbolWidth + symbolPadding + bBox.width + itemDistance + (showCheckbox ? 20 : 0); legend.itemHeight = itemHeight = mathRound(item.legendItemHeight || bBox.height); // if the item exceeds the width, start a new line if (horizontal && legend.itemX - initialItemX + itemWidth > (widthOption || (chart.chartWidth - 2 * padding - initialItemX - options.x))) { legend.itemX = initialItemX; legend.itemY += itemMarginTop + legend.lastLineHeight + itemMarginBottom; legend.lastLineHeight = 0; // reset for next line (#915, #3976) } // If the item exceeds the height, start a new column /*if (!horizontal && legend.itemY + options.y + itemHeight > chart.chartHeight - spacingTop - spacingBottom) { legend.itemY = legend.initialItemY; legend.itemX += legend.maxItemWidth; legend.maxItemWidth = 0; }*/ // Set the edge positions legend.maxItemWidth = mathMax(legend.maxItemWidth, itemWidth); legend.lastItemY = itemMarginTop + legend.itemY + itemMarginBottom; legend.lastLineHeight = mathMax(itemHeight, legend.lastLineHeight); // #915 // cache the position of the newly generated or reordered items item._legendItemPos = [legend.itemX, legend.itemY]; // advance if (horizontal) { legend.itemX += itemWidth; } else { legend.itemY += itemMarginTop + itemHeight + itemMarginBottom; legend.lastLineHeight = itemHeight; } // the width of the widest item legend.offsetWidth = widthOption || mathMax( (horizontal ? legend.itemX - initialItemX - itemDistance : itemWidth) + padding, legend.offsetWidth ); }, /** * Get all items, which is one item per series for normal series and one item per point * for pie series. */ getAllItems: function () { var allItems = []; each(this.chart.series, function (series) { var seriesOptions = series.options; // Handle showInLegend. If the series is linked to another series, defaults to false. if (!pick(seriesOptions.showInLegend, !defined(seriesOptions.linkedTo) ? UNDEFINED : false, true)) { return; } // use points or series for the legend item depending on legendType allItems = allItems.concat( series.legendItems || (seriesOptions.legendType === 'point' ? series.data : series) ); }); return allItems; }, /** * Adjust the chart margins by reserving space for the legend on only one side * of the chart. If the position is set to a corner, top or bottom is reserved * for horizontal legends and left or right for vertical ones. */ adjustMargins: function (margin, spacing) { var chart = this.chart, options = this.options, // Use the first letter of each alignment option in order to detect the side alignment = options.align.charAt(0) + options.verticalAlign.charAt(0) + options.layout.charAt(0); // #4189 - use charAt(x) notation instead of [x] for IE7 if (this.display && !options.floating) { each([ /(lth|ct|rth)/, /(rtv|rm|rbv)/, /(rbh|cb|lbh)/, /(lbv|lm|ltv)/ ], function (alignments, side) { if (alignments.test(alignment) && !defined(margin[side])) { // Now we have detected on which side of the chart we should reserve space for the legend chart[marginNames[side]] = mathMax( chart[marginNames[side]], chart.legend[(side + 1) % 2 ? 'legendHeight' : 'legendWidth'] + [1, -1, -1, 1][side] * options[(side % 2) ? 'x' : 'y'] + pick(options.margin, 12) + spacing[side] ); } }); } }, /** * Render the legend. This method can be called both before and after * chart.render. If called after, it will only rearrange items instead * of creating new ones. */ render: function () { var legend = this, chart = legend.chart, renderer = chart.renderer, legendGroup = legend.group, allItems, display, legendWidth, legendHeight, box = legend.box, options = legend.options, padding = legend.padding, legendBorderWidth = options.borderWidth, legendBackgroundColor = options.backgroundColor; legend.itemX = legend.initialItemX; legend.itemY = legend.initialItemY; legend.offsetWidth = 0; legend.lastItemY = 0; if (!legendGroup) { legend.group = legendGroup = renderer.g('legend') .attr({ zIndex: 7 }) .add(); legend.contentGroup = renderer.g() .attr({ zIndex: 1 }) // above background .add(legendGroup); legend.scrollGroup = renderer.g() .add(legend.contentGroup); } legend.renderTitle(); // add each series or point allItems = legend.getAllItems(); // sort by legendIndex stableSort(allItems, function (a, b) { return ((a.options && a.options.legendIndex) || 0) - ((b.options && b.options.legendIndex) || 0); }); // reversed legend if (options.reversed) { allItems.reverse(); } legend.allItems = allItems; legend.display = display = !!allItems.length; // render the items legend.lastLineHeight = 0; each(allItems, function (item) { legend.renderItem(item); }); // Get the box legendWidth = (options.width || legend.offsetWidth) + padding; legendHeight = legend.lastItemY + legend.lastLineHeight + legend.titleHeight; legendHeight = legend.handleOverflow(legendHeight); legendHeight += padding; // Draw the border and/or background if (legendBorderWidth || legendBackgroundColor) { if (!box) { legend.box = box = renderer.rect( 0, 0, legendWidth, legendHeight, options.borderRadius, legendBorderWidth || 0 ).attr({ stroke: options.borderColor, 'stroke-width': legendBorderWidth || 0, fill: legendBackgroundColor || NONE }) .add(legendGroup) .shadow(options.shadow); box.isNew = true; } else if (legendWidth > 0 && legendHeight > 0) { box[box.isNew ? 'attr' : 'animate']( box.crisp({ width: legendWidth, height: legendHeight }) ); box.isNew = false; } // hide the border if no items box[display ? 'show' : 'hide'](); } legend.legendWidth = legendWidth; legend.legendHeight = legendHeight; // Now that the legend width and height are established, put the items in the // final position each(allItems, function (item) { legend.positionItem(item); }); // 1.x compatibility: positioning based on style /*var props = ['left', 'right', 'top', 'bottom'], prop, i = 4; while (i--) { prop = props[i]; if (options.style[prop] && options.style[prop] !== 'auto') { options[i < 2 ? 'align' : 'verticalAlign'] = prop; options[i < 2 ? 'x' : 'y'] = pInt(options.style[prop]) * (i % 2 ? -1 : 1); } }*/ if (display) { legendGroup.align(extend({ width: legendWidth, height: legendHeight }, options), true, 'spacingBox'); } if (!chart.isResizing) { this.positionCheckboxes(); } }, /** * Set up the overflow handling by adding navigation with up and down arrows below the * legend. */ handleOverflow: function (legendHeight) { var legend = this, chart = this.chart, renderer = chart.renderer, options = this.options, optionsY = options.y, alignTop = options.verticalAlign === 'top', spaceHeight = chart.spacingBox.height + (alignTop ? -optionsY : optionsY) - this.padding, maxHeight = options.maxHeight, clipHeight, clipRect = this.clipRect, navOptions = options.navigation, animation = pick(navOptions.animation, true), arrowSize = navOptions.arrowSize || 12, nav = this.nav, pages = this.pages, padding = this.padding, lastY, allItems = this.allItems, clipToHeight = function (height) { clipRect.attr({ height: height }); // useHTML if (legend.contentGroup.div) { legend.contentGroup.div.style.clip = 'rect(' + padding + 'px,9999px,' + (padding + height) + 'px,0)'; } }; // Adjust the height if (options.layout === 'horizontal') { spaceHeight /= 2; } if (maxHeight) { spaceHeight = mathMin(spaceHeight, maxHeight); } // Reset the legend height and adjust the clipping rectangle pages.length = 0; if (legendHeight > spaceHeight) { this.clipHeight = clipHeight = mathMax(spaceHeight - 20 - this.titleHeight - padding, 0); this.currentPage = pick(this.currentPage, 1); this.fullHeight = legendHeight; // Fill pages with Y positions so that the top of each a legend item defines // the scroll top for each page (#2098) each(allItems, function (item, i) { var y = item._legendItemPos[1], h = mathRound(item.legendItem.getBBox().height), len = pages.length; if (!len || (y - pages[len - 1] > clipHeight && (lastY || y) !== pages[len - 1])) { pages.push(lastY || y); len++; } if (i === allItems.length - 1 && y + h - pages[len - 1] > clipHeight) { pages.push(y); } if (y !== lastY) { lastY = y; } }); // Only apply clipping if needed. Clipping causes blurred legend in PDF export (#1787) if (!clipRect) { clipRect = legend.clipRect = renderer.clipRect(0, padding, 9999, 0); legend.contentGroup.clip(clipRect); } clipToHeight(clipHeight); // Add navigation elements if (!nav) { this.nav = nav = renderer.g().attr({ zIndex: 1 }).add(this.group); this.up = renderer.symbol('triangle', 0, 0, arrowSize, arrowSize) .on('click', function () { legend.scroll(-1, animation); }) .add(nav); this.pager = renderer.text('', 15, 10) .css(navOptions.style) .add(nav); this.down = renderer.symbol('triangle-down', 0, 0, arrowSize, arrowSize) .on('click', function () { legend.scroll(1, animation); }) .add(nav); } // Set initial position legend.scroll(0); legendHeight = spaceHeight; } else if (nav) { clipToHeight(chart.chartHeight); nav.hide(); this.scrollGroup.attr({ translateY: 1 }); this.clipHeight = 0; // #1379 } return legendHeight; }, /** * Scroll the legend by a number of pages * @param {Object} scrollBy * @param {Object} animation */ scroll: function (scrollBy, animation) { var pages = this.pages, pageCount = pages.length, currentPage = this.currentPage + scrollBy, clipHeight = this.clipHeight, navOptions = this.options.navigation, activeColor = navOptions.activeColor, inactiveColor = navOptions.inactiveColor, pager = this.pager, padding = this.padding, scrollOffset; // When resizing while looking at the last page if (currentPage > pageCount) { currentPage = pageCount; } if (currentPage > 0) { if (animation !== UNDEFINED) { setAnimation(animation, this.chart); } this.nav.attr({ translateX: padding, translateY: clipHeight + this.padding + 7 + this.titleHeight, visibility: VISIBLE }); this.up.attr({ fill: currentPage === 1 ? inactiveColor : activeColor }) .css({ cursor: currentPage === 1 ? 'default' : 'pointer' }); pager.attr({ text: currentPage + '/' + pageCount }); this.down.attr({ x: 18 + this.pager.getBBox().width, // adjust to text width fill: currentPage === pageCount ? inactiveColor : activeColor }) .css({ cursor: currentPage === pageCount ? 'default' : 'pointer' }); scrollOffset = -pages[currentPage - 1] + this.initialItemY; this.scrollGroup.animate({ translateY: scrollOffset }); this.currentPage = currentPage; this.positionCheckboxes(scrollOffset); } } }; /* * LegendSymbolMixin */ var LegendSymbolMixin = Highcharts.LegendSymbolMixin = { /** * Get the series' symbol in the legend * * @param {Object} legend The legend object * @param {Object} item The series (this) or point */ drawRectangle: function (legend, item) { var symbolHeight = legend.options.symbolHeight || legend.fontMetrics.f; item.legendSymbol = this.chart.renderer.rect( 0, legend.baseline - symbolHeight + 1, // #3988 legend.symbolWidth, symbolHeight, legend.options.symbolRadius || 0 ).attr({ zIndex: 3 }).add(item.legendGroup); }, /** * Get the series' symbol in the legend. This method should be overridable to create custom * symbols through Highcharts.seriesTypes[type].prototype.drawLegendSymbols. * * @param {Object} legend The legend object */ drawLineMarker: function (legend) { var options = this.options, markerOptions = options.marker, radius, legendSymbol, symbolWidth = legend.symbolWidth, renderer = this.chart.renderer, legendItemGroup = this.legendGroup, verticalCenter = legend.baseline - mathRound(legend.fontMetrics.b * 0.3), attr; // Draw the line if (options.lineWidth) { attr = { 'stroke-width': options.lineWidth }; if (options.dashStyle) { attr.dashstyle = options.dashStyle; } this.legendLine = renderer.path([ M, 0, verticalCenter, L, symbolWidth, verticalCenter ]) .attr(attr) .add(legendItemGroup); } // Draw the marker if (markerOptions && markerOptions.enabled !== false) { radius = markerOptions.radius; this.legendSymbol = legendSymbol = renderer.symbol( this.symbol, (symbolWidth / 2) - radius, verticalCenter - radius, 2 * radius, 2 * radius, markerOptions ) .add(legendItemGroup); legendSymbol.isMarker = true; } } }; // Workaround for #2030, horizontal legend items not displaying in IE11 Preview, // and for #2580, a similar drawing flaw in Firefox 26. // Explore if there's a general cause for this. The problem may be related // to nested group elements, as the legend item texts are within 4 group elements. if (/Trident\/7\.0/.test(userAgent) || isFirefox) { wrap(Legend.prototype, 'positionItem', function (proceed, item) { var legend = this, runPositionItem = function () { // If chart destroyed in sync, this is undefined (#2030) if (item._legendItemPos) { proceed.call(legend, item); } }; // Do it now, for export and to get checkbox placement runPositionItem(); // Do it after to work around the core issue setTimeout(runPositionItem); }); } /** * The Chart class * @param {String|Object} renderTo The DOM element to render to, or its id * @param {Object} options * @param {Function} callback Function to run when the chart has loaded */ var Chart = Highcharts.Chart = function () { this.getArgs.apply(this, arguments); }; Highcharts.chart = function (a, b, c) { return new Chart(a, b, c); }; Chart.prototype = { /** * Hook for modules */ callbacks: [], /** * Handle the arguments passed to the constructor * @returns {Array} Arguments without renderTo */ getArgs: function () { var args = [].slice.call(arguments); // Remove the optional first argument, renderTo, and // set it on this. if (isString(args[0]) || args[0].nodeName) { this.renderTo = args.shift(); } this.init(args[0], args[1]); }, /** * Initialize the chart */ init: function (userOptions, callback) { // Handle regular options var options, seriesOptions = userOptions.series; // skip merging data points to increase performance userOptions.series = null; options = merge(defaultOptions, userOptions); // do the merge options.series = userOptions.series = seriesOptions; // set back the series data this.userOptions = userOptions; var optionsChart = options.chart; // Create margin & spacing array this.margin = this.splashArray('margin', optionsChart); this.spacing = this.splashArray('spacing', optionsChart); var chartEvents = optionsChart.events; //this.runChartClick = chartEvents && !!chartEvents.click; this.bounds = { h: {}, v: {} }; // Pixel data bounds for touch zoom this.callback = callback; this.isResizing = 0; this.options = options; //chartTitleOptions = UNDEFINED; //chartSubtitleOptions = UNDEFINED; this.axes = []; this.series = []; this.hasCartesianSeries = optionsChart.showAxes; //this.axisOffset = UNDEFINED; //this.maxTicks = UNDEFINED; // handle the greatest amount of ticks on grouped axes //this.inverted = UNDEFINED; //this.loadingShown = UNDEFINED; //this.container = UNDEFINED; //this.chartWidth = UNDEFINED; //this.chartHeight = UNDEFINED; //this.marginRight = UNDEFINED; //this.marginBottom = UNDEFINED; //this.containerWidth = UNDEFINED; //this.containerHeight = UNDEFINED; //this.oldChartWidth = UNDEFINED; //this.oldChartHeight = UNDEFINED; //this.renderTo = UNDEFINED; //this.renderToClone = UNDEFINED; //this.spacingBox = UNDEFINED //this.legend = UNDEFINED; // Elements //this.chartBackground = UNDEFINED; //this.plotBackground = UNDEFINED; //this.plotBGImage = UNDEFINED; //this.plotBorder = UNDEFINED; //this.loadingDiv = UNDEFINED; //this.loadingSpan = UNDEFINED; var chart = this, eventType; // Add the chart to the global lookup chart.index = charts.length; charts.push(chart); chartCount++; // Set up auto resize if (optionsChart.reflow !== false) { addEvent(chart, 'load', function () { chart.initReflow(); }); } // Chart event handlers if (chartEvents) { for (eventType in chartEvents) { addEvent(chart, eventType, chartEvents[eventType]); } } chart.xAxis = []; chart.yAxis = []; // Expose methods and variables chart.animation = useCanVG ? false : pick(optionsChart.animation, true); chart.pointCount = chart.colorCounter = chart.symbolCounter = 0; chart.firstRender(); }, /** * Initialize an individual series, called internally before render time */ initSeries: function (options) { var chart = this, optionsChart = chart.options.chart, type = options.type || optionsChart.type || optionsChart.defaultSeriesType, series, constr = seriesTypes[type]; // No such series type if (!constr) { error(17, true); } series = new constr(); series.init(this, options); return series; }, /** * Check whether a given point is within the plot area * * @param {Number} plotX Pixel x relative to the plot area * @param {Number} plotY Pixel y relative to the plot area * @param {Boolean} inverted Whether the chart is inverted */ isInsidePlot: function (plotX, plotY, inverted) { var x = inverted ? plotY : plotX, y = inverted ? plotX : plotY; return x >= 0 && x <= this.plotWidth && y >= 0 && y <= this.plotHeight; }, /** * Redraw legend, axes or series based on updated data * * @param {Boolean|Object} animation Whether to apply animation, and optionally animation * configuration */ redraw: function (animation) { var chart = this, axes = chart.axes, series = chart.series, pointer = chart.pointer, legend = chart.legend, redrawLegend = chart.isDirtyLegend, hasStackedSeries, hasDirtyStacks, hasCartesianSeries = chart.hasCartesianSeries, isDirtyBox = chart.isDirtyBox, seriesLength = series.length, i = seriesLength, serie, renderer = chart.renderer, isHiddenChart = renderer.isHidden(), afterRedraw = []; setAnimation(animation, chart); if (isHiddenChart) { chart.cloneRenderTo(); } // Adjust title layout (reflow multiline text) chart.layOutTitles(); // link stacked series while (i--) { serie = series[i]; if (serie.options.stacking) { hasStackedSeries = true; if (serie.isDirty) { hasDirtyStacks = true; break; } } } if (hasDirtyStacks) { // mark others as dirty i = seriesLength; while (i--) { serie = series[i]; if (serie.options.stacking) { serie.isDirty = true; } } } // Handle updated data in the series each(series, function (serie) { if (serie.isDirty) { if (serie.options.legendType === 'point') { if (serie.updateTotals) { serie.updateTotals(); } redrawLegend = true; } } }); // handle added or removed series if (redrawLegend && legend.options.enabled) { // series or pie points are added or removed // draw legend graphics legend.render(); chart.isDirtyLegend = false; } // reset stacks if (hasStackedSeries) { chart.getStacks(); } if (hasCartesianSeries) { if (!chart.isResizing) { // reset maxTicks chart.maxTicks = null; // set axes scales each(axes, function (axis) { axis.setScale(); }); } } chart.getMargins(); // #3098 if (hasCartesianSeries) { // If one axis is dirty, all axes must be redrawn (#792, #2169) each(axes, function (axis) { if (axis.isDirty) { isDirtyBox = true; } }); // redraw axes each(axes, function (axis) { // Fire 'afterSetExtremes' only if extremes are set var key = axis.min + ',' + axis.max; if (axis.extKey !== key) { // #821, #4452 axis.extKey = key; afterRedraw.push(function () { // prevent a recursive call to chart.redraw() (#1119) fireEvent(axis, 'afterSetExtremes', extend(axis.eventArgs, axis.getExtremes())); // #747, #751 delete axis.eventArgs; }); } if (isDirtyBox || hasStackedSeries) { axis.redraw(); } }); } // the plot areas size has changed if (isDirtyBox) { chart.drawChartBox(); } // redraw affected series each(series, function (serie) { if (serie.isDirty && serie.visible && (!serie.isCartesian || serie.xAxis)) { // issue #153 serie.redraw(); } }); // move tooltip or reset if (pointer) { pointer.reset(true); } // redraw if canvas renderer.draw(); // fire the event fireEvent(chart, 'redraw'); if (isHiddenChart) { chart.cloneRenderTo(true); } // Fire callbacks that are put on hold until after the redraw each(afterRedraw, function (callback) { callback.call(); }); }, /** * Get an axis, series or point object by id. * @param id {String} The id as given in the configuration options */ get: function (id) { var chart = this, axes = chart.axes, series = chart.series; var i, j, points; // search axes for (i = 0; i < axes.length; i++) { if (axes[i].options.id === id) { return axes[i]; } } // search series for (i = 0; i < series.length; i++) { if (series[i].options.id === id) { return series[i]; } } // search points for (i = 0; i < series.length; i++) { points = series[i].points || []; for (j = 0; j < points.length; j++) { if (points[j].id === id) { return points[j]; } } } return null; }, /** * Create the Axis instances based on the config options */ getAxes: function () { var chart = this, options = this.options, xAxisOptions = options.xAxis = splat(options.xAxis || {}), yAxisOptions = options.yAxis = splat(options.yAxis || {}), optionsArray; // make sure the options are arrays and add some members each(xAxisOptions, function (axis, i) { axis.index = i; axis.isX = true; }); each(yAxisOptions, function (axis, i) { axis.index = i; }); // concatenate all axis options into one array optionsArray = xAxisOptions.concat(yAxisOptions); each(optionsArray, function (axisOptions) { new Axis(chart, axisOptions); // eslint-disable-line no-new }); }, /** * Get the currently selected points from all series */ getSelectedPoints: function () { var points = []; each(this.series, function (serie) { points = points.concat(grep(serie.points || [], function (point) { return point.selected; })); }); return points; }, /** * Get the currently selected series */ getSelectedSeries: function () { return grep(this.series, function (serie) { return serie.selected; }); }, /** * Show the title and subtitle of the chart * * @param titleOptions {Object} New title options * @param subtitleOptions {Object} New subtitle options * */ setTitle: function (titleOptions, subtitleOptions, redraw) { var chart = this, options = chart.options, chartTitleOptions, chartSubtitleOptions; chartTitleOptions = options.title = merge(options.title, titleOptions); chartSubtitleOptions = options.subtitle = merge(options.subtitle, subtitleOptions); // add title and subtitle each([ ['title', titleOptions, chartTitleOptions], ['subtitle', subtitleOptions, chartSubtitleOptions] ], function (arr) { var name = arr[0], title = chart[name], titleOptions = arr[1], chartTitleOptions = arr[2]; if (title && titleOptions) { chart[name] = title = title.destroy(); // remove old } if (chartTitleOptions && chartTitleOptions.text && !title) { chart[name] = chart.renderer.text( chartTitleOptions.text, 0, 0, chartTitleOptions.useHTML ) .attr({ align: chartTitleOptions.align, 'class': PREFIX + name, zIndex: chartTitleOptions.zIndex || 4 }) .css(chartTitleOptions.style) .add(); } }); chart.layOutTitles(redraw); }, /** * Lay out the chart titles and cache the full offset height for use in getMargins */ layOutTitles: function (redraw) { var titleOffset = 0, title = this.title, subtitle = this.subtitle, options = this.options, titleOptions = options.title, subtitleOptions = options.subtitle, requiresDirtyBox, renderer = this.renderer, autoWidth = this.spacingBox.width - 44; // 44 makes room for default context button if (title) { title .css({ width: (titleOptions.width || autoWidth) + PX }) .align(extend({ y: renderer.fontMetrics(titleOptions.style.fontSize, title).b - 3 }, titleOptions), false, 'spacingBox'); if (!titleOptions.floating && !titleOptions.verticalAlign) { titleOffset = title.getBBox().height; } } if (subtitle) { subtitle .css({ width: (subtitleOptions.width || autoWidth) + PX }) .align(extend({ y: titleOffset + (titleOptions.margin - 13) + renderer.fontMetrics(subtitleOptions.style.fontSize, title).b }, subtitleOptions), false, 'spacingBox'); if (!subtitleOptions.floating && !subtitleOptions.verticalAlign) { titleOffset = mathCeil(titleOffset + subtitle.getBBox().height); } } requiresDirtyBox = this.titleOffset !== titleOffset; this.titleOffset = titleOffset; // used in getMargins if (!this.isDirtyBox && requiresDirtyBox) { this.isDirtyBox = requiresDirtyBox; // Redraw if necessary (#2719, #2744) if (this.hasRendered && pick(redraw, true) && this.isDirtyBox) { this.redraw(); } } }, /** * Get chart width and height according to options and container size */ getChartSize: function () { var chart = this, optionsChart = chart.options.chart, widthOption = optionsChart.width, heightOption = optionsChart.height, renderTo = chart.renderToClone || chart.renderTo; // Get inner width and height if (!defined(widthOption)) { chart.containerWidth = getStyle(renderTo, 'width'); } if (!defined(heightOption)) { chart.containerHeight = getStyle(renderTo, 'height'); } chart.chartWidth = mathMax(0, widthOption || chart.containerWidth || 600); // #1393, 1460 chart.chartHeight = mathMax(0, pick(heightOption, // the offsetHeight of an empty container is 0 in standard browsers, but 19 in IE7: chart.containerHeight > 19 ? chart.containerHeight : 400)); }, /** * Create a clone of the chart's renderTo div and place it outside the viewport to allow * size computation on chart.render and chart.redraw */ cloneRenderTo: function (revert) { var clone = this.renderToClone, container = this.container; // Destroy the clone and bring the container back to the real renderTo div if (revert) { if (clone) { this.renderTo.appendChild(container); discardElement(clone); delete this.renderToClone; } // Set up the clone } else { if (container && container.parentNode === this.renderTo) { this.renderTo.removeChild(container); // do not clone this } this.renderToClone = clone = this.renderTo.cloneNode(0); css(clone, { position: ABSOLUTE, top: '-9999px', display: 'block' // #833 }); if (clone.style.setProperty) { // #2631 clone.style.setProperty('display', 'block', 'important'); } doc.body.appendChild(clone); if (container) { clone.appendChild(container); } } }, /** * Get the containing element, determine the size and create the inner container * div to hold the chart */ getContainer: function () { var chart = this, container, options = chart.options, optionsChart = options.chart, chartWidth, chartHeight, renderTo = chart.renderTo, indexAttrName = 'data-highcharts-chart', oldChartIndex, Ren, containerId = 'highcharts-' + idCounter++; if (!renderTo) { chart.renderTo = renderTo = optionsChart.renderTo; } if (isString(renderTo)) { chart.renderTo = renderTo = doc.getElementById(renderTo); } // Display an error if the renderTo is wrong if (!renderTo) { error(13, true); } // If the container already holds a chart, destroy it. The check for hasRendered is there // because web pages that are saved to disk from the browser, will preserve the data-highcharts-chart // attribute and the SVG contents, but not an interactive chart. So in this case, // charts[oldChartIndex] will point to the wrong chart if any (#2609). oldChartIndex = pInt(attr(renderTo, indexAttrName)); if (!isNaN(oldChartIndex) && charts[oldChartIndex] && charts[oldChartIndex].hasRendered) { charts[oldChartIndex].destroy(); } // Make a reference to the chart from the div attr(renderTo, indexAttrName, chart.index); // remove previous chart renderTo.innerHTML = ''; // If the container doesn't have an offsetWidth, it has or is a child of a node // that has display:none. We need to temporarily move it out to a visible // state to determine the size, else the legend and tooltips won't render // properly. The allowClone option is used in sparklines as a micro optimization, // saving about 1-2 ms each chart. if (!optionsChart.skipClone && !renderTo.offsetWidth) { chart.cloneRenderTo(); } // get the width and height chart.getChartSize(); chartWidth = chart.chartWidth; chartHeight = chart.chartHeight; // create the inner container chart.container = container = createElement(DIV, { className: PREFIX + 'container' + (optionsChart.className ? ' ' + optionsChart.className : ''), id: containerId }, extend({ position: RELATIVE, overflow: HIDDEN, // needed for context menu (avoid scrollbars) and // content overflow in IE width: chartWidth + PX, height: chartHeight + PX, textAlign: 'left', lineHeight: 'normal', // #427 zIndex: 0, // #1072 '-webkit-tap-highlight-color': 'rgba(0,0,0,0)' }, optionsChart.style), chart.renderToClone || renderTo ); // cache the cursor (#1650) chart._cursor = container.style.cursor; // Initialize the renderer Ren = Highcharts[optionsChart.renderer] || Renderer; chart.renderer = new Ren( container, chartWidth, chartHeight, optionsChart.style, optionsChart.forExport, options.exporting && options.exporting.allowHTML ); if (useCanVG) { // If we need canvg library, extend and configure the renderer // to get the tracker for translating mouse events chart.renderer.create(chart, container, chartWidth, chartHeight); } // Add a reference to the charts index chart.renderer.chartIndex = chart.index; }, /** * Calculate margins by rendering axis labels in a preliminary position. Title, * subtitle and legend have already been rendered at this stage, but will be * moved into their final positions */ getMargins: function (skipAxes) { var chart = this, spacing = chart.spacing, margin = chart.margin, titleOffset = chart.titleOffset; chart.resetMargins(); // Adjust for title and subtitle if (titleOffset && !defined(margin[0])) { chart.plotTop = mathMax(chart.plotTop, titleOffset + chart.options.title.margin + spacing[0]); } // Adjust for legend chart.legend.adjustMargins(margin, spacing); // adjust for scroller if (chart.extraBottomMargin) { chart.marginBottom += chart.extraBottomMargin; } if (chart.extraTopMargin) { chart.plotTop += chart.extraTopMargin; } if (!skipAxes) { this.getAxisMargins(); } }, getAxisMargins: function () { var chart = this, axisOffset = chart.axisOffset = [0, 0, 0, 0], // top, right, bottom, left margin = chart.margin; // pre-render axes to get labels offset width if (chart.hasCartesianSeries) { each(chart.axes, function (axis) { if (axis.visible) { axis.getOffset(); } }); } // Add the axis offsets each(marginNames, function (m, side) { if (!defined(margin[side])) { chart[m] += axisOffset[side]; } }); chart.setChartSize(); }, /** * Resize the chart to its container if size is not explicitly set */ reflow: function (e) { var chart = this, optionsChart = chart.options.chart, renderTo = chart.renderTo, width = optionsChart.width || getStyle(renderTo, 'width'), height = optionsChart.height || getStyle(renderTo, 'height'), target = e ? e.target : win; // Width and height checks for display:none. Target is doc in IE8 and Opera, // win in Firefox, Chrome and IE9. if (!chart.hasUserSize && !chart.isPrinting && width && height && (target === win || target === doc)) { // #1093 if (width !== chart.containerWidth || height !== chart.containerHeight) { clearTimeout(chart.reflowTimeout); // When called from window.resize, e is set, else it's called directly (#2224) chart.reflowTimeout = syncTimeout(function () { if (chart.container) { // It may have been destroyed in the meantime (#1257) chart.setSize(width, height, false); chart.hasUserSize = null; } }, e ? 100 : 0); } chart.containerWidth = width; chart.containerHeight = height; } }, /** * Add the event handlers necessary for auto resizing */ initReflow: function () { var chart = this, reflow = function (e) { chart.reflow(e); }; addEvent(win, 'resize', reflow); addEvent(chart, 'destroy', function () { removeEvent(win, 'resize', reflow); }); }, /** * Resize the chart to a given width and height * @param {Number} width * @param {Number} height * @param {Object|Boolean} animation */ setSize: function (width, height, animation) { var chart = this, chartWidth, chartHeight, renderer = chart.renderer, globalAnimation; // Handle the isResizing counter chart.isResizing += 1; // set the animation for the current process setAnimation(animation, chart); chart.oldChartHeight = chart.chartHeight; chart.oldChartWidth = chart.chartWidth; if (defined(width)) { chart.chartWidth = chartWidth = mathMax(0, mathRound(width)); chart.hasUserSize = !!chartWidth; } if (defined(height)) { chart.chartHeight = chartHeight = mathMax(0, mathRound(height)); } // Resize the container with the global animation applied if enabled (#2503) globalAnimation = renderer.globalAnimation; (globalAnimation ? animate : css)(chart.container, { width: chartWidth + PX, height: chartHeight + PX }, globalAnimation); chart.setChartSize(true); renderer.setSize(chartWidth, chartHeight, animation); // handle axes chart.maxTicks = null; each(chart.axes, function (axis) { axis.isDirty = true; axis.setScale(); }); // make sure non-cartesian series are also handled each(chart.series, function (serie) { serie.isDirty = true; }); chart.isDirtyLegend = true; // force legend redraw chart.isDirtyBox = true; // force redraw of plot and chart border chart.layOutTitles(); // #2857 chart.getMargins(); chart.redraw(animation); chart.oldChartHeight = null; fireEvent(chart, 'resize'); // Fire endResize and set isResizing back. If animation is disabled, fire without delay globalAnimation = renderer.globalAnimation; // Reassign it before using it, it may have changed since the top of this function. syncTimeout(function () { if (chart) { fireEvent(chart, 'endResize', null, function () { chart.isResizing -= 1; }); } }, globalAnimation === false ? 0 : ((globalAnimation && globalAnimation.duration) || 500)); }, /** * Set the public chart properties. This is done before and after the pre-render * to determine margin sizes */ setChartSize: function (skipAxes) { var chart = this, inverted = chart.inverted, renderer = chart.renderer, chartWidth = chart.chartWidth, chartHeight = chart.chartHeight, optionsChart = chart.options.chart, spacing = chart.spacing, clipOffset = chart.clipOffset, clipX, clipY, plotLeft, plotTop, plotWidth, plotHeight, plotBorderWidth; chart.plotLeft = plotLeft = mathRound(chart.plotLeft); chart.plotTop = plotTop = mathRound(chart.plotTop); chart.plotWidth = plotWidth = mathMax(0, mathRound(chartWidth - plotLeft - chart.marginRight)); chart.plotHeight = plotHeight = mathMax(0, mathRound(chartHeight - plotTop - chart.marginBottom)); chart.plotSizeX = inverted ? plotHeight : plotWidth; chart.plotSizeY = inverted ? plotWidth : plotHeight; chart.plotBorderWidth = optionsChart.plotBorderWidth || 0; // Set boxes used for alignment chart.spacingBox = renderer.spacingBox = { x: spacing[3], y: spacing[0], width: chartWidth - spacing[3] - spacing[1], height: chartHeight - spacing[0] - spacing[2] }; chart.plotBox = renderer.plotBox = { x: plotLeft, y: plotTop, width: plotWidth, height: plotHeight }; plotBorderWidth = 2 * mathFloor(chart.plotBorderWidth / 2); clipX = mathCeil(mathMax(plotBorderWidth, clipOffset[3]) / 2); clipY = mathCeil(mathMax(plotBorderWidth, clipOffset[0]) / 2); chart.clipBox = { x: clipX, y: clipY, width: mathFloor(chart.plotSizeX - mathMax(plotBorderWidth, clipOffset[1]) / 2 - clipX), height: mathMax(0, mathFloor(chart.plotSizeY - mathMax(plotBorderWidth, clipOffset[2]) / 2 - clipY)) }; if (!skipAxes) { each(chart.axes, function (axis) { axis.setAxisSize(); axis.setAxisTranslation(); }); } }, /** * Initial margins before auto size margins are applied */ resetMargins: function () { var chart = this; each(marginNames, function (m, side) { chart[m] = pick(chart.margin[side], chart.spacing[side]); }); chart.axisOffset = [0, 0, 0, 0]; // top, right, bottom, left chart.clipOffset = [0, 0, 0, 0]; }, /** * Draw the borders and backgrounds for chart and plot area */ drawChartBox: function () { var chart = this, optionsChart = chart.options.chart, renderer = chart.renderer, chartWidth = chart.chartWidth, chartHeight = chart.chartHeight, chartBackground = chart.chartBackground, plotBackground = chart.plotBackground, plotBorder = chart.plotBorder, plotBGImage = chart.plotBGImage, chartBorderWidth = optionsChart.borderWidth || 0, chartBackgroundColor = optionsChart.backgroundColor, plotBackgroundColor = optionsChart.plotBackgroundColor, plotBackgroundImage = optionsChart.plotBackgroundImage, plotBorderWidth = optionsChart.plotBorderWidth || 0, mgn, bgAttr, plotLeft = chart.plotLeft, plotTop = chart.plotTop, plotWidth = chart.plotWidth, plotHeight = chart.plotHeight, plotBox = chart.plotBox, clipRect = chart.clipRect, clipBox = chart.clipBox; // Chart area mgn = chartBorderWidth + (optionsChart.shadow ? 8 : 0); if (chartBorderWidth || chartBackgroundColor) { if (!chartBackground) { bgAttr = { fill: chartBackgroundColor || NONE }; if (chartBorderWidth) { // #980 bgAttr.stroke = optionsChart.borderColor; bgAttr['stroke-width'] = chartBorderWidth; } chart.chartBackground = renderer.rect(mgn / 2, mgn / 2, chartWidth - mgn, chartHeight - mgn, optionsChart.borderRadius, chartBorderWidth) .attr(bgAttr) .addClass(PREFIX + 'background') .add() .shadow(optionsChart.shadow); } else { // resize chartBackground.animate( chartBackground.crisp({ width: chartWidth - mgn, height: chartHeight - mgn }) ); } } // Plot background if (plotBackgroundColor) { if (!plotBackground) { chart.plotBackground = renderer.rect(plotLeft, plotTop, plotWidth, plotHeight, 0) .attr({ fill: plotBackgroundColor }) .add() .shadow(optionsChart.plotShadow); } else { plotBackground.animate(plotBox); } } if (plotBackgroundImage) { if (!plotBGImage) { chart.plotBGImage = renderer.image(plotBackgroundImage, plotLeft, plotTop, plotWidth, plotHeight) .add(); } else { plotBGImage.animate(plotBox); } } // Plot clip if (!clipRect) { chart.clipRect = renderer.clipRect(clipBox); } else { clipRect.animate({ width: clipBox.width, height: clipBox.height }); } // Plot area border if (plotBorderWidth) { if (!plotBorder) { chart.plotBorder = renderer.rect(plotLeft, plotTop, plotWidth, plotHeight, 0, -plotBorderWidth) .attr({ stroke: optionsChart.plotBorderColor, 'stroke-width': plotBorderWidth, fill: NONE, zIndex: 1 }) .add(); } else { plotBorder.strokeWidth = -plotBorderWidth; plotBorder.animate( plotBorder.crisp({ x: plotLeft, y: plotTop, width: plotWidth, height: plotHeight }) //#3282 plotBorder should be negative ); } } // reset chart.isDirtyBox = false; }, /** * Detect whether a certain chart property is needed based on inspecting its options * and series. This mainly applies to the chart.invert property, and in extensions to * the chart.angular and chart.polar properties. */ propFromSeries: function () { var chart = this, optionsChart = chart.options.chart, klass, seriesOptions = chart.options.series, i, value; each(['inverted', 'angular', 'polar'], function (key) { // The default series type's class klass = seriesTypes[optionsChart.type || optionsChart.defaultSeriesType]; // Get the value from available chart-wide properties value = ( chart[key] || // 1. it is set before optionsChart[key] || // 2. it is set in the options (klass && klass.prototype[key]) // 3. it's default series class requires it ); // 4. Check if any the chart's series require it i = seriesOptions && seriesOptions.length; while (!value && i--) { klass = seriesTypes[seriesOptions[i].type]; if (klass && klass.prototype[key]) { value = true; } } // Set the chart property chart[key] = value; }); }, /** * Link two or more series together. This is done initially from Chart.render, * and after Chart.addSeries and Series.remove. */ linkSeries: function () { var chart = this, chartSeries = chart.series; // Reset links each(chartSeries, function (series) { series.linkedSeries.length = 0; }); // Apply new links each(chartSeries, function (series) { var linkedTo = series.options.linkedTo; if (isString(linkedTo)) { if (linkedTo === ':previous') { linkedTo = chart.series[series.index - 1]; } else { linkedTo = chart.get(linkedTo); } if (linkedTo) { linkedTo.linkedSeries.push(series); series.linkedParent = linkedTo; series.visible = pick(series.options.visible, linkedTo.options.visible, series.visible); // #3879 } } }); }, /** * Render series for the chart */ renderSeries: function () { each(this.series, function (serie) { serie.translate(); serie.render(); }); }, /** * Render labels for the chart */ renderLabels: function () { var chart = this, labels = chart.options.labels; if (labels.items) { each(labels.items, function (label) { var style = extend(labels.style, label.style), x = pInt(style.left) + chart.plotLeft, y = pInt(style.top) + chart.plotTop + 12; // delete to prevent rewriting in IE delete style.left; delete style.top; chart.renderer.text( label.html, x, y ) .attr({ zIndex: 2 }) .css(style) .add(); }); } }, /** * Render all graphics for the chart */ render: function () { var chart = this, axes = chart.axes, renderer = chart.renderer, options = chart.options, tempWidth, tempHeight, redoHorizontal, redoVertical; // Title chart.setTitle(); // Legend chart.legend = new Legend(chart, options.legend); // Get stacks if (chart.getStacks) { chart.getStacks(); } // Get chart margins chart.getMargins(true); chart.setChartSize(); // Record preliminary dimensions for later comparison tempWidth = chart.plotWidth; tempHeight = chart.plotHeight = chart.plotHeight - 21; // 21 is the most common correction for X axis labels // Get margins by pre-rendering axes each(axes, function (axis) { axis.setScale(); }); chart.getAxisMargins(); // If the plot area size has changed significantly, calculate tick positions again redoHorizontal = tempWidth / chart.plotWidth > 1.1; redoVertical = tempHeight / chart.plotHeight > 1.05; // Height is more sensitive if (redoHorizontal || redoVertical) { chart.maxTicks = null; // reset for second pass each(axes, function (axis) { if ((axis.horiz && redoHorizontal) || (!axis.horiz && redoVertical)) { axis.setTickInterval(true); // update to reflect the new margins } }); chart.getMargins(); // second pass to check for new labels } // Draw the borders and backgrounds chart.drawChartBox(); // Axes if (chart.hasCartesianSeries) { each(axes, function (axis) { if (axis.visible) { axis.render(); } }); } // The series if (!chart.seriesGroup) { chart.seriesGroup = renderer.g('series-group') .attr({ zIndex: 3 }) .add(); } chart.renderSeries(); // Labels chart.renderLabels(); // Credits chart.showCredits(options.credits); // Set flag chart.hasRendered = true; }, /** * Show chart credits based on config options */ showCredits: function (credits) { if (credits.enabled && !this.credits) { this.credits = this.renderer.text( credits.text, 0, 0 ) .on('click', function () { if (credits.href) { win.location.href = credits.href; } }) .attr({ align: credits.position.align, zIndex: 8 }) .css(credits.style) .add() .align(credits.position); } }, /** * Clean up memory usage */ destroy: function () { var chart = this, axes = chart.axes, series = chart.series, container = chart.container, i, parentNode = container && container.parentNode; // fire the chart.destoy event fireEvent(chart, 'destroy'); // Delete the chart from charts lookup array charts[chart.index] = UNDEFINED; chartCount--; chart.renderTo.removeAttribute('data-highcharts-chart'); // remove events removeEvent(chart); // ==== Destroy collections: // Destroy axes i = axes.length; while (i--) { axes[i] = axes[i].destroy(); } // Destroy each series i = series.length; while (i--) { series[i] = series[i].destroy(); } // ==== Destroy chart properties: each(['title', 'subtitle', 'chartBackground', 'plotBackground', 'plotBGImage', 'plotBorder', 'seriesGroup', 'clipRect', 'credits', 'pointer', 'scroller', 'rangeSelector', 'legend', 'resetZoomButton', 'tooltip', 'renderer'], function (name) { var prop = chart[name]; if (prop && prop.destroy) { chart[name] = prop.destroy(); } }); // remove container and all SVG if (container) { // can break in IE when destroyed before finished loading container.innerHTML = ''; removeEvent(container); if (parentNode) { discardElement(container); } } // clean it all up for (i in chart) { delete chart[i]; } }, /** * VML namespaces can't be added until after complete. Listening * for Perini's doScroll hack is not enough. */ isReadyToRender: function () { var chart = this; // Note: win == win.top is required if ((!hasSVG && (win == win.top && doc.readyState !== 'complete')) || (useCanVG && !win.canvg)) { // eslint-disable-line eqeqeq if (useCanVG) { // Delay rendering until canvg library is downloaded and ready CanVGController.push(function () { chart.firstRender(); }, chart.options.global.canvasToolsURL); } else { doc.attachEvent('onreadystatechange', function () { doc.detachEvent('onreadystatechange', chart.firstRender); if (doc.readyState === 'complete') { chart.firstRender(); } }); } return false; } return true; }, /** * Prepare for first rendering after all data are loaded */ firstRender: function () { var chart = this, options = chart.options; // Check whether the chart is ready to render if (!chart.isReadyToRender()) { return; } // Create the container chart.getContainer(); // Run an early event after the container and renderer are established fireEvent(chart, 'init'); chart.resetMargins(); chart.setChartSize(); // Set the common chart properties (mainly invert) from the given series chart.propFromSeries(); // get axes chart.getAxes(); // Initialize the series each(options.series || [], function (serieOptions) { chart.initSeries(serieOptions); }); chart.linkSeries(); // Run an event after axes and series are initialized, but before render. At this stage, // the series data is indexed and cached in the xData and yData arrays, so we can access // those before rendering. Used in Highstock. fireEvent(chart, 'beforeRender'); // depends on inverted and on margins being set if (Highcharts.Pointer) { chart.pointer = new Pointer(chart, options); } chart.render(); // add canvas chart.renderer.draw(); // Fire the load event if there are no external images if (!chart.renderer.imgCount) { chart.onload(); } // If the chart was rendered outside the top container, put it back in (#3679) chart.cloneRenderTo(true); }, /** * On chart load */ onload: function () { var chart = this; // Run callbacks each([this.callback].concat(this.callbacks), function (fn) { if (fn && chart.index !== undefined) { // Chart destroyed in its own callback (#3600) fn.apply(chart, [chart]); } }); // Fire the load event if there are no external images if (!chart.renderer.imgCount) { fireEvent(chart, 'load'); } }, /** * Creates arrays for spacing and margin from given options. */ splashArray: function (target, options) { var oVar = options[target], tArray = isObject(oVar) ? oVar : [oVar, oVar, oVar, oVar]; return [pick(options[target + 'Top'], tArray[0]), pick(options[target + 'Right'], tArray[1]), pick(options[target + 'Bottom'], tArray[2]), pick(options[target + 'Left'], tArray[3])]; } }; // end Chart /** * The Point object and prototype. Inheritable and used as base for PiePoint */ var Point = function () {}; Point.prototype = { /** * Initialize the point * @param {Object} series The series object containing this point * @param {Object} options The data in either number, array or object format */ init: function (series, options, x) { var point = this, colors; point.series = series; point.color = series.color; // #3445 point.applyOptions(options, x); point.pointAttr = {}; if (series.options.colorByPoint) { colors = series.options.colors || series.chart.options.colors; point.color = point.color || colors[series.colorCounter++]; // loop back to zero if (series.colorCounter === colors.length) { series.colorCounter = 0; } } series.chart.pointCount++; return point; }, /** * Apply the options containing the x and y data and possible some extra properties. * This is called on point init or from point.update. * * @param {Object} options */ applyOptions: function (options, x) { var point = this, series = point.series, pointValKey = series.options.pointValKey || series.pointValKey; options = Point.prototype.optionsToObject.call(this, options); // copy options directly to point extend(point, options); point.options = point.options ? extend(point.options, options) : options; // For higher dimension series types. For instance, for ranges, point.y is mapped to point.low. if (pointValKey) { point.y = point[pointValKey]; } point.isNull = point.y === null; // If no x is set by now, get auto incremented value. All points must have an // x value, however the y value can be null to create a gap in the series if (typeof point.x !== 'number' && series) { point.x = x === undefined ? series.autoIncrement() : x; } return point; }, /** * Transform number or array configs into objects */ optionsToObject: function (options) { var ret = {}, series = this.series, keys = series.options.keys, pointArrayMap = keys || series.pointArrayMap || ['y'], valueCount = pointArrayMap.length, firstItemType, i = 0, j = 0; if (typeof options === 'number' || options === null) { ret[pointArrayMap[0]] = options; } else if (isArray(options)) { // with leading x value if (!keys && options.length > valueCount) { firstItemType = typeof options[0]; if (firstItemType === 'string') { ret.name = options[0]; } else if (firstItemType === 'number') { ret.x = options[0]; } i++; } while (j < valueCount) { if (!keys || options[i] !== undefined) { // Skip undefined positions for keys ret[pointArrayMap[j]] = options[i]; } i++; j++; } } else if (typeof options === 'object') { ret = options; // This is the fastest way to detect if there are individual point dataLabels that need // to be considered in drawDataLabels. These can only occur in object configs. if (options.dataLabels) { series._hasPointLabels = true; } // Same approach as above for markers if (options.marker) { series._hasPointMarkers = true; } } return ret; }, /** * Destroy a point to clear memory. Its reference still stays in series.data. */ destroy: function () { var point = this, series = point.series, chart = series.chart, hoverPoints = chart.hoverPoints, prop; chart.pointCount--; if (hoverPoints) { point.setState(); erase(hoverPoints, point); if (!hoverPoints.length) { chart.hoverPoints = null; } } if (point === chart.hoverPoint) { point.onMouseOut(); } // remove all events if (point.graphic || point.dataLabel) { // removeEvent and destroyElements are performance expensive removeEvent(point); point.destroyElements(); } if (point.legendItem) { // pies have legend items chart.legend.destroyItem(point); } for (prop in point) { point[prop] = null; } }, /** * Destroy SVG elements associated with the point */ destroyElements: function () { var point = this, props = ['graphic', 'dataLabel', 'dataLabelUpper', 'connector', 'shadowGroup'], prop, i = 6; while (i--) { prop = props[i]; if (point[prop]) { point[prop] = point[prop].destroy(); } } }, /** * Return the configuration hash needed for the data label and tooltip formatters */ getLabelConfig: function () { return { x: this.category, y: this.y, color: this.color, key: this.name || this.category, series: this.series, point: this, percentage: this.percentage, total: this.total || this.stackTotal }; }, /** * Extendable method for formatting each point's tooltip line * * @return {String} A string to be concatenated in to the common tooltip text */ tooltipFormatter: function (pointFormat) { // Insert options for valueDecimals, valuePrefix, and valueSuffix var series = this.series, seriesTooltipOptions = series.tooltipOptions, valueDecimals = pick(seriesTooltipOptions.valueDecimals, ''), valuePrefix = seriesTooltipOptions.valuePrefix || '', valueSuffix = seriesTooltipOptions.valueSuffix || ''; // Loop over the point array map and replace unformatted values with sprintf formatting markup each(series.pointArrayMap || ['y'], function (key) { key = '{point.' + key; // without the closing bracket if (valuePrefix || valueSuffix) { pointFormat = pointFormat.replace(key + '}', valuePrefix + key + '}' + valueSuffix); } pointFormat = pointFormat.replace(key + '}', key + ':,.' + valueDecimals + 'f}'); }); return format(pointFormat, { point: this, series: this.series }); }, /** * Fire an event on the Point object. * @param {String} eventType * @param {Object} eventArgs Additional event arguments * @param {Function} defaultFunction Default event handler */ firePointEvent: function (eventType, eventArgs, defaultFunction) { var point = this, series = this.series, seriesOptions = series.options; // load event handlers on demand to save time on mouseover/out if (seriesOptions.point.events[eventType] || (point.options && point.options.events && point.options.events[eventType])) { this.importEvents(); } // add default handler if in selection mode if (eventType === 'click' && seriesOptions.allowPointSelect) { defaultFunction = function (event) { // Control key is for Windows, meta (= Cmd key) for Mac, Shift for Opera if (point.select) { // Could be destroyed by prior event handlers (#2911) point.select(null, event.ctrlKey || event.metaKey || event.shiftKey); } }; } fireEvent(this, eventType, eventArgs, defaultFunction); }, visible: true };/** * @classDescription The base function which all other series types inherit from. The data in the series is stored * in various arrays. * * - First, series.options.data contains all the original config options for * each point whether added by options or methods like series.addPoint. * - Next, series.data contains those values converted to points, but in case the series data length * exceeds the cropThreshold, or if the data is grouped, series.data doesn't contain all the points. It * only contains the points that have been created on demand. * - Then there's series.points that contains all currently visible point objects. In case of cropping, * the cropped-away points are not part of this array. The series.points array starts at series.cropStart * compared to series.data and series.options.data. If however the series data is grouped, these can't * be correlated one to one. * - series.xData and series.processedXData contain clean x values, equivalent to series.data and series.points. * - series.yData and series.processedYData contain clean x values, equivalent to series.data and series.points. * * @param {Object} chart * @param {Object} options */ var Series = Highcharts.Series = function () {}; Series.prototype = { isCartesian: true, type: 'line', pointClass: Point, sorted: true, // requires the data to be sorted requireSorting: true, pointAttrToOptions: { // mapping between SVG attributes and the corresponding options stroke: 'lineColor', 'stroke-width': 'lineWidth', fill: 'fillColor', r: 'radius' }, directTouch: false, axisTypes: ['xAxis', 'yAxis'], colorCounter: 0, parallelArrays: ['x', 'y'], // each point's x and y values are stored in this.xData and this.yData init: function (chart, options) { var series = this, eventType, events, chartSeries = chart.series, sortByIndex = function (a, b) { return pick(a.options.index, a._i) - pick(b.options.index, b._i); }; series.chart = chart; series.options = options = series.setOptions(options); // merge with plotOptions series.linkedSeries = []; // bind the axes series.bindAxes(); // set some variables extend(series, { name: options.name, state: NORMAL_STATE, pointAttr: {}, visible: options.visible !== false, // true by default selected: options.selected === true // false by default }); // special if (useCanVG) { options.animation = false; } // register event listeners events = options.events; for (eventType in events) { addEvent(series, eventType, events[eventType]); } if ( (events && events.click) || (options.point && options.point.events && options.point.events.click) || options.allowPointSelect ) { chart.runTrackerClick = true; } series.getColor(); series.getSymbol(); // Set the data each(series.parallelArrays, function (key) { series[key + 'Data'] = []; }); series.setData(options.data, false); // Mark cartesian if (series.isCartesian) { chart.hasCartesianSeries = true; } // Register it in the chart chartSeries.push(series); series._i = chartSeries.length - 1; // Sort series according to index option (#248, #1123, #2456) stableSort(chartSeries, sortByIndex); if (this.yAxis) { stableSort(this.yAxis.series, sortByIndex); } each(chartSeries, function (series, i) { series.index = i; series.name = series.name || 'Series ' + (i + 1); }); }, /** * Set the xAxis and yAxis properties of cartesian series, and register the series * in the axis.series array */ bindAxes: function () { var series = this, seriesOptions = series.options, chart = series.chart, axisOptions; each(series.axisTypes || [], function (AXIS) { // repeat for xAxis and yAxis each(chart[AXIS], function (axis) { // loop through the chart's axis objects axisOptions = axis.options; // apply if the series xAxis or yAxis option mathches the number of the // axis, or if undefined, use the first axis if ((seriesOptions[AXIS] === axisOptions.index) || (seriesOptions[AXIS] !== UNDEFINED && seriesOptions[AXIS] === axisOptions.id) || (seriesOptions[AXIS] === UNDEFINED && axisOptions.index === 0)) { // register this series in the axis.series lookup axis.series.push(series); // set this series.xAxis or series.yAxis reference series[AXIS] = axis; // mark dirty for redraw axis.isDirty = true; } }); // The series needs an X and an Y axis if (!series[AXIS] && series.optionalAxis !== AXIS) { error(18, true); } }); }, /** * For simple series types like line and column, the data values are held in arrays like * xData and yData for quick lookup to find extremes and more. For multidimensional series * like bubble and map, this can be extended with arrays like zData and valueData by * adding to the series.parallelArrays array. */ updateParallelArrays: function (point, i) { var series = point.series, args = arguments, fn = typeof i === 'number' ? // Insert the value in the given position function (key) { var val = key === 'y' && series.toYData ? series.toYData(point) : point[key]; series[key + 'Data'][i] = val; } : // Apply the method specified in i with the following arguments as arguments function (key) { Array.prototype[i].apply(series[key + 'Data'], Array.prototype.slice.call(args, 2)); }; each(series.parallelArrays, fn); }, /** * Return an auto incremented x value based on the pointStart and pointInterval options. * This is only used if an x value is not given for the point that calls autoIncrement. */ autoIncrement: function () { var options = this.options, xIncrement = this.xIncrement, date, pointInterval, pointIntervalUnit = options.pointIntervalUnit; xIncrement = pick(xIncrement, options.pointStart, 0); this.pointInterval = pointInterval = pick(this.pointInterval, options.pointInterval, 1); // Added code for pointInterval strings if (pointIntervalUnit === 'month' || pointIntervalUnit === 'year') { date = new Date(xIncrement); date = (pointIntervalUnit === 'month') ? +date[setMonth](date[getMonth]() + pointInterval) : +date[setFullYear](date[getFullYear]() + pointInterval); pointInterval = date - xIncrement; } this.xIncrement = xIncrement + pointInterval; return xIncrement; }, /** * Set the series options by merging from the options tree * @param {Object} itemOptions */ setOptions: function (itemOptions) { var chart = this.chart, chartOptions = chart.options, plotOptions = chartOptions.plotOptions, userOptions = chart.userOptions || {}, userPlotOptions = userOptions.plotOptions || {}, typeOptions = plotOptions[this.type], options, zones; this.userOptions = itemOptions; // General series options take precedence over type options because otherwise, default // type options like column.animation would be overwritten by the general option. // But issues have been raised here (#3881), and the solution may be to distinguish // between default option and userOptions like in the tooltip below. options = merge( typeOptions, plotOptions.series, itemOptions ); // The tooltip options are merged between global and series specific options this.tooltipOptions = merge( defaultOptions.tooltip, defaultOptions.plotOptions[this.type].tooltip, userOptions.tooltip, userPlotOptions.series && userPlotOptions.series.tooltip, userPlotOptions[this.type] && userPlotOptions[this.type].tooltip, itemOptions.tooltip ); // Delete marker object if not allowed (#1125) if (typeOptions.marker === null) { delete options.marker; } // Handle color zones this.zoneAxis = options.zoneAxis; zones = this.zones = (options.zones || []).slice(); if ((options.negativeColor || options.negativeFillColor) && !options.zones) { zones.push({ value: options[this.zoneAxis + 'Threshold'] || options.threshold || 0, color: options.negativeColor, fillColor: options.negativeFillColor }); } if (zones.length) { // Push one extra zone for the rest if (defined(zones[zones.length - 1].value)) { zones.push({ color: this.color, fillColor: this.fillColor }); } } return options; }, getCyclic: function (prop, value, defaults) { var i, userOptions = this.userOptions, indexName = '_' + prop + 'Index', counterName = prop + 'Counter'; if (!value) { if (defined(userOptions[indexName])) { // after Series.update() i = userOptions[indexName]; } else { userOptions[indexName] = i = this.chart[counterName] % defaults.length; this.chart[counterName] += 1; } value = defaults[i]; } this[prop] = value; }, /** * Get the series' color */ getColor: function () { if (this.options.colorByPoint) { this.options.color = null; // #4359, selected slice got series.color even when colorByPoint was set. } else { this.getCyclic('color', this.options.color || defaultPlotOptions[this.type].color, this.chart.options.colors); } }, /** * Get the series' symbol */ getSymbol: function () { var seriesMarkerOption = this.options.marker; this.getCyclic('symbol', seriesMarkerOption.symbol, this.chart.options.symbols); // don't substract radius in image symbols (#604) if (/^url/.test(this.symbol)) { seriesMarkerOption.radius = 0; } }, drawLegendSymbol: LegendSymbolMixin.drawLineMarker, /** * Replace the series data with a new set of data * @param {Object} data * @param {Object} redraw */ setData: function (data, redraw, animation, updatePoints) { var series = this, oldData = series.points, oldDataLength = (oldData && oldData.length) || 0, dataLength, options = series.options, chart = series.chart, firstPoint = null, xAxis = series.xAxis, hasCategories = xAxis && !!xAxis.categories, i, turboThreshold = options.turboThreshold, pt, xData = this.xData, yData = this.yData, pointArrayMap = series.pointArrayMap, valueCount = pointArrayMap && pointArrayMap.length; data = data || []; dataLength = data.length; redraw = pick(redraw, true); // If the point count is the same as is was, just run Point.update which is // cheaper, allows animation, and keeps references to points. if (updatePoints !== false && dataLength && oldDataLength === dataLength && !series.cropped && !series.hasGroupedData && series.visible) { each(data, function (point, i) { // .update doesn't exist on a linked, hidden series (#3709) if (oldData[i].update && point !== options.data[i]) { oldData[i].update(point, false, null, false); } }); } else { // Reset properties series.xIncrement = null; series.colorCounter = 0; // for series with colorByPoint (#1547) // Update parallel arrays each(this.parallelArrays, function (key) { series[key + 'Data'].length = 0; }); // In turbo mode, only one- or twodimensional arrays of numbers are allowed. The // first value is tested, and we assume that all the rest are defined the same // way. Although the 'for' loops are similar, they are repeated inside each // if-else conditional for max performance. if (turboThreshold && dataLength > turboThreshold) { // find the first non-null point i = 0; while (firstPoint === null && i < dataLength) { firstPoint = data[i]; i++; } if (isNumber(firstPoint)) { // assume all points are numbers var x = pick(options.pointStart, 0), pointInterval = pick(options.pointInterval, 1); for (i = 0; i < dataLength; i++) { xData[i] = x; yData[i] = data[i]; x += pointInterval; } series.xIncrement = x; } else if (isArray(firstPoint)) { // assume all points are arrays if (valueCount) { // [x, low, high] or [x, o, h, l, c] for (i = 0; i < dataLength; i++) { pt = data[i]; xData[i] = pt[0]; yData[i] = pt.slice(1, valueCount + 1); } } else { // [x, y] for (i = 0; i < dataLength; i++) { pt = data[i]; xData[i] = pt[0]; yData[i] = pt[1]; } } } else { error(12); // Highcharts expects configs to be numbers or arrays in turbo mode } } else { for (i = 0; i < dataLength; i++) { if (data[i] !== UNDEFINED) { // stray commas in oldIE pt = { series: series }; series.pointClass.prototype.applyOptions.apply(pt, [data[i]]); series.updateParallelArrays(pt, i); if (hasCategories && defined(pt.name)) { // #4401 xAxis.names[pt.x] = pt.name; // #2046 } } } } // Forgetting to cast strings to numbers is a common caveat when handling CSV or JSON if (isString(yData[0])) { error(14, true); } series.data = []; series.options.data = series.userOptions.data = data; // destroy old points i = oldDataLength; while (i--) { if (oldData[i] && oldData[i].destroy) { oldData[i].destroy(); } } // reset minRange (#878) if (xAxis) { xAxis.minRange = xAxis.userMinRange; } // redraw series.isDirty = series.isDirtyData = chart.isDirtyBox = true; animation = false; } // Typically for pie series, points need to be processed and generated // prior to rendering the legend if (options.legendType === 'point') { this.processData(); this.generatePoints(); } if (redraw) { chart.redraw(animation); } }, /** * Process the data by cropping away unused data points if the series is longer * than the crop threshold. This saves computing time for lage series. */ processData: function (force) { var series = this, processedXData = series.xData, // copied during slice operation below processedYData = series.yData, dataLength = processedXData.length, croppedData, cropStart = 0, cropped, distance, closestPointRange, xAxis = series.xAxis, i, // loop variable options = series.options, cropThreshold = options.cropThreshold, getExtremesFromAll = series.getExtremesFromAll || options.getExtremesFromAll, // #4599 isCartesian = series.isCartesian, xExtremes, val2lin = xAxis && xAxis.val2lin, isLog = xAxis && xAxis.isLog, min, max; // If the series data or axes haven't changed, don't go through this. Return false to pass // the message on to override methods like in data grouping. if (isCartesian && !series.isDirty && !xAxis.isDirty && !series.yAxis.isDirty && !force) { return false; } if (xAxis) { xExtremes = xAxis.getExtremes(); // corrected for log axis (#3053) min = xExtremes.min; max = xExtremes.max; } // optionally filter out points outside the plot area if (isCartesian && series.sorted && !getExtremesFromAll && (!cropThreshold || dataLength > cropThreshold || series.forceCrop)) { // it's outside current extremes if (processedXData[dataLength - 1] < min || processedXData[0] > max) { processedXData = []; processedYData = []; // only crop if it's actually spilling out } else if (processedXData[0] < min || processedXData[dataLength - 1] > max) { croppedData = this.cropData(series.xData, series.yData, min, max); processedXData = croppedData.xData; processedYData = croppedData.yData; cropStart = croppedData.start; cropped = true; } } // Find the closest distance between processed points i = processedXData.length || 1; while (--i) { distance = isLog ? val2lin(processedXData[i]) - val2lin(processedXData[i - 1]) : processedXData[i] - processedXData[i - 1]; if (distance > 0 && (closestPointRange === UNDEFINED || distance < closestPointRange)) { closestPointRange = distance; // Unsorted data is not supported by the line tooltip, as well as data grouping and // navigation in Stock charts (#725) and width calculation of columns (#1900) } else if (distance < 0 && series.requireSorting) { error(15); } } // Record the properties series.cropped = cropped; // undefined or true series.cropStart = cropStart; series.processedXData = processedXData; series.processedYData = processedYData; series.closestPointRange = closestPointRange; }, /** * Iterate over xData and crop values between min and max. Returns object containing crop start/end * cropped xData with corresponding part of yData, dataMin and dataMax within the cropped range */ cropData: function (xData, yData, min, max) { var dataLength = xData.length, cropStart = 0, cropEnd = dataLength, cropShoulder = pick(this.cropShoulder, 1), // line-type series need one point outside i, j; // iterate up to find slice start for (i = 0; i < dataLength; i++) { if (xData[i] >= min) { cropStart = mathMax(0, i - cropShoulder); break; } } // proceed to find slice end for (j = i; j < dataLength; j++) { if (xData[j] > max) { cropEnd = j + cropShoulder; break; } } return { xData: xData.slice(cropStart, cropEnd), yData: yData.slice(cropStart, cropEnd), start: cropStart, end: cropEnd }; }, /** * Generate the data point after the data has been processed by cropping away * unused points and optionally grouped in Highcharts Stock. */ generatePoints: function () { var series = this, options = series.options, dataOptions = options.data, data = series.data, dataLength, processedXData = series.processedXData, processedYData = series.processedYData, pointClass = series.pointClass, processedDataLength = processedXData.length, cropStart = series.cropStart || 0, cursor, hasGroupedData = series.hasGroupedData, point, points = [], i; if (!data && !hasGroupedData) { var arr = []; arr.length = dataOptions.length; data = series.data = arr; } for (i = 0; i < processedDataLength; i++) { cursor = cropStart + i; if (!hasGroupedData) { if (data[cursor]) { point = data[cursor]; } else if (dataOptions[cursor] !== UNDEFINED) { // #970 data[cursor] = point = (new pointClass()).init(series, dataOptions[cursor], processedXData[i]); } points[i] = point; } else { // splat the y data in case of ohlc data array points[i] = (new pointClass()).init(series, [processedXData[i]].concat(splat(processedYData[i]))); } points[i].index = cursor; // For faster access in Point.update } // Hide cropped-away points - this only runs when the number of points is above cropThreshold, or when // swithching view from non-grouped data to grouped data (#637) if (data && (processedDataLength !== (dataLength = data.length) || hasGroupedData)) { for (i = 0; i < dataLength; i++) { if (i === cropStart && !hasGroupedData) { // when has grouped data, clear all points i += processedDataLength; } if (data[i]) { data[i].destroyElements(); data[i].plotX = UNDEFINED; // #1003 } } } series.data = data; series.points = points; }, /** * Calculate Y extremes for visible data */ getExtremes: function (yData) { var xAxis = this.xAxis, yAxis = this.yAxis, xData = this.processedXData, yDataLength, activeYData = [], activeCounter = 0, xExtremes = xAxis.getExtremes(), // #2117, need to compensate for log X axis xMin = xExtremes.min, xMax = xExtremes.max, validValue, withinRange, x, y, i, j; yData = yData || this.stackedYData || this.processedYData; yDataLength = yData.length; for (i = 0; i < yDataLength; i++) { x = xData[i]; y = yData[i]; // For points within the visible range, including the first point outside the // visible range, consider y extremes validValue = y !== null && y !== UNDEFINED && (!yAxis.isLog || (y.length || y > 0)); withinRange = this.getExtremesFromAll || this.options.getExtremesFromAll || this.cropped || ((xData[i + 1] || x) >= xMin && (xData[i - 1] || x) <= xMax); if (validValue && withinRange) { j = y.length; if (j) { // array, like ohlc or range data while (j--) { if (y[j] !== null) { activeYData[activeCounter++] = y[j]; } } } else { activeYData[activeCounter++] = y; } } } this.dataMin = arrayMin(activeYData); this.dataMax = arrayMax(activeYData); }, /** * Translate data points from raw data values to chart specific positioning data * needed later in drawPoints, drawGraph and drawTracker. */ translate: function () { if (!this.processedXData) { // hidden series this.processData(); } this.generatePoints(); var series = this, options = series.options, stacking = options.stacking, xAxis = series.xAxis, categories = xAxis.categories, yAxis = series.yAxis, points = series.points, dataLength = points.length, hasModifyValue = !!series.modifyValue, i, pointPlacement = options.pointPlacement, dynamicallyPlaced = pointPlacement === 'between' || isNumber(pointPlacement), threshold = options.threshold, stackThreshold = options.startFromThreshold ? threshold : 0, plotX, plotY, lastPlotX, stackIndicator, closestPointRangePx = Number.MAX_VALUE; // Translate each point for (i = 0; i < dataLength; i++) { var point = points[i], xValue = point.x, yValue = point.y, yBottom = point.low, stack = stacking && yAxis.stacks[(series.negStacks && yValue < (stackThreshold ? 0 : threshold) ? '-' : '') + series.stackKey], pointStack, stackValues; // Discard disallowed y values for log axes (#3434) if (yAxis.isLog && yValue !== null && yValue <= 0) { point.y = yValue = null; error(10); } // Get the plotX translation point.plotX = plotX = mathMin(mathMax(-1e5, xAxis.translate(xValue, 0, 0, 0, 1, pointPlacement, this.type === 'flags')), 1e5); // #3923 // Calculate the bottom y value for stacked series if (stacking && series.visible && !point.isNull && stack && stack[xValue]) { stackIndicator = series.getStackIndicator(stackIndicator, xValue, series.index); pointStack = stack[xValue]; stackValues = pointStack.points[stackIndicator.key]; yBottom = stackValues[0]; yValue = stackValues[1]; if (yBottom === stackThreshold) { yBottom = pick(threshold, yAxis.min); } if (yAxis.isLog && yBottom <= 0) { // #1200, #1232 yBottom = null; } point.total = point.stackTotal = pointStack.total; point.percentage = pointStack.total && (point.y / pointStack.total * 100); point.stackY = yValue; // Place the stack label pointStack.setOffset(series.pointXOffset || 0, series.barW || 0); } // Set translated yBottom or remove it point.yBottom = defined(yBottom) ? yAxis.translate(yBottom, 0, 1, 0, 1) : null; // general hook, used for Highstock compare mode if (hasModifyValue) { yValue = series.modifyValue(yValue, point); } // Set the the plotY value, reset it for redraws point.plotY = plotY = (typeof yValue === 'number' && yValue !== Infinity) ? mathMin(mathMax(-1e5, yAxis.translate(yValue, 0, 1, 0, 1)), 1e5) : // #3201 UNDEFINED; point.isInside = plotY !== UNDEFINED && plotY >= 0 && plotY <= yAxis.len && // #3519 plotX >= 0 && plotX <= xAxis.len; // Set client related positions for mouse tracking point.clientX = dynamicallyPlaced ? xAxis.translate(xValue, 0, 0, 0, 1) : plotX; // #1514 point.negative = point.y < (threshold || 0); // some API data point.category = categories && categories[point.x] !== UNDEFINED ? categories[point.x] : point.x; // Determine auto enabling of markers (#3635) if (i) { closestPointRangePx = mathMin(closestPointRangePx, mathAbs(plotX - lastPlotX)); } lastPlotX = plotX; } series.closestPointRangePx = closestPointRangePx; }, /** * Return the series points with null points filtered out */ getValidPoints: function (points) { return grep(points || this.points, function (point) { return !point.isNull; }); }, /** * Set the clipping for the series. For animated series it is called twice, first to initiate * animating the clip then the second time without the animation to set the final clip. */ setClip: function (animation) { var chart = this.chart, options = this.options, renderer = chart.renderer, inverted = chart.inverted, seriesClipBox = this.clipBox, clipBox = seriesClipBox || chart.clipBox, sharedClipKey = this.sharedClipKey || ['_sharedClip', animation && animation.duration, animation && animation.easing, clipBox.height, options.xAxis, options.yAxis].join(','), // #4526 clipRect = chart[sharedClipKey], markerClipRect = chart[sharedClipKey + 'm']; // If a clipping rectangle with the same properties is currently present in the chart, use that. if (!clipRect) { // When animation is set, prepare the initial positions if (animation) { clipBox.width = 0; chart[sharedClipKey + 'm'] = markerClipRect = renderer.clipRect( -99, // include the width of the first marker inverted ? -chart.plotLeft : -chart.plotTop, 99, inverted ? chart.chartWidth : chart.chartHeight ); } chart[sharedClipKey] = clipRect = renderer.clipRect(clipBox); } if (animation) { clipRect.count += 1; } if (options.clip !== false) { this.group.clip(animation || seriesClipBox ? clipRect : chart.clipRect); this.markerGroup.clip(markerClipRect); this.sharedClipKey = sharedClipKey; } // Remove the shared clipping rectangle when all series are shown if (!animation) { clipRect.count -= 1; if (clipRect.count <= 0 && sharedClipKey && chart[sharedClipKey]) { if (!seriesClipBox) { chart[sharedClipKey] = chart[sharedClipKey].destroy(); } if (chart[sharedClipKey + 'm']) { chart[sharedClipKey + 'm'] = chart[sharedClipKey + 'm'].destroy(); } } } }, /** * Animate in the series */ animate: function (init) { var series = this, chart = series.chart, clipRect, animation = series.options.animation, sharedClipKey; // Animation option is set to true if (animation && !isObject(animation)) { animation = defaultPlotOptions[series.type].animation; } // Initialize the animation. Set up the clipping rectangle. if (init) { series.setClip(animation); // Run the animation } else { sharedClipKey = this.sharedClipKey; clipRect = chart[sharedClipKey]; if (clipRect) { clipRect.animate({ width: chart.plotSizeX }, animation); } if (chart[sharedClipKey + 'm']) { chart[sharedClipKey + 'm'].animate({ width: chart.plotSizeX + 99 }, animation); } // Delete this function to allow it only once series.animate = null; } }, /** * This runs after animation to land on the final plot clipping */ afterAnimate: function () { this.setClip(); fireEvent(this, 'afterAnimate'); }, /** * Draw the markers */ drawPoints: function () { var series = this, pointAttr, points = series.points, chart = series.chart, plotX, plotY, i, point, radius, symbol, isImage, graphic, options = series.options, seriesMarkerOptions = options.marker, seriesPointAttr = series.pointAttr[''], pointMarkerOptions, hasPointMarker, enabled, isInside, markerGroup = series.markerGroup, xAxis = series.xAxis, globallyEnabled = pick( seriesMarkerOptions.enabled, xAxis.isRadial, series.closestPointRangePx > 2 * seriesMarkerOptions.radius ); if (seriesMarkerOptions.enabled !== false || series._hasPointMarkers) { i = points.length; while (i--) { point = points[i]; plotX = mathFloor(point.plotX); // #1843 plotY = point.plotY; graphic = point.graphic; pointMarkerOptions = point.marker || {}; hasPointMarker = !!point.marker; enabled = (globallyEnabled && pointMarkerOptions.enabled === UNDEFINED) || pointMarkerOptions.enabled; isInside = point.isInside; // only draw the point if y is defined if (enabled && plotY !== UNDEFINED && !isNaN(plotY) && point.y !== null) { // shortcuts pointAttr = point.pointAttr[point.selected ? SELECT_STATE : NORMAL_STATE] || seriesPointAttr; radius = pointAttr.r; symbol = pick(pointMarkerOptions.symbol, series.symbol); isImage = symbol.indexOf('url') === 0; if (graphic) { // update graphic[isInside ? 'show' : 'hide'](true) // Since the marker group isn't clipped, each individual marker must be toggled .attr(pointAttr) // #4759 .animate(extend({ x: plotX - radius, y: plotY - radius }, graphic.symbolName ? { // don't apply to image symbols #507 width: 2 * radius, height: 2 * radius } : {})); } else if (isInside && (radius > 0 || isImage)) { point.graphic = graphic = chart.renderer.symbol( symbol, plotX - radius, plotY - radius, 2 * radius, 2 * radius, hasPointMarker ? pointMarkerOptions : seriesMarkerOptions ) .attr(pointAttr) .add(markerGroup); } } else if (graphic) { point.graphic = graphic.destroy(); // #1269 } } } }, /** * Convert state properties from API naming conventions to SVG attributes * * @param {Object} options API options object * @param {Object} base1 SVG attribute object to inherit from * @param {Object} base2 Second level SVG attribute object to inherit from */ convertAttribs: function (options, base1, base2, base3) { var conversion = this.pointAttrToOptions, attr, option, obj = {}; options = options || {}; base1 = base1 || {}; base2 = base2 || {}; base3 = base3 || {}; for (attr in conversion) { option = conversion[attr]; obj[attr] = pick(options[option], base1[attr], base2[attr], base3[attr]); } return obj; }, /** * Get the state attributes. Each series type has its own set of attributes * that are allowed to change on a point's state change. Series wide attributes are stored for * all series, and additionally point specific attributes are stored for all * points with individual marker options. If such options are not defined for the point, * a reference to the series wide attributes is stored in point.pointAttr. */ getAttribs: function () { var series = this, seriesOptions = series.options, normalOptions = defaultPlotOptions[series.type].marker ? seriesOptions.marker : seriesOptions, stateOptions = normalOptions.states, stateOptionsHover = stateOptions[HOVER_STATE], pointStateOptionsHover, seriesColor = series.color, seriesNegativeColor = series.options.negativeColor, normalDefaults = { stroke: seriesColor, fill: seriesColor }, points = series.points || [], // #927 i, j, threshold, point, seriesPointAttr = [], pointAttr, pointAttrToOptions = series.pointAttrToOptions, hasPointSpecificOptions = series.hasPointSpecificOptions, defaultLineColor = normalOptions.lineColor, defaultFillColor = normalOptions.fillColor, turboThreshold = seriesOptions.turboThreshold, zones = series.zones, zoneAxis = series.zoneAxis || 'y', attr, key; // series type specific modifications if (seriesOptions.marker) { // line, spline, area, areaspline, scatter // if no hover radius is given, default to normal radius + 2 stateOptionsHover.radius = stateOptionsHover.radius || normalOptions.radius + stateOptionsHover.radiusPlus; stateOptionsHover.lineWidth = stateOptionsHover.lineWidth || normalOptions.lineWidth + stateOptionsHover.lineWidthPlus; } else { // column, bar, pie // if no hover color is given, brighten the normal color stateOptionsHover.color = stateOptionsHover.color || Color(stateOptionsHover.color || seriesColor) .brighten(stateOptionsHover.brightness).get(); // if no hover negativeColor is given, brighten the normal negativeColor stateOptionsHover.negativeColor = stateOptionsHover.negativeColor || Color(stateOptionsHover.negativeColor || seriesNegativeColor) .brighten(stateOptionsHover.brightness).get(); } // general point attributes for the series normal state seriesPointAttr[NORMAL_STATE] = series.convertAttribs(normalOptions, normalDefaults); // HOVER_STATE and SELECT_STATE states inherit from normal state except the default radius each([HOVER_STATE, SELECT_STATE], function (state) { seriesPointAttr[state] = series.convertAttribs(stateOptions[state], seriesPointAttr[NORMAL_STATE]); }); // set it series.pointAttr = seriesPointAttr; // Generate the point-specific attribute collections if specific point // options are given. If not, create a referance to the series wide point // attributes i = points.length; if (!turboThreshold || i < turboThreshold || hasPointSpecificOptions) { while (i--) { point = points[i]; normalOptions = (point.options && point.options.marker) || point.options; if (normalOptions && normalOptions.enabled === false) { normalOptions.radius = 0; } if (zones.length) { j = 0; threshold = zones[j]; while (point[zoneAxis] >= threshold.value) { threshold = zones[++j]; } point.color = point.fillColor = pick(threshold.color, series.color); // #3636, #4267, #4430 - inherit color from series, when color is undefined } hasPointSpecificOptions = seriesOptions.colorByPoint || point.color; // #868 // check if the point has specific visual options if (point.options) { for (key in pointAttrToOptions) { if (defined(normalOptions[pointAttrToOptions[key]])) { hasPointSpecificOptions = true; } } } // a specific marker config object is defined for the individual point: // create it's own attribute collection if (hasPointSpecificOptions) { normalOptions = normalOptions || {}; pointAttr = []; stateOptions = normalOptions.states || {}; // reassign for individual point pointStateOptionsHover = stateOptions[HOVER_STATE] = stateOptions[HOVER_STATE] || {}; // Handle colors for column and pies if (!seriesOptions.marker || (point.negative && !pointStateOptionsHover.fillColor && !stateOptionsHover.fillColor)) { // column, bar, point or negative threshold for series with markers (#3636) // If no hover color is given, brighten the normal color. #1619, #2579 pointStateOptionsHover[series.pointAttrToOptions.fill] = pointStateOptionsHover.color || (!point.options.color && stateOptionsHover[(point.negative && seriesNegativeColor ? 'negativeColor' : 'color')]) || Color(point.color) .brighten(pointStateOptionsHover.brightness || stateOptionsHover.brightness) .get(); } // normal point state inherits series wide normal state attr = { color: point.color }; // #868 if (!defaultFillColor) { // Individual point color or negative color markers (#2219) attr.fillColor = point.color; } if (!defaultLineColor) { attr.lineColor = point.color; // Bubbles take point color, line markers use white } // Color is explicitly set to null or undefined (#1288, #4068) if (normalOptions.hasOwnProperty('color') && !normalOptions.color) { delete normalOptions.color; } pointAttr[NORMAL_STATE] = series.convertAttribs(extend(attr, normalOptions), seriesPointAttr[NORMAL_STATE]); // inherit from point normal and series hover pointAttr[HOVER_STATE] = series.convertAttribs( stateOptions[HOVER_STATE], seriesPointAttr[HOVER_STATE], pointAttr[NORMAL_STATE] ); // inherit from point normal and series hover pointAttr[SELECT_STATE] = series.convertAttribs( stateOptions[SELECT_STATE], seriesPointAttr[SELECT_STATE], pointAttr[NORMAL_STATE] ); // no marker config object is created: copy a reference to the series-wide // attribute collection } else { pointAttr = seriesPointAttr; } point.pointAttr = pointAttr; } } }, /** * Clear DOM objects and free up memory */ destroy: function () { var series = this, chart = series.chart, issue134 = /AppleWebKit\/533/.test(userAgent), destroy, i, data = series.data || [], point, prop, axis; // add event hook fireEvent(series, 'destroy'); // remove all events removeEvent(series); // erase from axes each(series.axisTypes || [], function (AXIS) { axis = series[AXIS]; if (axis) { erase(axis.series, series); axis.isDirty = axis.forceRedraw = true; } }); // remove legend items if (series.legendItem) { series.chart.legend.destroyItem(series); } // destroy all points with their elements i = data.length; while (i--) { point = data[i]; if (point && point.destroy) { point.destroy(); } } series.points = null; // Clear the animation timeout if we are destroying the series during initial animation clearTimeout(series.animationTimeout); // Destroy all SVGElements associated to the series for (prop in series) { if (series[prop] instanceof SVGElement && !series[prop].survive) { // Survive provides a hook for not destroying // issue 134 workaround destroy = issue134 && prop === 'group' ? 'hide' : 'destroy'; series[prop][destroy](); } } // remove from hoverSeries if (chart.hoverSeries === series) { chart.hoverSeries = null; } erase(chart.series, series); // clear all members for (prop in series) { delete series[prop]; } }, /** * Get the graph path */ getGraphPath: function (points, nullsAsZeroes, connectCliffs) { var series = this, options = series.options, step = options.step, reversed, graphPath = [], gap; points = points || series.points; // Bottom of a stack is reversed reversed = points.reversed; if (reversed) { points.reverse(); } // Reverse the steps (#5004) step = { right: 1, center: 2 }[step] || (step && 3); if (step && reversed) { step = 4 - step; } // Remove invalid points, especially in spline (#5015) if (options.connectNulls && !nullsAsZeroes && !connectCliffs) { points = this.getValidPoints(points); } // Build the line each(points, function (point, i) { var plotX = point.plotX, plotY = point.plotY, lastPoint = points[i - 1], pathToPoint; // the path to this point from the previous if ((point.leftCliff || (lastPoint && lastPoint.rightCliff)) && !connectCliffs) { gap = true; // ... and continue } // Line series, nullsAsZeroes is not handled if (point.isNull && !defined(nullsAsZeroes) && i > 0) { gap = !options.connectNulls; // Area series, nullsAsZeroes is set } else if (point.isNull && !nullsAsZeroes) { gap = true; } else { if (i === 0 || gap) { pathToPoint = [M, point.plotX, point.plotY]; } else if (series.getPointSpline) { // generate the spline as defined in the SplineSeries object pathToPoint = series.getPointSpline(points, point, i); } else if (step) { if (step === 1) { // right pathToPoint = [ L, lastPoint.plotX, plotY ]; } else if (step === 2) { // center pathToPoint = [ L, (lastPoint.plotX + plotX) / 2, lastPoint.plotY, L, (lastPoint.plotX + plotX) / 2, plotY ]; } else { pathToPoint = [ L, plotX, lastPoint.plotY ]; } pathToPoint.push(L, plotX, plotY); } else { // normal line to next point pathToPoint = [ L, plotX, plotY ]; } graphPath.push.apply(graphPath, pathToPoint); gap = false; } }); series.graphPath = graphPath; return graphPath; }, /** * Draw the actual graph */ drawGraph: function () { var series = this, options = this.options, props = [['graph', options.lineColor || this.color, options.dashStyle]], lineWidth = options.lineWidth, roundCap = options.linecap !== 'square', graphPath = (this.gappedPath || this.getGraphPath).call(this), fillColor = (this.fillGraph && this.color) || NONE, // polygon series use filled graph zones = this.zones; each(zones, function (threshold, i) { props.push(['zoneGraph' + i, threshold.color || series.color, threshold.dashStyle || options.dashStyle]); }); // Draw the graph each(props, function (prop, i) { var graphKey = prop[0], graph = series[graphKey], attribs; if (graph) { graph.animate({ d: graphPath }); } else if ((lineWidth || fillColor) && graphPath.length) { // #1487 attribs = { stroke: prop[1], 'stroke-width': lineWidth, fill: fillColor, zIndex: 1 // #1069 }; if (prop[2]) { attribs.dashstyle = prop[2]; } else if (roundCap) { attribs['stroke-linecap'] = attribs['stroke-linejoin'] = 'round'; } series[graphKey] = series.chart.renderer.path(graphPath) .attr(attribs) .add(series.group) .shadow((i < 2) && options.shadow); // add shadow to normal series (0) or to first zone (1) #3932 } }); }, /** * Clip the graphs into the positive and negative coloured graphs */ applyZones: function () { var series = this, chart = this.chart, renderer = chart.renderer, zones = this.zones, translatedFrom, translatedTo, clips = this.clips || [], clipAttr, graph = this.graph, area = this.area, chartSizeMax = mathMax(chart.chartWidth, chart.chartHeight), axis = this[(this.zoneAxis || 'y') + 'Axis'], extremes, reversed = axis.reversed, inverted = chart.inverted, horiz = axis.horiz, pxRange, pxPosMin, pxPosMax, ignoreZones = false; if (zones.length && (graph || area) && axis.min !== UNDEFINED) { // The use of the Color Threshold assumes there are no gaps // so it is safe to hide the original graph and area if (graph) { graph.hide(); } if (area) { area.hide(); } // Create the clips extremes = axis.getExtremes(); each(zones, function (threshold, i) { translatedFrom = reversed ? (horiz ? chart.plotWidth : 0) : (horiz ? 0 : axis.toPixels(extremes.min)); translatedFrom = mathMin(mathMax(pick(translatedTo, translatedFrom), 0), chartSizeMax); translatedTo = mathMin(mathMax(mathRound(axis.toPixels(pick(threshold.value, extremes.max), true)), 0), chartSizeMax); if (ignoreZones) { translatedFrom = translatedTo = axis.toPixels(extremes.max); } pxRange = Math.abs(translatedFrom - translatedTo); pxPosMin = mathMin(translatedFrom, translatedTo); pxPosMax = mathMax(translatedFrom, translatedTo); if (axis.isXAxis) { clipAttr = { x: inverted ? pxPosMax : pxPosMin, y: 0, width: pxRange, height: chartSizeMax }; if (!horiz) { clipAttr.x = chart.plotHeight - clipAttr.x; } } else { clipAttr = { x: 0, y: inverted ? pxPosMax : pxPosMin, width: chartSizeMax, height: pxRange }; if (horiz) { clipAttr.y = chart.plotWidth - clipAttr.y; } } /// VML SUPPPORT if (chart.inverted && renderer.isVML) { if (axis.isXAxis) { clipAttr = { x: 0, y: reversed ? pxPosMin : pxPosMax, height: clipAttr.width, width: chart.chartWidth }; } else { clipAttr = { x: clipAttr.y - chart.plotLeft - chart.spacingBox.x, y: 0, width: clipAttr.height, height: chart.chartHeight }; } } /// END OF VML SUPPORT if (clips[i]) { clips[i].animate(clipAttr); } else { clips[i] = renderer.clipRect(clipAttr); if (graph) { series['zoneGraph' + i].clip(clips[i]); } if (area) { series['zoneArea' + i].clip(clips[i]); } } // if this zone extends out of the axis, ignore the others ignoreZones = threshold.value > extremes.max; }); this.clips = clips; } }, /** * Initialize and perform group inversion on series.group and series.markerGroup */ invertGroups: function () { var series = this, chart = series.chart; // Pie, go away (#1736) if (!series.xAxis) { return; } // A fixed size is needed for inversion to work function setInvert() { var size = { width: series.yAxis.len, height: series.xAxis.len }; each(['group', 'markerGroup'], function (groupName) { if (series[groupName]) { series[groupName].attr(size).invert(); } }); } addEvent(chart, 'resize', setInvert); // do it on resize addEvent(series, 'destroy', function () { removeEvent(chart, 'resize', setInvert); }); // Do it now setInvert(); // do it now // On subsequent render and redraw, just do setInvert without setting up events again series.invertGroups = setInvert; }, /** * General abstraction for creating plot groups like series.group, series.dataLabelsGroup and * series.markerGroup. On subsequent calls, the group will only be adjusted to the updated plot size. */ plotGroup: function (prop, name, visibility, zIndex, parent) { var group = this[prop], isNew = !group; // Generate it on first call if (isNew) { this[prop] = group = this.chart.renderer.g(name) .attr({ zIndex: zIndex || 0.1 // IE8 needs this }) .add(parent); group.addClass('highcharts-series-' + this.index); } // Place it on first and subsequent (redraw) calls group.attr({ visibility: visibility })[isNew ? 'attr' : 'animate'](this.getPlotBox()); return group; }, /** * Get the translation and scale for the plot area of this series */ getPlotBox: function () { var chart = this.chart, xAxis = this.xAxis, yAxis = this.yAxis; // Swap axes for inverted (#2339) if (chart.inverted) { xAxis = yAxis; yAxis = this.xAxis; } return { translateX: xAxis ? xAxis.left : chart.plotLeft, translateY: yAxis ? yAxis.top : chart.plotTop, scaleX: 1, // #1623 scaleY: 1 }; }, /** * Render the graph and markers */ render: function () { var series = this, chart = series.chart, group, options = series.options, animation = options.animation, // Animation doesn't work in IE8 quirks when the group div is hidden, // and looks bad in other oldIE animDuration = (animation && !!series.animate && chart.renderer.isSVG && pick(animation.duration, 500)) || 0, visibility = series.visible ? 'inherit' : 'hidden', // #2597 zIndex = options.zIndex, hasRendered = series.hasRendered, chartSeriesGroup = chart.seriesGroup; // the group group = series.plotGroup( 'group', 'series', visibility, zIndex, chartSeriesGroup ); series.markerGroup = series.plotGroup( 'markerGroup', 'markers', visibility, zIndex, chartSeriesGroup ); // initiate the animation if (animDuration) { series.animate(true); } // cache attributes for shapes series.getAttribs(); // SVGRenderer needs to know this before drawing elements (#1089, #1795) group.inverted = series.isCartesian ? chart.inverted : false; // draw the graph if any if (series.drawGraph) { series.drawGraph(); series.applyZones(); } each(series.points, function (point) { if (point.redraw) { point.redraw(); } }); // draw the data labels (inn pies they go before the points) if (series.drawDataLabels) { series.drawDataLabels(); } // draw the points if (series.visible) { series.drawPoints(); } // draw the mouse tracking area if (series.drawTracker && series.options.enableMouseTracking !== false) { series.drawTracker(); } // Handle inverted series and tracker groups if (chart.inverted) { series.invertGroups(); } // Initial clipping, must be defined after inverting groups for VML. Applies to columns etc. (#3839). if (options.clip !== false && !series.sharedClipKey && !hasRendered) { group.clip(chart.clipRect); } // Run the animation if (animDuration) { series.animate(); } // Call the afterAnimate function on animation complete (but don't overwrite the animation.complete option // which should be available to the user). if (!hasRendered) { series.animationTimeout = syncTimeout(function () { series.afterAnimate(); }, animDuration); } series.isDirty = series.isDirtyData = false; // means data is in accordance with what you see // (See #322) series.isDirty = series.isDirtyData = false; // means data is in accordance with what you see series.hasRendered = true; }, /** * Redraw the series after an update in the axes. */ redraw: function () { var series = this, chart = series.chart, wasDirtyData = series.isDirtyData, // cache it here as it is set to false in render, but used after wasDirty = series.isDirty, group = series.group, xAxis = series.xAxis, yAxis = series.yAxis; // reposition on resize if (group) { if (chart.inverted) { group.attr({ width: chart.plotWidth, height: chart.plotHeight }); } group.animate({ translateX: pick(xAxis && xAxis.left, chart.plotLeft), translateY: pick(yAxis && yAxis.top, chart.plotTop) }); } series.translate(); series.render(); if (wasDirtyData) { fireEvent(series, 'updatedData'); } if (wasDirty || wasDirtyData) { // #3945 recalculate the kdtree when dirty delete this.kdTree; // #3868 recalculate the kdtree with dirty data } }, /** * KD Tree && PointSearching Implementation */ kdDimensions: 1, kdAxisArray: ['clientX', 'plotY'], searchPoint: function (e, compareX) { var series = this, xAxis = series.xAxis, yAxis = series.yAxis, inverted = series.chart.inverted; return this.searchKDTree({ clientX: inverted ? xAxis.len - e.chartY + xAxis.pos : e.chartX - xAxis.pos, plotY: inverted ? yAxis.len - e.chartX + yAxis.pos : e.chartY - yAxis.pos }, compareX); }, buildKDTree: function () { var series = this, dimensions = series.kdDimensions; // Internal function function _kdtree(points, depth, dimensions) { var axis, median, length = points && points.length; if (length) { // alternate between the axis axis = series.kdAxisArray[depth % dimensions]; // sort point array points.sort(function (a, b) { return a[axis] - b[axis]; }); median = Math.floor(length / 2); // build and return nod return { point: points[median], left: _kdtree(points.slice(0, median), depth + 1, dimensions), right: _kdtree(points.slice(median + 1), depth + 1, dimensions) }; } } // Start the recursive build process with a clone of the points array and null points filtered out (#3873) function startRecursive() { series.kdTree = _kdtree(series.getValidPoints(), dimensions, dimensions); } delete series.kdTree; // For testing tooltips, don't build async syncTimeout(startRecursive, series.options.kdNow ? 0 : 1); }, searchKDTree: function (point, compareX) { var series = this, kdX = this.kdAxisArray[0], kdY = this.kdAxisArray[1], kdComparer = compareX ? 'distX' : 'dist'; // Set the one and two dimensional distance on the point object function setDistance(p1, p2) { var x = (defined(p1[kdX]) && defined(p2[kdX])) ? Math.pow(p1[kdX] - p2[kdX], 2) : null, y = (defined(p1[kdY]) && defined(p2[kdY])) ? Math.pow(p1[kdY] - p2[kdY], 2) : null, r = (x || 0) + (y || 0); p2.dist = defined(r) ? Math.sqrt(r) : Number.MAX_VALUE; p2.distX = defined(x) ? Math.sqrt(x) : Number.MAX_VALUE; } function _search(search, tree, depth, dimensions) { var point = tree.point, axis = series.kdAxisArray[depth % dimensions], tdist, sideA, sideB, ret = point, nPoint1, nPoint2; setDistance(search, point); // Pick side based on distance to splitting point tdist = search[axis] - point[axis]; sideA = tdist < 0 ? 'left' : 'right'; sideB = tdist < 0 ? 'right' : 'left'; // End of tree if (tree[sideA]) { nPoint1 = _search(search, tree[sideA], depth + 1, dimensions); ret = (nPoint1[kdComparer] < ret[kdComparer] ? nPoint1 : point); } if (tree[sideB]) { // compare distance to current best to splitting point to decide wether to check side B or not if (Math.sqrt(tdist * tdist) < ret[kdComparer]) { nPoint2 = _search(search, tree[sideB], depth + 1, dimensions); ret = (nPoint2[kdComparer] < ret[kdComparer] ? nPoint2 : ret); } } return ret; } if (!this.kdTree) { this.buildKDTree(); } if (this.kdTree) { return _search(point, this.kdTree, this.kdDimensions, this.kdDimensions); } } }; // end Series prototype // Extend the Chart prototype for dynamic methods extend(Chart.prototype, { /** * Add a series dynamically after time * * @param {Object} options The config options * @param {Boolean} redraw Whether to redraw the chart after adding. Defaults to true. * @param {Boolean|Object} animation Whether to apply animation, and optionally animation * configuration * * @return {Object} series The newly created series object */ addSeries: function (options, redraw, animation) { var series, chart = this; if (options) { redraw = pick(redraw, true); // defaults to true fireEvent(chart, 'addSeries', { options: options }, function () { series = chart.initSeries(options); chart.isDirtyLegend = true; // the series array is out of sync with the display chart.linkSeries(); if (redraw) { chart.redraw(animation); } }); } return series; }, /** * Add an axis to the chart * @param {Object} options The axis option * @param {Boolean} isX Whether it is an X axis or a value axis */ addAxis: function (options, isX, redraw, animation) { var key = isX ? 'xAxis' : 'yAxis', chartOptions = this.options; new Axis(this, merge(options, { // eslint-disable-line no-new index: this[key].length, isX: isX })); // Push the new axis options to the chart options chartOptions[key] = splat(chartOptions[key] || {}); chartOptions[key].push(options); if (pick(redraw, true)) { this.redraw(animation); } }, /** * Dim the chart and show a loading text or symbol * @param {String} str An optional text to show in the loading label instead of the default one */ showLoading: function (str) { var chart = this, options = chart.options, loadingDiv = chart.loadingDiv, loadingOptions = options.loading, setLoadingSize = function () { if (loadingDiv) { css(loadingDiv, { left: chart.plotLeft + PX, top: chart.plotTop + PX, width: chart.plotWidth + PX, height: chart.plotHeight + PX }); } }; // create the layer at the first call if (!loadingDiv) { chart.loadingDiv = loadingDiv = createElement(DIV, { className: PREFIX + 'loading' }, extend(loadingOptions.style, { zIndex: 10, display: NONE }), chart.container); chart.loadingSpan = createElement( 'span', null, loadingOptions.labelStyle, loadingDiv ); addEvent(chart, 'redraw', setLoadingSize); // #1080 } // update text chart.loadingSpan.innerHTML = str || options.lang.loading; // show it if (!chart.loadingShown) { css(loadingDiv, { opacity: 0, display: '' }); animate(loadingDiv, { opacity: loadingOptions.style.opacity }, { duration: loadingOptions.showDuration || 0 }); chart.loadingShown = true; } setLoadingSize(); }, /** * Hide the loading layer */ hideLoading: function () { var options = this.options, loadingDiv = this.loadingDiv; if (loadingDiv) { animate(loadingDiv, { opacity: 0 }, { duration: options.loading.hideDuration || 100, complete: function () { css(loadingDiv, { display: NONE }); } }); } this.loadingShown = false; } }); // extend the Point prototype for dynamic methods extend(Point.prototype, { /** * Update the point with new options (typically x/y data) and optionally redraw the series. * * @param {Object} options Point options as defined in the series.data array * @param {Boolean} redraw Whether to redraw the chart or wait for an explicit call * @param {Boolean|Object} animation Whether to apply animation, and optionally animation * configuration * */ update: function (options, redraw, animation, runEvent) { var point = this, series = point.series, graphic = point.graphic, i, chart = series.chart, seriesOptions = series.options, names = series.xAxis && series.xAxis.names; redraw = pick(redraw, true); function update() { point.applyOptions(options); // Update visuals if (point.y === null && graphic) { // #4146 point.graphic = graphic.destroy(); } if (isObject(options) && !isArray(options)) { // Defer the actual redraw until getAttribs has been called (#3260) point.redraw = function () { if (graphic && graphic.element) { if (options && options.marker && options.marker.symbol) { point.graphic = graphic.destroy(); } } if (options && options.dataLabels && point.dataLabel) { // #2468 point.dataLabel = point.dataLabel.destroy(); } point.redraw = null; }; } // record changes in the parallel arrays i = point.index; series.updateParallelArrays(point, i); if (names && point.name) { names[point.x] = point.name; } // Record the options to options.data. If there is an object from before, // use point options, otherwise use raw options. (#4701) seriesOptions.data[i] = isObject(seriesOptions.data[i]) ? point.options : options; // redraw series.isDirty = series.isDirtyData = true; if (!series.fixedBox && series.hasCartesianSeries) { // #1906, #2320 chart.isDirtyBox = true; } if (seriesOptions.legendType === 'point') { // #1831, #1885 chart.isDirtyLegend = true; } if (redraw) { chart.redraw(animation); } } // Fire the event with a default handler of doing the update if (runEvent === false) { // When called from setData update(); } else { point.firePointEvent('update', { options: options }, update); } }, /** * Remove a point and optionally redraw the series and if necessary the axes * @param {Boolean} redraw Whether to redraw the chart or wait for an explicit call * @param {Boolean|Object} animation Whether to apply animation, and optionally animation * configuration */ remove: function (redraw, animation) { this.series.removePoint(inArray(this, this.series.data), redraw, animation); } }); // Extend the series prototype for dynamic methods extend(Series.prototype, { /** * Add a point dynamically after chart load time * @param {Object} options Point options as given in series.data * @param {Boolean} redraw Whether to redraw the chart or wait for an explicit call * @param {Boolean} shift If shift is true, a point is shifted off the start * of the series as one is appended to the end. * @param {Boolean|Object} animation Whether to apply animation, and optionally animation * configuration */ addPoint: function (options, redraw, shift, animation) { var series = this, seriesOptions = series.options, data = series.data, graph = series.graph, area = series.area, chart = series.chart, names = series.xAxis && series.xAxis.names, currentShift = (graph && graph.shift) || 0, shiftShapes = ['graph', 'area'], dataOptions = seriesOptions.data, point, isInTheMiddle, xData = series.xData, i, x; setAnimation(animation, chart); // Make graph animate sideways if (shift) { i = series.zones.length; while (i--) { shiftShapes.push('zoneGraph' + i, 'zoneArea' + i); } each(shiftShapes, function (shape) { if (series[shape]) { series[shape].shift = currentShift + (seriesOptions.step ? 2 : 1); } }); } if (area) { area.isArea = true; // needed in animation, both with and without shift } // Optional redraw, defaults to true redraw = pick(redraw, true); // Get options and push the point to xData, yData and series.options. In series.generatePoints // the Point instance will be created on demand and pushed to the series.data array. point = { series: series }; series.pointClass.prototype.applyOptions.apply(point, [options]); x = point.x; // Get the insertion point i = xData.length; if (series.requireSorting && x < xData[i - 1]) { isInTheMiddle = true; while (i && xData[i - 1] > x) { i--; } } series.updateParallelArrays(point, 'splice', i, 0, 0); // insert undefined item series.updateParallelArrays(point, i); // update it if (names && point.name) { names[x] = point.name; } dataOptions.splice(i, 0, options); if (isInTheMiddle) { series.data.splice(i, 0, null); series.processData(); } // Generate points to be added to the legend (#1329) if (seriesOptions.legendType === 'point') { series.generatePoints(); } // Shift the first point off the parallel arrays if (shift) { if (data[0] && data[0].remove) { data[0].remove(false); } else { data.shift(); series.updateParallelArrays(point, 'shift'); dataOptions.shift(); } } // redraw series.isDirty = true; series.isDirtyData = true; if (redraw) { series.getAttribs(); // #1937 chart.redraw(); } }, /** * Remove a point (rendered or not), by index */ removePoint: function (i, redraw, animation) { var series = this, data = series.data, point = data[i], points = series.points, chart = series.chart, remove = function () { if (points && points.length === data.length) { // #4935 points.splice(i, 1); } data.splice(i, 1); series.options.data.splice(i, 1); series.updateParallelArrays(point || { series: series }, 'splice', i, 1); if (point) { point.destroy(); } // redraw series.isDirty = true; series.isDirtyData = true; if (redraw) { chart.redraw(); } }; setAnimation(animation, chart); redraw = pick(redraw, true); // Fire the event with a default handler of removing the point if (point) { point.firePointEvent('remove', null, remove); } else { remove(); } }, /** * Remove a series and optionally redraw the chart * * @param {Boolean} redraw Whether to redraw the chart or wait for an explicit call * @param {Boolean|Object} animation Whether to apply animation, and optionally animation * configuration */ remove: function (redraw, animation) { var series = this, chart = series.chart; // Fire the event with a default handler of removing the point fireEvent(series, 'remove', null, function () { // Destroy elements series.destroy(); // Redraw chart.isDirtyLegend = chart.isDirtyBox = true; chart.linkSeries(); if (pick(redraw, true)) { chart.redraw(animation); } }); }, /** * Update the series with a new set of options */ update: function (newOptions, redraw) { var series = this, chart = this.chart, // must use user options when changing type because this.options is merged // in with type specific plotOptions oldOptions = this.userOptions, oldType = this.type, proto = seriesTypes[oldType].prototype, preserve = ['group', 'markerGroup', 'dataLabelsGroup'], n; // If we're changing type or zIndex, create new groups (#3380, #3404) if ((newOptions.type && newOptions.type !== oldType) || newOptions.zIndex !== undefined) { preserve.length = 0; } // Make sure groups are not destroyed (#3094) each(preserve, function (prop) { preserve[prop] = series[prop]; delete series[prop]; }); // Do the merge, with some forced options newOptions = merge(oldOptions, { animation: false, index: this.index, pointStart: this.xData[0] // when updating after addPoint }, { data: this.options.data }, newOptions); // Destroy the series and delete all properties. Reinsert all methods // and properties from the new type prototype (#2270, #3719) this.remove(false); for (n in proto) { this[n] = UNDEFINED; } extend(this, seriesTypes[newOptions.type || oldType].prototype); // Re-register groups (#3094) each(preserve, function (prop) { series[prop] = preserve[prop]; }); this.init(chart, newOptions); chart.linkSeries(); // Links are lost in this.remove (#3028) if (pick(redraw, true)) { chart.redraw(false); } } }); // Extend the Axis.prototype for dynamic methods extend(Axis.prototype, { /** * Update the axis with a new options structure */ update: function (newOptions, redraw) { var chart = this.chart; newOptions = chart.options[this.coll][this.options.index] = merge(this.userOptions, newOptions); this.destroy(true); this._addedPlotLB = this.chart._labelPanes = UNDEFINED; // #1611, #2887, #4314 this.init(chart, extend(newOptions, { events: UNDEFINED })); chart.isDirtyBox = true; if (pick(redraw, true)) { chart.redraw(); } }, /** * Remove the axis from the chart */ remove: function (redraw) { var chart = this.chart, key = this.coll, // xAxis or yAxis axisSeries = this.series, i = axisSeries.length; // Remove associated series (#2687) while (i--) { if (axisSeries[i]) { axisSeries[i].remove(false); } } // Remove the axis erase(chart.axes, this); erase(chart[key], this); chart.options[key].splice(this.options.index, 1); each(chart[key], function (axis, i) { // Re-index, #1706 axis.options.index = i; }); this.destroy(); chart.isDirtyBox = true; if (pick(redraw, true)) { chart.redraw(); } }, /** * Update the axis title by options */ setTitle: function (newTitleOptions, redraw) { this.update({ title: newTitleOptions }, redraw); }, /** * Set new axis categories and optionally redraw * @param {Array} categories * @param {Boolean} redraw */ setCategories: function (categories, redraw) { this.update({ categories: categories }, redraw); } }); /** * LineSeries object */ var LineSeries = extendClass(Series); seriesTypes.line = LineSeries; /** * Set the default options for column */ defaultPlotOptions.column = merge(defaultSeriesOptions, { borderColor: '#FFFFFF', //borderWidth: 1, borderRadius: 0, //colorByPoint: undefined, groupPadding: 0.2, //grouping: true, marker: null, // point options are specified in the base options pointPadding: 0.1, //pointWidth: null, minPointLength: 0, cropThreshold: 50, // when there are more points, they will not animate out of the chart on xAxis.setExtremes pointRange: null, // null means auto, meaning 1 in a categorized axis and least distance between points if not categories states: { hover: { brightness: 0.1, shadow: false, halo: false }, select: { color: '#C0C0C0', borderColor: '#000000', shadow: false } }, dataLabels: { align: null, // auto verticalAlign: null, // auto y: null }, softThreshold: false, startFromThreshold: true, // false doesn't work well: http://jsfiddle.net/highcharts/hz8fopan/14/ stickyTracking: false, tooltip: { distance: 6 }, threshold: 0 }); /** * ColumnSeries object */ var ColumnSeries = extendClass(Series, { type: 'column', pointAttrToOptions: { // mapping between SVG attributes and the corresponding options stroke: 'borderColor', fill: 'color', r: 'borderRadius' }, cropShoulder: 0, directTouch: true, // When tooltip is not shared, this series (and derivatives) requires direct touch/hover. KD-tree does not apply. trackerGroups: ['group', 'dataLabelsGroup'], negStacks: true, // use separate negative stacks, unlike area stacks where a negative // point is substracted from previous (#1910) /** * Initialize the series */ init: function () { Series.prototype.init.apply(this, arguments); var series = this, chart = series.chart; // if the series is added dynamically, force redraw of other // series affected by a new column if (chart.hasRendered) { each(chart.series, function (otherSeries) { if (otherSeries.type === series.type) { otherSeries.isDirty = true; } }); } }, /** * Return the width and x offset of the columns adjusted for grouping, groupPadding, pointPadding, * pointWidth etc. */ getColumnMetrics: function () { var series = this, options = series.options, xAxis = series.xAxis, yAxis = series.yAxis, reversedXAxis = xAxis.reversed, stackKey, stackGroups = {}, columnCount = 0; // Get the total number of column type series. // This is called on every series. Consider moving this logic to a // chart.orderStacks() function and call it on init, addSeries and removeSeries if (options.grouping === false) { columnCount = 1; } else { each(series.chart.series, function (otherSeries) { var otherOptions = otherSeries.options, otherYAxis = otherSeries.yAxis, columnIndex; if (otherSeries.type === series.type && otherSeries.visible && yAxis.len === otherYAxis.len && yAxis.pos === otherYAxis.pos) { // #642, #2086 if (otherOptions.stacking) { stackKey = otherSeries.stackKey; if (stackGroups[stackKey] === UNDEFINED) { stackGroups[stackKey] = columnCount++; } columnIndex = stackGroups[stackKey]; } else if (otherOptions.grouping !== false) { // #1162 columnIndex = columnCount++; } otherSeries.columnIndex = columnIndex; } }); } var categoryWidth = mathMin( mathAbs(xAxis.transA) * (xAxis.ordinalSlope || options.pointRange || xAxis.closestPointRange || xAxis.tickInterval || 1), // #2610 xAxis.len // #1535 ), groupPadding = categoryWidth * options.groupPadding, groupWidth = categoryWidth - 2 * groupPadding, pointOffsetWidth = groupWidth / columnCount, pointWidth = mathMin( options.maxPointWidth || xAxis.len, pick(options.pointWidth, pointOffsetWidth * (1 - 2 * options.pointPadding)) ), pointPadding = (pointOffsetWidth - pointWidth) / 2, colIndex = (series.columnIndex || 0) + (reversedXAxis ? 1 : 0), // #1251, #3737 pointXOffset = pointPadding + (groupPadding + colIndex * pointOffsetWidth - (categoryWidth / 2)) * (reversedXAxis ? -1 : 1); // Save it for reading in linked series (Error bars particularly) series.columnMetrics = { width: pointWidth, offset: pointXOffset }; return series.columnMetrics; }, /** * Make the columns crisp. The edges are rounded to the nearest full pixel. */ crispCol: function (x, y, w, h) { var chart = this.chart, borderWidth = this.borderWidth, xCrisp = -(borderWidth % 2 ? 0.5 : 0), yCrisp = borderWidth % 2 ? 0.5 : 1, right, bottom, fromTop; if (chart.inverted && chart.renderer.isVML) { yCrisp += 1; } // Horizontal. We need to first compute the exact right edge, then round it // and compute the width from there. right = Math.round(x + w) + xCrisp; x = Math.round(x) + xCrisp; w = right - x; // Vertical bottom = Math.round(y + h) + yCrisp; fromTop = mathAbs(y) <= 0.5 && bottom > 0.5; // #4504, #4656 y = Math.round(y) + yCrisp; h = bottom - y; // Top edges are exceptions if (fromTop) { y -= 1; h += 1; } return { x: x, y: y, width: w, height: h }; }, /** * Translate each point to the plot area coordinate system and find shape positions */ translate: function () { var series = this, chart = series.chart, options = series.options, borderWidth = series.borderWidth = pick( options.borderWidth, series.closestPointRange * series.xAxis.transA < 2 ? 0 : 1 // #3635 ), yAxis = series.yAxis, threshold = options.threshold, translatedThreshold = series.translatedThreshold = yAxis.getThreshold(threshold), minPointLength = pick(options.minPointLength, 5), metrics = series.getColumnMetrics(), pointWidth = metrics.width, seriesBarW = series.barW = mathMax(pointWidth, 1 + 2 * borderWidth), // postprocessed for border width pointXOffset = series.pointXOffset = metrics.offset; if (chart.inverted) { translatedThreshold -= 0.5; // #3355 } // When the pointPadding is 0, we want the columns to be packed tightly, so we allow individual // columns to have individual sizes. When pointPadding is greater, we strive for equal-width // columns (#2694). if (options.pointPadding) { seriesBarW = mathCeil(seriesBarW); } Series.prototype.translate.apply(series); // Record the new values each(series.points, function (point) { var yBottom = mathMin(pick(point.yBottom, translatedThreshold), 9e4), // #3575 safeDistance = 999 + mathAbs(yBottom), plotY = mathMin(mathMax(-safeDistance, point.plotY), yAxis.len + safeDistance), // Don't draw too far outside plot area (#1303, #2241, #4264) barX = point.plotX + pointXOffset, barW = seriesBarW, barY = mathMin(plotY, yBottom), up, barH = mathMax(plotY, yBottom) - barY; // Handle options.minPointLength if (mathAbs(barH) < minPointLength) { if (minPointLength) { barH = minPointLength; up = (!yAxis.reversed && !point.negative) || (yAxis.reversed && point.negative); barY = mathAbs(barY - translatedThreshold) > minPointLength ? // stacked yBottom - minPointLength : // keep position translatedThreshold - (up ? minPointLength : 0); // #1485, #4051 } } // Cache for access in polar point.barX = barX; point.pointWidth = pointWidth; // Fix the tooltip on center of grouped columns (#1216, #424, #3648) point.tooltipPos = chart.inverted ? [yAxis.len + yAxis.pos - chart.plotLeft - plotY, series.xAxis.len - barX - barW / 2, barH] : [barX + barW / 2, plotY + yAxis.pos - chart.plotTop, barH]; // Register shape type and arguments to be used in drawPoints point.shapeType = 'rect'; point.shapeArgs = series.crispCol(barX, barY, barW, barH); }); }, getSymbol: noop, /** * Use a solid rectangle like the area series types */ drawLegendSymbol: LegendSymbolMixin.drawRectangle, /** * Columns have no graph */ drawGraph: noop, /** * Draw the columns. For bars, the series.group is rotated, so the same coordinates * apply for columns and bars. This method is inherited by scatter series. * */ drawPoints: function () { var series = this, chart = this.chart, options = series.options, renderer = chart.renderer, animationLimit = options.animationLimit || 250, shapeArgs, pointAttr; // draw the columns each(series.points, function (point) { var plotY = point.plotY, graphic = point.graphic, borderAttr; if (plotY !== UNDEFINED && !isNaN(plotY) && point.y !== null) { shapeArgs = point.shapeArgs; borderAttr = defined(series.borderWidth) ? { 'stroke-width': series.borderWidth } : {}; pointAttr = point.pointAttr[point.selected ? SELECT_STATE : NORMAL_STATE] || series.pointAttr[NORMAL_STATE]; if (graphic) { // update stop(graphic); graphic.attr(borderAttr).attr(pointAttr)[chart.pointCount < animationLimit ? 'animate' : 'attr'](merge(shapeArgs)); // #4267 } else { point.graphic = graphic = renderer[point.shapeType](shapeArgs) .attr(borderAttr) .attr(pointAttr) .add(point.group || series.group) .shadow(options.shadow, null, options.stacking && !options.borderRadius); } } else if (graphic) { point.graphic = graphic.destroy(); // #1269 } }); }, /** * Animate the column heights one by one from zero * @param {Boolean} init Whether to initialize the animation or run it */ animate: function (init) { var series = this, yAxis = this.yAxis, options = series.options, inverted = this.chart.inverted, attr = {}, translatedThreshold; if (hasSVG) { // VML is too slow anyway if (init) { attr.scaleY = 0.001; translatedThreshold = mathMin(yAxis.pos + yAxis.len, mathMax(yAxis.pos, yAxis.toPixels(options.threshold))); if (inverted) { attr.translateX = translatedThreshold - yAxis.len; } else { attr.translateY = translatedThreshold; } series.group.attr(attr); } else { // run the animation attr.scaleY = 1; attr[inverted ? 'translateX' : 'translateY'] = yAxis.pos; series.group.animate(attr, series.options.animation); // delete this function to allow it only once series.animate = null; } } }, /** * Remove this series from the chart */ remove: function () { var series = this, chart = series.chart; // column and bar series affects other series of the same type // as they are either stacked or grouped if (chart.hasRendered) { each(chart.series, function (otherSeries) { if (otherSeries.type === series.type) { otherSeries.isDirty = true; } }); } Series.prototype.remove.apply(series, arguments); } }); seriesTypes.column = ColumnSeries; /** * Set the default options for scatter */ defaultPlotOptions.scatter = merge(defaultSeriesOptions, { lineWidth: 0, marker: { enabled: true // Overrides auto-enabling in line series (#3647) }, tooltip: { headerFormat: '<span style="color:{point.color}">\u25CF</span> <span style="font-size: 10px;"> {series.name}</span><br/>', pointFormat: 'x: <b>{point.x}</b><br/>y: <b>{point.y}</b><br/>' } }); /** * The scatter series class */ var ScatterSeries = extendClass(Series, { type: 'scatter', sorted: false, requireSorting: false, noSharedTooltip: true, trackerGroups: ['group', 'markerGroup', 'dataLabelsGroup'], takeOrdinalPosition: false, // #2342 kdDimensions: 2, drawGraph: function () { if (this.options.lineWidth) { Series.prototype.drawGraph.call(this); } } }); seriesTypes.scatter = ScatterSeries; /** * Draw the data labels */ Series.prototype.drawDataLabels = function () { var series = this, seriesOptions = series.options, cursor = seriesOptions.cursor, options = seriesOptions.dataLabels, points = series.points, pointOptions, generalOptions, hasRendered = series.hasRendered || 0, str, dataLabelsGroup, renderer = series.chart.renderer; if (options.enabled || series._hasPointLabels) { // Process default alignment of data labels for columns if (series.dlProcessOptions) { series.dlProcessOptions(options); } // Create a separate group for the data labels to avoid rotation dataLabelsGroup = series.plotGroup( 'dataLabelsGroup', 'data-labels', options.defer ? HIDDEN : VISIBLE, options.zIndex || 6 ); if (pick(options.defer, true)) { dataLabelsGroup.attr({ opacity: +hasRendered }); // #3300 if (!hasRendered) { addEvent(series, 'afterAnimate', function () { if (series.visible) { // #3023, #3024 dataLabelsGroup.show(); } dataLabelsGroup[seriesOptions.animation ? 'animate' : 'attr']({ opacity: 1 }, { duration: 200 }); }); } } // Make the labels for each point generalOptions = options; each(points, function (point) { var enabled, dataLabel = point.dataLabel, labelConfig, attr, name, rotation, connector = point.connector, isNew = true, style, moreStyle = {}; // Determine if each data label is enabled pointOptions = point.dlOptions || (point.options && point.options.dataLabels); // dlOptions is used in treemaps enabled = pick(pointOptions && pointOptions.enabled, generalOptions.enabled) && point.y !== null; // #2282, #4641 // If the point is outside the plot area, destroy it. #678, #820 if (dataLabel && !enabled) { point.dataLabel = dataLabel.destroy(); // Individual labels are disabled if the are explicitly disabled // in the point options, or if they fall outside the plot area. } else if (enabled) { // Create individual options structure that can be extended without // affecting others options = merge(generalOptions, pointOptions); style = options.style; rotation = options.rotation; // Get the string labelConfig = point.getLabelConfig(); str = options.format ? format(options.format, labelConfig) : options.formatter.call(labelConfig, options); // Determine the color style.color = pick(options.color, style.color, series.color, 'black'); // update existing label if (dataLabel) { if (defined(str)) { dataLabel .attr({ text: str }); isNew = false; } else { // #1437 - the label is shown conditionally point.dataLabel = dataLabel = dataLabel.destroy(); if (connector) { point.connector = connector.destroy(); } } // create new label } else if (defined(str)) { attr = { //align: align, fill: options.backgroundColor, stroke: options.borderColor, 'stroke-width': options.borderWidth, r: options.borderRadius || 0, rotation: rotation, padding: options.padding, zIndex: 1 }; // Get automated contrast color if (style.color === 'contrast') { moreStyle.color = options.inside || options.distance < 0 || !!seriesOptions.stacking ? renderer.getContrast(point.color || series.color) : '#000000'; } if (cursor) { moreStyle.cursor = cursor; } // Remove unused attributes (#947) for (name in attr) { if (attr[name] === UNDEFINED) { delete attr[name]; } } dataLabel = point.dataLabel = renderer[rotation ? 'text' : 'label']( // labels don't support rotation str, 0, -9999, options.shape, null, null, options.useHTML ) .attr(attr) .css(extend(style, moreStyle)) .add(dataLabelsGroup) .shadow(options.shadow); } if (dataLabel) { // Now the data label is created and placed at 0,0, so we need to align it series.alignDataLabel(point, dataLabel, options, null, isNew); } } }); } }; /** * Align each individual data label */ Series.prototype.alignDataLabel = function (point, dataLabel, options, alignTo, isNew) { var chart = this.chart, inverted = chart.inverted, plotX = pick(point.plotX, -9999), plotY = pick(point.plotY, -9999), bBox = dataLabel.getBBox(), baseline = chart.renderer.fontMetrics(options.style.fontSize).b, rotation = options.rotation, normRotation, negRotation, align = options.align, rotCorr, // rotation correction // Math.round for rounding errors (#2683), alignTo to allow column labels (#2700) visible = this.visible && (point.series.forceDL || chart.isInsidePlot(plotX, mathRound(plotY), inverted) || (alignTo && chart.isInsidePlot(plotX, inverted ? alignTo.x + 1 : alignTo.y + alignTo.height - 1, inverted))), alignAttr, // the final position; justify = pick(options.overflow, 'justify') === 'justify'; if (visible) { // The alignment box is a singular point alignTo = extend({ x: inverted ? chart.plotWidth - plotY : plotX, y: mathRound(inverted ? chart.plotHeight - plotX : plotY), width: 0, height: 0 }, alignTo); // Add the text size for alignment calculation extend(options, { width: bBox.width, height: bBox.height }); // Allow a hook for changing alignment in the last moment, then do the alignment if (rotation) { justify = false; // Not supported for rotated text rotCorr = chart.renderer.rotCorr(baseline, rotation); // #3723 alignAttr = { x: alignTo.x + options.x + alignTo.width / 2 + rotCorr.x, y: alignTo.y + options.y + alignTo.height / 2 }; dataLabel [isNew ? 'attr' : 'animate'](alignAttr) .attr({ // #3003 align: options.align }); // Compensate for the rotated label sticking out on the sides normRotation = (rotation + 720) % 360; negRotation = normRotation > 180 && normRotation < 360; if (align === 'left') { alignAttr.y -= negRotation ? bBox.height : 0; } else if (align === 'center') { alignAttr.x -= bBox.width / 2; alignAttr.y -= bBox.height / 2; } else if (align === 'right') { alignAttr.x -= bBox.width; alignAttr.y -= negRotation ? 0 : bBox.height; } } else { dataLabel.align(options, null, alignTo); alignAttr = dataLabel.alignAttr; } // Handle justify or crop if (justify) { this.justifyDataLabel(dataLabel, options, alignAttr, bBox, alignTo, isNew); // Now check that the data label is within the plot area } else if (pick(options.crop, true)) { visible = chart.isInsidePlot(alignAttr.x, alignAttr.y) && chart.isInsidePlot(alignAttr.x + bBox.width, alignAttr.y + bBox.height); } // When we're using a shape, make it possible with a connector or an arrow pointing to thie point if (options.shape && !rotation) { dataLabel.attr({ anchorX: point.plotX, anchorY: point.plotY }); } } // Show or hide based on the final aligned position if (!visible) { stop(dataLabel); dataLabel.attr({ y: -9999 }); dataLabel.placed = false; // don't animate back in } }; /** * If data labels fall partly outside the plot area, align them back in, in a way that * doesn't hide the point. */ Series.prototype.justifyDataLabel = function (dataLabel, options, alignAttr, bBox, alignTo, isNew) { var chart = this.chart, align = options.align, verticalAlign = options.verticalAlign, off, justified, padding = dataLabel.box ? 0 : (dataLabel.padding || 0); // Off left off = alignAttr.x + padding; if (off < 0) { if (align === 'right') { options.align = 'left'; } else { options.x = -off; } justified = true; } // Off right off = alignAttr.x + bBox.width - padding; if (off > chart.plotWidth) { if (align === 'left') { options.align = 'right'; } else { options.x = chart.plotWidth - off; } justified = true; } // Off top off = alignAttr.y + padding; if (off < 0) { if (verticalAlign === 'bottom') { options.verticalAlign = 'top'; } else { options.y = -off; } justified = true; } // Off bottom off = alignAttr.y + bBox.height - padding; if (off > chart.plotHeight) { if (verticalAlign === 'top') { options.verticalAlign = 'bottom'; } else { options.y = chart.plotHeight - off; } justified = true; } if (justified) { dataLabel.placed = !isNew; dataLabel.align(options, null, alignTo); } }; /** * Override the base drawDataLabels method by pie specific functionality */ if (seriesTypes.pie) { seriesTypes.pie.prototype.drawDataLabels = function () { var series = this, data = series.data, point, chart = series.chart, options = series.options.dataLabels, connectorPadding = pick(options.connectorPadding, 10), connectorWidth = pick(options.connectorWidth, 1), plotWidth = chart.plotWidth, plotHeight = chart.plotHeight, connector, connectorPath, softConnector = pick(options.softConnector, true), distanceOption = options.distance, seriesCenter = series.center, radius = seriesCenter[2] / 2, centerY = seriesCenter[1], outside = distanceOption > 0, dataLabel, dataLabelWidth, labelPos, labelHeight, halves = [// divide the points into right and left halves for anti collision [], // right [] // left ], x, y, visibility, rankArr, i, j, overflow = [0, 0, 0, 0], // top, right, bottom, left sort = function (a, b) { return b.y - a.y; }; // get out if not enabled if (!series.visible || (!options.enabled && !series._hasPointLabels)) { return; } // run parent method Series.prototype.drawDataLabels.apply(series); each(data, function (point) { if (point.dataLabel && point.visible) { // #407, #2510 // Arrange points for detection collision halves[point.half].push(point); // Reset positions (#4905) point.dataLabel._pos = null; } }); /* Loop over the points in each half, starting from the top and bottom * of the pie to detect overlapping labels. */ i = 2; while (i--) { var slots = [], slotsLength, usedSlots = [], points = halves[i], pos, bottom, length = points.length, slotIndex; if (!length) { continue; } // Sort by angle series.sortByAngle(points, i - 0.5); // Assume equal label heights on either hemisphere (#2630) j = labelHeight = 0; while (!labelHeight && points[j]) { // #1569 labelHeight = points[j] && points[j].dataLabel && (points[j].dataLabel.getBBox().height || 21); // 21 is for #968 j++; } // Only do anti-collision when we are outside the pie and have connectors (#856) if (distanceOption > 0) { // Build the slots bottom = mathMin(centerY + radius + distanceOption, chart.plotHeight); for (pos = mathMax(0, centerY - radius - distanceOption); pos <= bottom; pos += labelHeight) { slots.push(pos); } slotsLength = slots.length; /* Visualize the slots if (!series.slotElements) { series.slotElements = []; } if (i === 1) { series.slotElements.forEach(function (elem) { elem.destroy(); }); series.slotElements.length = 0; } slots.forEach(function (pos, no) { var slotX = series.getX(pos, i) + chart.plotLeft - (i ? 100 : 0), slotY = pos + chart.plotTop; if (!isNaN(slotX)) { series.slotElements.push(chart.renderer.rect(slotX, slotY - 7, 100, labelHeight, 1) .attr({ 'stroke-width': 1, stroke: 'silver', fill: 'rgba(0,0,255,0.1)' }) .add()); series.slotElements.push(chart.renderer.text('Slot '+ no, slotX, slotY + 4) .attr({ fill: 'silver' }).add()); } }); // */ // if there are more values than available slots, remove lowest values if (length > slotsLength) { // create an array for sorting and ranking the points within each quarter rankArr = [].concat(points); rankArr.sort(sort); j = length; while (j--) { rankArr[j].rank = j; } j = length; while (j--) { if (points[j].rank >= slotsLength) { points.splice(j, 1); } } length = points.length; } // The label goes to the nearest open slot, but not closer to the edge than // the label's index. for (j = 0; j < length; j++) { point = points[j]; labelPos = point.labelPos; var closest = 9999, distance, slotI; // find the closest slot index for (slotI = 0; slotI < slotsLength; slotI++) { distance = mathAbs(slots[slotI] - labelPos[1]); if (distance < closest) { closest = distance; slotIndex = slotI; } } // if that slot index is closer to the edges of the slots, move it // to the closest appropriate slot if (slotIndex < j && slots[j] !== null) { // cluster at the top slotIndex = j; } else if (slotsLength < length - j + slotIndex && slots[j] !== null) { // cluster at the bottom slotIndex = slotsLength - length + j; while (slots[slotIndex] === null) { // make sure it is not taken slotIndex++; } } else { // Slot is taken, find next free slot below. In the next run, the next slice will find the // slot above these, because it is the closest one while (slots[slotIndex] === null) { // make sure it is not taken slotIndex++; } } usedSlots.push({ i: slotIndex, y: slots[slotIndex] }); slots[slotIndex] = null; // mark as taken } // sort them in order to fill in from the top usedSlots.sort(sort); } // now the used slots are sorted, fill them up sequentially for (j = 0; j < length; j++) { var slot, naturalY; point = points[j]; labelPos = point.labelPos; dataLabel = point.dataLabel; visibility = point.visible === false ? HIDDEN : 'inherit'; naturalY = labelPos[1]; if (distanceOption > 0) { slot = usedSlots.pop(); slotIndex = slot.i; // if the slot next to currrent slot is free, the y value is allowed // to fall back to the natural position y = slot.y; if ((naturalY > y && slots[slotIndex + 1] !== null) || (naturalY < y && slots[slotIndex - 1] !== null)) { y = mathMin(mathMax(0, naturalY), chart.plotHeight); } } else { y = naturalY; } // get the x - use the natural x position for first and last slot, to prevent the top // and botton slice connectors from touching each other on either side x = options.justify ? seriesCenter[0] + (i ? -1 : 1) * (radius + distanceOption) : series.getX(y === centerY - radius - distanceOption || y === centerY + radius + distanceOption ? naturalY : y, i); // Record the placement and visibility dataLabel._attr = { visibility: visibility, align: labelPos[6] }; dataLabel._pos = { x: x + options.x + ({ left: connectorPadding, right: -connectorPadding }[labelPos[6]] || 0), y: y + options.y - 10 // 10 is for the baseline (label vs text) }; dataLabel.connX = x; dataLabel.connY = y; // Detect overflowing data labels if (this.options.size === null) { dataLabelWidth = dataLabel.width; // Overflow left if (x - dataLabelWidth < connectorPadding) { overflow[3] = mathMax(mathRound(dataLabelWidth - x + connectorPadding), overflow[3]); // Overflow right } else if (x + dataLabelWidth > plotWidth - connectorPadding) { overflow[1] = mathMax(mathRound(x + dataLabelWidth - plotWidth + connectorPadding), overflow[1]); } // Overflow top if (y - labelHeight / 2 < 0) { overflow[0] = mathMax(mathRound(-y + labelHeight / 2), overflow[0]); // Overflow left } else if (y + labelHeight / 2 > plotHeight) { overflow[2] = mathMax(mathRound(y + labelHeight / 2 - plotHeight), overflow[2]); } } } // for each point } // for each half // Do not apply the final placement and draw the connectors until we have verified // that labels are not spilling over. if (arrayMax(overflow) === 0 || this.verifyDataLabelOverflow(overflow)) { // Place the labels in the final position this.placeDataLabels(); // Draw the connectors if (outside && connectorWidth) { each(this.points, function (point) { connector = point.connector; labelPos = point.labelPos; dataLabel = point.dataLabel; if (dataLabel && dataLabel._pos && point.visible) { visibility = dataLabel._attr.visibility; x = dataLabel.connX; y = dataLabel.connY; connectorPath = softConnector ? [ M, x + (labelPos[6] === 'left' ? 5 : -5), y, // end of the string at the label 'C', x, y, // first break, next to the label 2 * labelPos[2] - labelPos[4], 2 * labelPos[3] - labelPos[5], labelPos[2], labelPos[3], // second break L, labelPos[4], labelPos[5] // base ] : [ M, x + (labelPos[6] === 'left' ? 5 : -5), y, // end of the string at the label L, labelPos[2], labelPos[3], // second break L, labelPos[4], labelPos[5] // base ]; if (connector) { connector.animate({ d: connectorPath }); connector.attr('visibility', visibility); } else { point.connector = connector = series.chart.renderer.path(connectorPath).attr({ 'stroke-width': connectorWidth, stroke: options.connectorColor || point.color || '#606060', visibility: visibility //zIndex: 0 // #2722 (reversed) }) .add(series.dataLabelsGroup); } } else if (connector) { point.connector = connector.destroy(); } }); } } }; /** * Perform the final placement of the data labels after we have verified that they * fall within the plot area. */ seriesTypes.pie.prototype.placeDataLabels = function () { each(this.points, function (point) { var dataLabel = point.dataLabel, _pos; if (dataLabel && point.visible) { _pos = dataLabel._pos; if (_pos) { dataLabel.attr(dataLabel._attr); dataLabel[dataLabel.moved ? 'animate' : 'attr'](_pos); dataLabel.moved = true; } else if (dataLabel) { dataLabel.attr({ y: -9999 }); } } }); }; seriesTypes.pie.prototype.alignDataLabel = noop; /** * Verify whether the data labels are allowed to draw, or we should run more translation and data * label positioning to keep them inside the plot area. Returns true when data labels are ready * to draw. */ seriesTypes.pie.prototype.verifyDataLabelOverflow = function (overflow) { var center = this.center, options = this.options, centerOption = options.center, minSize = options.minSize || 80, newSize = minSize, ret; // Handle horizontal size and center if (centerOption[0] !== null) { // Fixed center newSize = mathMax(center[2] - mathMax(overflow[1], overflow[3]), minSize); } else { // Auto center newSize = mathMax( center[2] - overflow[1] - overflow[3], // horizontal overflow minSize ); center[0] += (overflow[3] - overflow[1]) / 2; // horizontal center } // Handle vertical size and center if (centerOption[1] !== null) { // Fixed center newSize = mathMax(mathMin(newSize, center[2] - mathMax(overflow[0], overflow[2])), minSize); } else { // Auto center newSize = mathMax( mathMin( newSize, center[2] - overflow[0] - overflow[2] // vertical overflow ), minSize ); center[1] += (overflow[0] - overflow[2]) / 2; // vertical center } // If the size must be decreased, we need to run translate and drawDataLabels again if (newSize < center[2]) { center[2] = newSize; center[3] = Math.min(relativeLength(options.innerSize || 0, newSize), newSize); // #3632 this.translate(center); if (this.drawDataLabels) { this.drawDataLabels(); } // Else, return true to indicate that the pie and its labels is within the plot area } else { ret = true; } return ret; }; } if (seriesTypes.column) { /** * Override the basic data label alignment by adjusting for the position of the column */ seriesTypes.column.prototype.alignDataLabel = function (point, dataLabel, options, alignTo, isNew) { var inverted = this.chart.inverted, series = point.series, dlBox = point.dlBox || point.shapeArgs, // data label box for alignment below = pick(point.below, point.plotY > pick(this.translatedThreshold, series.yAxis.len)), // point.below is used in range series inside = pick(options.inside, !!this.options.stacking), // draw it inside the box? overshoot; // Align to the column itself, or the top of it if (dlBox) { // Area range uses this method but not alignTo alignTo = merge(dlBox); if (alignTo.y < 0) { alignTo.height += alignTo.y; alignTo.y = 0; } overshoot = alignTo.y + alignTo.height - series.yAxis.len; if (overshoot > 0) { alignTo.height -= overshoot; } if (inverted) { alignTo = { x: series.yAxis.len - alignTo.y - alignTo.height, y: series.xAxis.len - alignTo.x - alignTo.width, width: alignTo.height, height: alignTo.width }; } // Compute the alignment box if (!inside) { if (inverted) { alignTo.x += below ? 0 : alignTo.width; alignTo.width = 0; } else { alignTo.y += below ? alignTo.height : 0; alignTo.height = 0; } } } // When alignment is undefined (typically columns and bars), display the individual // point below or above the point depending on the threshold options.align = pick( options.align, !inverted || inside ? 'center' : below ? 'right' : 'left' ); options.verticalAlign = pick( options.verticalAlign, inverted || inside ? 'middle' : below ? 'top' : 'bottom' ); // Call the parent method Series.prototype.alignDataLabel.call(this, point, dataLabel, options, alignTo, isNew); }; } /** * Highcharts module to hide overlapping data labels. This module is included in Highcharts. */ (function (H) { var Chart = H.Chart, each = H.each, pick = H.pick, addEvent = H.addEvent; // Collect potensial overlapping data labels. Stack labels probably don't need to be // considered because they are usually accompanied by data labels that lie inside the columns. Chart.prototype.callbacks.push(function (chart) { function collectAndHide() { var labels = []; each(chart.series, function (series) { var dlOptions = series.options.dataLabels, collections = series.dataLabelCollections || ['dataLabel']; // Range series have two collections if ((dlOptions.enabled || series._hasPointLabels) && !dlOptions.allowOverlap && series.visible) { // #3866 each(collections, function (coll) { each(series.points, function (point) { if (point[coll]) { point[coll].labelrank = pick(point.labelrank, point.shapeArgs && point.shapeArgs.height); // #4118 labels.push(point[coll]); } }); }); } }); chart.hideOverlappingLabels(labels); } // Do it now ... collectAndHide(); // ... and after each chart redraw addEvent(chart, 'redraw', collectAndHide); }); /** * Hide overlapping labels. Labels are moved and faded in and out on zoom to provide a smooth * visual imression. */ Chart.prototype.hideOverlappingLabels = function (labels) { var len = labels.length, label, i, j, label1, label2, isIntersecting, pos1, pos2, parent1, parent2, padding, intersectRect = function (x1, y1, w1, h1, x2, y2, w2, h2) { return !( x2 > x1 + w1 || x2 + w2 < x1 || y2 > y1 + h1 || y2 + h2 < y1 ); }; // Mark with initial opacity for (i = 0; i < len; i++) { label = labels[i]; if (label) { label.oldOpacity = label.opacity; label.newOpacity = 1; } } // Prevent a situation in a gradually rising slope, that each label // will hide the previous one because the previous one always has // lower rank. labels.sort(function (a, b) { return (b.labelrank || 0) - (a.labelrank || 0); }); // Detect overlapping labels for (i = 0; i < len; i++) { label1 = labels[i]; for (j = i + 1; j < len; ++j) { label2 = labels[j]; if (label1 && label2 && label1.placed && label2.placed && label1.newOpacity !== 0 && label2.newOpacity !== 0) { pos1 = label1.alignAttr; pos2 = label2.alignAttr; parent1 = label1.parentGroup; // Different panes have different positions parent2 = label2.parentGroup; padding = 2 * (label1.box ? 0 : label1.padding); // Substract the padding if no background or border (#4333) isIntersecting = intersectRect( pos1.x + parent1.translateX, pos1.y + parent1.translateY, label1.width - padding, label1.height - padding, pos2.x + parent2.translateX, pos2.y + parent2.translateY, label2.width - padding, label2.height - padding ); if (isIntersecting) { (label1.labelrank < label2.labelrank ? label1 : label2).newOpacity = 0; } } } } // Hide or show each(labels, function (label) { var complete, newOpacity; if (label) { newOpacity = label.newOpacity; if (label.oldOpacity !== newOpacity && label.placed) { // Make sure the label is completely hidden to avoid catching clicks (#4362) if (newOpacity) { label.show(true); } else { complete = function () { label.hide(); }; } // Animate or set the opacity label.alignAttr.opacity = newOpacity; label[label.isOld ? 'animate' : 'attr'](label.alignAttr, null, complete); } label.isOld = true; } }); }; }(Highcharts)); /** * Override to use the extreme coordinates from the SVG shape, not the * data values */ wrap(Axis.prototype, 'getSeriesExtremes', function (proceed) { var isXAxis = this.isXAxis, dataMin, dataMax, xData = [], useMapGeometry; // Remove the xData array and cache it locally so that the proceed method doesn't use it if (isXAxis) { each(this.series, function (series, i) { if (series.useMapGeometry) { xData[i] = series.xData; series.xData = []; } }); } // Call base to reach normal cartesian series (like mappoint) proceed.call(this); // Run extremes logic for map and mapline if (isXAxis) { dataMin = pick(this.dataMin, Number.MAX_VALUE); dataMax = pick(this.dataMax, -Number.MAX_VALUE); each(this.series, function (series, i) { if (series.useMapGeometry) { dataMin = Math.min(dataMin, pick(series.minX, dataMin)); dataMax = Math.max(dataMax, pick(series.maxX, dataMin)); series.xData = xData[i]; // Reset xData array useMapGeometry = true; } }); if (useMapGeometry) { this.dataMin = dataMin; this.dataMax = dataMax; } } }); /** * Override axis translation to make sure the aspect ratio is always kept */ wrap(Axis.prototype, 'setAxisTranslation', function (proceed) { var chart = this.chart, mapRatio, plotRatio = chart.plotWidth / chart.plotHeight, adjustedAxisLength, xAxis = chart.xAxis[0], padAxis, fixTo, fixDiff, preserveAspectRatio; // Run the parent method proceed.call(this); // Check for map-like series if (this.coll === 'yAxis' && xAxis.transA !== UNDEFINED) { each(this.series, function (series) { if (series.preserveAspectRatio) { preserveAspectRatio = true; } }); } // On Y axis, handle both if (preserveAspectRatio) { // Use the same translation for both axes this.transA = xAxis.transA = Math.min(this.transA, xAxis.transA); mapRatio = plotRatio / ((xAxis.max - xAxis.min) / (this.max - this.min)); // What axis to pad to put the map in the middle padAxis = mapRatio < 1 ? this : xAxis; // Pad it adjustedAxisLength = (padAxis.max - padAxis.min) * padAxis.transA; padAxis.pixelPadding = padAxis.len - adjustedAxisLength; padAxis.minPixelPadding = padAxis.pixelPadding / 2; fixTo = padAxis.fixTo; if (fixTo) { fixDiff = fixTo[1] - padAxis.toValue(fixTo[0], true); fixDiff *= padAxis.transA; if (Math.abs(fixDiff) > padAxis.minPixelPadding || (padAxis.min === padAxis.dataMin && padAxis.max === padAxis.dataMax)) { // zooming out again, keep within restricted area fixDiff = 0; } padAxis.minPixelPadding -= fixDiff; } } }); /** * Override Axis.render in order to delete the fixTo prop */ wrap(Axis.prototype, 'render', function (proceed) { proceed.call(this); this.fixTo = null; }); /** * The ColorAxis object for inclusion in gradient legends */ var ColorAxis = Highcharts.ColorAxis = function () { this.isColorAxis = true; this.init.apply(this, arguments); }; extend(ColorAxis.prototype, Axis.prototype); extend(ColorAxis.prototype, { defaultColorAxisOptions: { lineWidth: 0, minPadding: 0, maxPadding: 0, gridLineWidth: 1, tickPixelInterval: 72, startOnTick: true, endOnTick: true, offset: 0, marker: { animation: { duration: 50 }, color: 'gray', width: 0.01 }, labels: { overflow: 'justify' }, minColor: '#EFEFFF', maxColor: '#003875', tickLength: 5 }, init: function (chart, userOptions) { var horiz = chart.options.legend.layout !== 'vertical', options; // Build the options options = merge(this.defaultColorAxisOptions, { side: horiz ? 2 : 1, reversed: !horiz }, userOptions, { opposite: !horiz, showEmpty: false, title: null, isColor: true }); Axis.prototype.init.call(this, chart, options); // Base init() pushes it to the xAxis array, now pop it again //chart[this.isXAxis ? 'xAxis' : 'yAxis'].pop(); // Prepare data classes if (userOptions.dataClasses) { this.initDataClasses(userOptions); } this.initStops(userOptions); // Override original axis properties this.horiz = horiz; this.zoomEnabled = false; }, /* * Return an intermediate color between two colors, according to pos where 0 * is the from color and 1 is the to color. * NOTE: Changes here should be copied * to the same function in drilldown.src.js and solid-gauge-src.js. */ tweenColors: function (from, to, pos) { // Check for has alpha, because rgba colors perform worse due to lack of // support in WebKit. var hasAlpha, ret; // Unsupported color, return to-color (#3920) if (!to.rgba.length || !from.rgba.length) { ret = to.input || 'none'; // Interpolate } else { from = from.rgba; to = to.rgba; hasAlpha = (to[3] !== 1 || from[3] !== 1); ret = (hasAlpha ? 'rgba(' : 'rgb(') + Math.round(to[0] + (from[0] - to[0]) * (1 - pos)) + ',' + Math.round(to[1] + (from[1] - to[1]) * (1 - pos)) + ',' + Math.round(to[2] + (from[2] - to[2]) * (1 - pos)) + (hasAlpha ? (',' + (to[3] + (from[3] - to[3]) * (1 - pos))) : '') + ')'; } return ret; }, initDataClasses: function (userOptions) { var axis = this, chart = this.chart, dataClasses, colorCounter = 0, options = this.options, len = userOptions.dataClasses.length; this.dataClasses = dataClasses = []; this.legendItems = []; each(userOptions.dataClasses, function (dataClass, i) { var colors; dataClass = merge(dataClass); dataClasses.push(dataClass); if (!dataClass.color) { if (options.dataClassColor === 'category') { colors = chart.options.colors; dataClass.color = colors[colorCounter++]; // loop back to zero if (colorCounter === colors.length) { colorCounter = 0; } } else { dataClass.color = axis.tweenColors( Color(options.minColor), Color(options.maxColor), len < 2 ? 0.5 : i / (len - 1) // #3219 ); } } }); }, initStops: function (userOptions) { this.stops = userOptions.stops || [ [0, this.options.minColor], [1, this.options.maxColor] ]; each(this.stops, function (stop) { stop.color = Color(stop[1]); }); }, /** * Extend the setOptions method to process extreme colors and color * stops. */ setOptions: function (userOptions) { Axis.prototype.setOptions.call(this, userOptions); this.options.crosshair = this.options.marker; this.coll = 'colorAxis'; }, setAxisSize: function () { var symbol = this.legendSymbol, chart = this.chart, x, y, width, height; if (symbol) { this.left = x = symbol.attr('x'); this.top = y = symbol.attr('y'); this.width = width = symbol.attr('width'); this.height = height = symbol.attr('height'); this.right = chart.chartWidth - x - width; this.bottom = chart.chartHeight - y - height; this.len = this.horiz ? width : height; this.pos = this.horiz ? x : y; } }, /** * Translate from a value to a color */ toColor: function (value, point) { var pos, stops = this.stops, from, to, color, dataClasses = this.dataClasses, dataClass, i; if (dataClasses) { i = dataClasses.length; while (i--) { dataClass = dataClasses[i]; from = dataClass.from; to = dataClass.to; if ((from === UNDEFINED || value >= from) && (to === UNDEFINED || value <= to)) { color = dataClass.color; if (point) { point.dataClass = i; } break; } } } else { if (this.isLog) { value = this.val2lin(value); } pos = 1 - ((this.max - value) / ((this.max - this.min) || 1)); i = stops.length; while (i--) { if (pos > stops[i][0]) { break; } } from = stops[i] || stops[i + 1]; to = stops[i + 1] || from; // The position within the gradient pos = 1 - (to[0] - pos) / ((to[0] - from[0]) || 1); color = this.tweenColors( from.color, to.color, pos ); } return color; }, /** * Override the getOffset method to add the whole axis groups inside the legend. */ getOffset: function () { var group = this.legendGroup, sideOffset = this.chart.axisOffset[this.side]; if (group) { // Hook for the getOffset method to add groups to this parent group this.axisParent = group; // Call the base Axis.prototype.getOffset.call(this); // First time only if (!this.added) { this.added = true; this.labelLeft = 0; this.labelRight = this.width; } // Reset it to avoid color axis reserving space this.chart.axisOffset[this.side] = sideOffset; } }, /** * Create the color gradient */ setLegendColor: function () { var grad, horiz = this.horiz, options = this.options, reversed = this.reversed, one = reversed ? 1 : 0, zero = reversed ? 0 : 1; grad = horiz ? [one, 0, zero, 0] : [0, zero, 0, one]; // #3190 this.legendColor = { linearGradient: { x1: grad[0], y1: grad[1], x2: grad[2], y2: grad[3] }, stops: options.stops || [ [0, options.minColor], [1, options.maxColor] ] }; }, /** * The color axis appears inside the legend and has its own legend symbol */ drawLegendSymbol: function (legend, item) { var padding = legend.padding, legendOptions = legend.options, horiz = this.horiz, width = pick(legendOptions.symbolWidth, horiz ? 200 : 12), height = pick(legendOptions.symbolHeight, horiz ? 12 : 200), labelPadding = pick(legendOptions.labelPadding, horiz ? 16 : 30), itemDistance = pick(legendOptions.itemDistance, 10); this.setLegendColor(); // Create the gradient item.legendSymbol = this.chart.renderer.rect( 0, legend.baseline - 11, width, height ).attr({ zIndex: 1 }).add(item.legendGroup); // Set how much space this legend item takes up this.legendItemWidth = width + padding + (horiz ? itemDistance : labelPadding); this.legendItemHeight = height + padding + (horiz ? labelPadding : 0); }, /** * Fool the legend */ setState: noop, visible: true, setVisible: noop, getSeriesExtremes: function () { var series; if (this.series.length) { series = this.series[0]; this.dataMin = series.valueMin; this.dataMax = series.valueMax; } }, drawCrosshair: function (e, point) { var plotX = point && point.plotX, plotY = point && point.plotY, crossPos, axisPos = this.pos, axisLen = this.len; if (point) { crossPos = this.toPixels(point[point.series.colorKey]); if (crossPos < axisPos) { crossPos = axisPos - 2; } else if (crossPos > axisPos + axisLen) { crossPos = axisPos + axisLen + 2; } point.plotX = crossPos; point.plotY = this.len - crossPos; Axis.prototype.drawCrosshair.call(this, e, point); point.plotX = plotX; point.plotY = plotY; if (this.cross) { this.cross .attr({ fill: this.crosshair.color }) .add(this.legendGroup); } } }, getPlotLinePath: function (a, b, c, d, pos) { return typeof pos === 'number' ? // crosshairs only // #3969 pos can be 0 !! (this.horiz ? ['M', pos - 4, this.top - 6, 'L', pos + 4, this.top - 6, pos, this.top, 'Z'] : ['M', this.left, pos, 'L', this.left - 6, pos + 6, this.left - 6, pos - 6, 'Z'] ) : Axis.prototype.getPlotLinePath.call(this, a, b, c, d); }, update: function (newOptions, redraw) { var chart = this.chart, legend = chart.legend; each(this.series, function (series) { series.isDirtyData = true; // Needed for Axis.update when choropleth colors change }); // When updating data classes, destroy old items and make sure new ones are created (#3207) if (newOptions.dataClasses && legend.allItems) { each(legend.allItems, function (item) { if (item.isDataClass) { item.legendGroup.destroy(); } }); chart.isDirtyLegend = true; } // Keep the options structure updated for export. Unlike xAxis and yAxis, the colorAxis is // not an array. (#3207) chart.options[this.coll] = merge(this.userOptions, newOptions); Axis.prototype.update.call(this, newOptions, redraw); if (this.legendItem) { this.setLegendColor(); legend.colorizeItem(this, true); } }, /** * Get the legend item symbols for data classes */ getDataClassLegendSymbols: function () { var axis = this, chart = this.chart, legendItems = this.legendItems, legendOptions = chart.options.legend, valueDecimals = legendOptions.valueDecimals, valueSuffix = legendOptions.valueSuffix || '', name; if (!legendItems.length) { each(this.dataClasses, function (dataClass, i) { var vis = true, from = dataClass.from, to = dataClass.to; // Assemble the default name. This can be overridden by legend.options.labelFormatter name = ''; if (from === UNDEFINED) { name = '< '; } else if (to === UNDEFINED) { name = '> '; } if (from !== UNDEFINED) { name += Highcharts.numberFormat(from, valueDecimals) + valueSuffix; } if (from !== UNDEFINED && to !== UNDEFINED) { name += ' - '; } if (to !== UNDEFINED) { name += Highcharts.numberFormat(to, valueDecimals) + valueSuffix; } // Add a mock object to the legend items legendItems.push(extend({ chart: chart, name: name, options: {}, drawLegendSymbol: LegendSymbolMixin.drawRectangle, visible: true, setState: noop, isDataClass: true, setVisible: function () { vis = this.visible = !vis; each(axis.series, function (series) { each(series.points, function (point) { if (point.dataClass === i) { point.setVisible(vis); } }); }); chart.legend.colorizeItem(this, vis); } }, dataClass)); }); } return legendItems; }, name: '' // Prevents 'undefined' in legend in IE8 }); /** * Handle animation of the color attributes directly */ each(['fill', 'stroke'], function (prop) { Highcharts.Fx.prototype[prop + 'Setter'] = function () { this.elem.attr(prop, ColorAxis.prototype.tweenColors(Color(this.start), Color(this.end), this.pos)); }; }); /** * Extend the chart getAxes method to also get the color axis */ wrap(Chart.prototype, 'getAxes', function (proceed) { var options = this.options, colorAxisOptions = options.colorAxis; proceed.call(this); this.colorAxis = []; if (colorAxisOptions) { new ColorAxis(this, colorAxisOptions); // eslint-disable-line no-new } }); /** * Wrap the legend getAllItems method to add the color axis. This also removes the * axis' own series to prevent them from showing up individually. */ wrap(Legend.prototype, 'getAllItems', function (proceed) { var allItems = [], colorAxis = this.chart.colorAxis[0]; if (colorAxis) { // Data classes if (colorAxis.options.dataClasses) { allItems = allItems.concat(colorAxis.getDataClassLegendSymbols()); // Gradient legend } else { // Add this axis on top allItems.push(colorAxis); } // Don't add the color axis' series each(colorAxis.series, function (series) { series.options.showInLegend = false; }); } return allItems.concat(proceed.call(this)); }); /** * Mixin for maps and heatmaps */ var colorPointMixin = { /** * Set the visibility of a single point */ setVisible: function (vis) { var point = this, method = vis ? 'show' : 'hide'; // Show and hide associated elements each(['graphic', 'dataLabel'], function (key) { if (point[key]) { point[key][method](); } }); } }; var colorSeriesMixin = { pointAttrToOptions: { // mapping between SVG attributes and the corresponding options stroke: 'borderColor', 'stroke-width': 'borderWidth', fill: 'color', dashstyle: 'dashStyle' }, pointArrayMap: ['value'], axisTypes: ['xAxis', 'yAxis', 'colorAxis'], optionalAxis: 'colorAxis', trackerGroups: ['group', 'markerGroup', 'dataLabelsGroup'], getSymbol: noop, parallelArrays: ['x', 'y', 'value'], colorKey: 'value', /** * In choropleth maps, the color is a result of the value, so this needs translation too */ translateColors: function () { var series = this, nullColor = this.options.nullColor, colorAxis = this.colorAxis, colorKey = this.colorKey; each(this.data, function (point) { var value = point[colorKey], color; color = point.options.color || (value === null ? nullColor : (colorAxis && value !== undefined) ? colorAxis.toColor(value, point) : point.color || series.color); if (color) { point.color = color; } }); } }; // The vector-effect attribute is not supported in IE <= 11 (at least), so we need // diffent logic (#3218) var supportsVectorEffect = doc.documentElement.style.vectorEffect !== undefined; /** * Extend the default options with map options */ defaultPlotOptions.map = merge(defaultPlotOptions.scatter, { allAreas: true, animation: false, // makes the complex shapes slow nullColor: '#F8F8F8', borderColor: 'silver', borderWidth: 1, marker: null, stickyTracking: false, dataLabels: { formatter: function () { // #2945 return this.point.value; }, inside: true, // for the color verticalAlign: 'middle', crop: false, overflow: false, padding: 0 }, turboThreshold: 0, tooltip: { followPointer: true, pointFormat: '{point.name}: {point.value}<br/>' }, states: { normal: { animation: true }, hover: { brightness: 0.2, halo: null } } }); /** * The MapAreaPoint object */ var MapAreaPoint = extendClass(Point, extend({ /** * Extend the Point object to split paths */ applyOptions: function (options, x) { var point = Point.prototype.applyOptions.call(this, options, x), series = this.series, joinBy = series.joinBy, mapPoint; if (series.mapData) { mapPoint = point[joinBy[1]] !== undefined && series.mapMap[point[joinBy[1]]]; if (mapPoint) { // This applies only to bubbles if (series.xyFromShape) { point.x = mapPoint._midX; point.y = mapPoint._midY; } extend(point, mapPoint); // copy over properties } else { point.value = point.value || null; } } return point; }, /** * Stop the fade-out */ onMouseOver: function (e) { clearTimeout(this.colorInterval); if (this.value !== null) { Point.prototype.onMouseOver.call(this, e); } else { //#3401 Tooltip doesn't hide when hovering over null points this.series.onMouseOut(e); } }, /** * Custom animation for tweening out the colors. Animation reduces blinking when hovering * over islands and coast lines. We run a custom implementation of animation becuase we * need to be able to run this independently from other animations like zoom redraw. Also, * adding color animation to the adapters would introduce almost the same amount of code. */ onMouseOut: function () { var point = this, start = +new Date(), normalColor = Color(point.color), hoverColor = Color(point.pointAttr.hover.fill), animation = point.series.options.states.normal.animation, duration = animation && (animation.duration || 500), fill; if (duration && normalColor.rgba.length === 4 && hoverColor.rgba.length === 4 && point.state !== 'select') { fill = point.pointAttr[''].fill; delete point.pointAttr[''].fill; // avoid resetting it in Point.setState clearTimeout(point.colorInterval); point.colorInterval = setInterval(function () { var pos = (new Date() - start) / duration, graphic = point.graphic; if (pos > 1) { pos = 1; } if (graphic) { graphic.attr('fill', ColorAxis.prototype.tweenColors.call(0, hoverColor, normalColor, pos)); } if (pos >= 1) { clearTimeout(point.colorInterval); } }, 13); } Point.prototype.onMouseOut.call(point); if (fill) { point.pointAttr[''].fill = fill; } }, /** * Zoom the chart to view a specific area point */ zoomTo: function () { var point = this, series = point.series; series.xAxis.setExtremes( point._minX, point._maxX, false ); series.yAxis.setExtremes( point._minY, point._maxY, false ); series.chart.redraw(); } }, colorPointMixin) ); /** * Add the series type */ seriesTypes.map = extendClass(seriesTypes.scatter, merge(colorSeriesMixin, { type: 'map', pointClass: MapAreaPoint, supportsDrilldown: true, getExtremesFromAll: true, useMapGeometry: true, // get axis extremes from paths, not values forceDL: true, searchPoint: noop, directTouch: true, // When tooltip is not shared, this series (and derivatives) requires direct touch/hover. KD-tree does not apply. preserveAspectRatio: true, // X axis and Y axis must have same translation slope /** * Get the bounding box of all paths in the map combined. */ getBox: function (paths) { var MAX_VALUE = Number.MAX_VALUE, maxX = -MAX_VALUE, minX = MAX_VALUE, maxY = -MAX_VALUE, minY = MAX_VALUE, minRange = MAX_VALUE, xAxis = this.xAxis, yAxis = this.yAxis, hasBox; // Find the bounding box each(paths || [], function (point) { if (point.path) { if (typeof point.path === 'string') { point.path = Highcharts.splitPath(point.path); } var path = point.path || [], i = path.length, even = false, // while loop reads from the end pointMaxX = -MAX_VALUE, pointMinX = MAX_VALUE, pointMaxY = -MAX_VALUE, pointMinY = MAX_VALUE, properties = point.properties; // The first time a map point is used, analyze its box if (!point._foundBox) { while (i--) { if (typeof path[i] === 'number' && !isNaN(path[i])) { if (even) { // even = x pointMaxX = Math.max(pointMaxX, path[i]); pointMinX = Math.min(pointMinX, path[i]); } else { // odd = Y pointMaxY = Math.max(pointMaxY, path[i]); pointMinY = Math.min(pointMinY, path[i]); } even = !even; } } // Cache point bounding box for use to position data labels, bubbles etc point._midX = pointMinX + (pointMaxX - pointMinX) * (point.middleX || (properties && properties['hc-middle-x']) || 0.5); // pick is slower and very marginally needed point._midY = pointMinY + (pointMaxY - pointMinY) * (point.middleY || (properties && properties['hc-middle-y']) || 0.5); point._maxX = pointMaxX; point._minX = pointMinX; point._maxY = pointMaxY; point._minY = pointMinY; point.labelrank = pick(point.labelrank, (pointMaxX - pointMinX) * (pointMaxY - pointMinY)); point._foundBox = true; } maxX = Math.max(maxX, point._maxX); minX = Math.min(minX, point._minX); maxY = Math.max(maxY, point._maxY); minY = Math.min(minY, point._minY); minRange = Math.min(point._maxX - point._minX, point._maxY - point._minY, minRange); hasBox = true; } }); // Set the box for the whole series if (hasBox) { this.minY = Math.min(minY, pick(this.minY, MAX_VALUE)); this.maxY = Math.max(maxY, pick(this.maxY, -MAX_VALUE)); this.minX = Math.min(minX, pick(this.minX, MAX_VALUE)); this.maxX = Math.max(maxX, pick(this.maxX, -MAX_VALUE)); // If no minRange option is set, set the default minimum zooming range to 5 times the // size of the smallest element if (xAxis && xAxis.options.minRange === undefined) { xAxis.minRange = Math.min(5 * minRange, (this.maxX - this.minX) / 5, xAxis.minRange || MAX_VALUE); } if (yAxis && yAxis.options.minRange === undefined) { yAxis.minRange = Math.min(5 * minRange, (this.maxY - this.minY) / 5, yAxis.minRange || MAX_VALUE); } } }, getExtremes: function () { // Get the actual value extremes for colors Series.prototype.getExtremes.call(this, this.valueData); // Recalculate box on updated data if (this.chart.hasRendered && this.isDirtyData) { this.getBox(this.options.data); } this.valueMin = this.dataMin; this.valueMax = this.dataMax; // Extremes for the mock Y axis this.dataMin = this.minY; this.dataMax = this.maxY; }, /** * Translate the path so that it automatically fits into the plot area box * @param {Object} path */ translatePath: function (path) { var series = this, even = false, // while loop reads from the end xAxis = series.xAxis, yAxis = series.yAxis, xMin = xAxis.min, xTransA = xAxis.transA, xMinPixelPadding = xAxis.minPixelPadding, yMin = yAxis.min, yTransA = yAxis.transA, yMinPixelPadding = yAxis.minPixelPadding, i, ret = []; // Preserve the original // Do the translation if (path) { i = path.length; while (i--) { if (typeof path[i] === 'number') { ret[i] = even ? (path[i] - xMin) * xTransA + xMinPixelPadding : (path[i] - yMin) * yTransA + yMinPixelPadding; even = !even; } else { ret[i] = path[i]; } } } return ret; }, /** * Extend setData to join in mapData. If the allAreas option is true, all areas * from the mapData are used, and those that don't correspond to a data value * are given null values. */ setData: function (data, redraw) { var options = this.options, mapData = options.mapData, joinBy = options.joinBy, joinByNull = joinBy === null, dataUsed = [], mapPoint, transform, mapTransforms, props, i; if (joinByNull) { joinBy = '_i'; } joinBy = this.joinBy = Highcharts.splat(joinBy); if (!joinBy[1]) { joinBy[1] = joinBy[0]; } // Pick up numeric values, add index if (data) { each(data, function (val, i) { if (typeof val === 'number') { data[i] = { value: val }; } if (joinByNull) { data[i]._i = i; } }); } this.getBox(data); if (mapData) { if (mapData.type === 'FeatureCollection') { if (mapData['hc-transform']) { this.chart.mapTransforms = mapTransforms = mapData['hc-transform']; // Cache cos/sin of transform rotation angle for (transform in mapTransforms) { if (mapTransforms.hasOwnProperty(transform) && transform.rotation) { transform.cosAngle = Math.cos(transform.rotation); transform.sinAngle = Math.sin(transform.rotation); } } } mapData = Highcharts.geojson(mapData, this.type, this); } this.getBox(mapData); this.mapData = mapData; this.mapMap = {}; for (i = 0; i < mapData.length; i++) { mapPoint = mapData[i]; props = mapPoint.properties; mapPoint._i = i; // Copy the property over to root for faster access if (joinBy[0] && props && props[joinBy[0]]) { mapPoint[joinBy[0]] = props[joinBy[0]]; } this.mapMap[mapPoint[joinBy[0]]] = mapPoint; } if (options.allAreas) { data = data || []; // Registered the point codes that actually hold data if (joinBy[1]) { each(data, function (point) { dataUsed.push(point[joinBy[1]]); }); } // Add those map points that don't correspond to data, which will be drawn as null points dataUsed = '|' + dataUsed.join('|') + '|'; // String search is faster than array.indexOf each(mapData, function (mapPoint) { if (!joinBy[0] || dataUsed.indexOf('|' + mapPoint[joinBy[0]] + '|') === -1) { data.push(merge(mapPoint, { value: null })); } }); } } Series.prototype.setData.call(this, data, redraw); }, /** * No graph for the map series */ drawGraph: noop, /** * We need the points' bounding boxes in order to draw the data labels, so * we skip it now and call it from drawPoints instead. */ drawDataLabels: noop, /** * Allow a quick redraw by just translating the area group. Used for zooming and panning * in capable browsers. */ doFullTranslate: function () { return this.isDirtyData || this.chart.isResizing || this.chart.renderer.isVML || !this.baseTrans; }, /** * Add the path option for data points. Find the max value for color calculation. */ translate: function () { var series = this, xAxis = series.xAxis, yAxis = series.yAxis, doFullTranslate = series.doFullTranslate(); series.generatePoints(); each(series.data, function (point) { // Record the middle point (loosely based on centroid), determined // by the middleX and middleY options. point.plotX = xAxis.toPixels(point._midX, true); point.plotY = yAxis.toPixels(point._midY, true); if (doFullTranslate) { point.shapeType = 'path'; point.shapeArgs = { d: series.translatePath(point.path) }; if (supportsVectorEffect) { point.shapeArgs['vector-effect'] = 'non-scaling-stroke'; } } }); series.translateColors(); }, /** * Use the drawPoints method of column, that is able to handle simple shapeArgs. * Extend it by assigning the tooltip position. */ drawPoints: function () { var series = this, xAxis = series.xAxis, yAxis = series.yAxis, group = series.group, chart = series.chart, renderer = chart.renderer, scaleX, scaleY, translateX, translateY, baseTrans = this.baseTrans; // Set a group that handles transform during zooming and panning in order to preserve clipping // on series.group if (!series.transformGroup) { series.transformGroup = renderer.g() .attr({ scaleX: 1, scaleY: 1 }) .add(group); series.transformGroup.survive = true; } // Draw the shapes again if (series.doFullTranslate()) { // Individual point actions if (chart.hasRendered && series.pointAttrToOptions.fill === 'color') { each(series.points, function (point) { // Reset color on update/redraw if (point.shapeArgs) { point.shapeArgs.fill = point.pointAttr[pick(point.state, '')].fill; // #3529 } }); } // If vector-effect is not supported, we set the stroke-width on the group element // and let all point graphics inherit. That way we don't have to iterate over all // points to update the stroke-width on zooming. if (!supportsVectorEffect) { each(series.points, function (point) { var attr = point.pointAttr['']; if (attr['stroke-width'] === series.pointAttr['']['stroke-width']) { attr['stroke-width'] = 'inherit'; } }); } // Draw them in transformGroup series.group = series.transformGroup; seriesTypes.column.prototype.drawPoints.apply(series); series.group = group; // Reset // Add class names each(series.points, function (point) { if (point.graphic) { if (point.name) { point.graphic.addClass('highcharts-name-' + point.name.replace(' ', '-').toLowerCase()); } if (point.properties && point.properties['hc-key']) { point.graphic.addClass('highcharts-key-' + point.properties['hc-key'].toLowerCase()); } if (!supportsVectorEffect) { point.graphic['stroke-widthSetter'] = noop; } } }); // Set the base for later scale-zooming. The originX and originY properties are the // axis values in the plot area's upper left corner. this.baseTrans = { originX: xAxis.min - xAxis.minPixelPadding / xAxis.transA, originY: yAxis.min - yAxis.minPixelPadding / yAxis.transA + (yAxis.reversed ? 0 : yAxis.len / yAxis.transA), transAX: xAxis.transA, transAY: yAxis.transA }; // Reset transformation in case we're doing a full translate (#3789) this.transformGroup.animate({ translateX: 0, translateY: 0, scaleX: 1, scaleY: 1 }); // Just update the scale and transform for better performance } else { scaleX = xAxis.transA / baseTrans.transAX; scaleY = yAxis.transA / baseTrans.transAY; translateX = xAxis.toPixels(baseTrans.originX, true); translateY = yAxis.toPixels(baseTrans.originY, true); // Handle rounding errors in normal view (#3789) if (scaleX > 0.99 && scaleX < 1.01 && scaleY > 0.99 && scaleY < 1.01) { scaleX = 1; scaleY = 1; translateX = Math.round(translateX); translateY = Math.round(translateY); } this.transformGroup.animate({ translateX: translateX, translateY: translateY, scaleX: scaleX, scaleY: scaleY }); } // Set the stroke-width directly on the group element so the children inherit it. We need to use // setAttribute directly, because the stroke-widthSetter method expects a stroke color also to be // set. if (!supportsVectorEffect) { series.group.element.setAttribute('stroke-width', series.options.borderWidth / (scaleX || 1)); } this.drawMapDataLabels(); }, /** * Draw the data labels. Special for maps is the time that the data labels are drawn (after points), * and the clipping of the dataLabelsGroup. */ drawMapDataLabels: function () { Series.prototype.drawDataLabels.call(this); if (this.dataLabelsGroup) { this.dataLabelsGroup.clip(this.chart.clipRect); } }, /** * Override render to throw in an async call in IE8. Otherwise it chokes on the US counties demo. */ render: function () { var series = this, render = Series.prototype.render; // Give IE8 some time to breathe. if (series.chart.renderer.isVML && series.data.length > 3000) { setTimeout(function () { render.call(series); }); } else { render.call(series); } }, /** * The initial animation for the map series. By default, animation is disabled. * Animation of map shapes is not at all supported in VML browsers. */ animate: function (init) { var chart = this.chart, animation = this.options.animation, group = this.group, xAxis = this.xAxis, yAxis = this.yAxis, left = xAxis.pos, top = yAxis.pos; if (chart.renderer.isSVG) { if (animation === true) { animation = { duration: 1000 }; } // Initialize the animation if (init) { // Scale down the group and place it in the center group.attr({ translateX: left + xAxis.len / 2, translateY: top + yAxis.len / 2, scaleX: 0.001, // #1499 scaleY: 0.001 }); // Run the animation } else { group.animate({ translateX: left, translateY: top, scaleX: 1, scaleY: 1 }, animation); // Delete this function to allow it only once this.animate = null; } } }, /** * Animate in the new series from the clicked point in the old series. * Depends on the drilldown.js module */ animateDrilldown: function (init) { var toBox = this.chart.plotBox, level = this.chart.drilldownLevels[this.chart.drilldownLevels.length - 1], fromBox = level.bBox, animationOptions = this.chart.options.drilldown.animation, scale; if (!init) { scale = Math.min(fromBox.width / toBox.width, fromBox.height / toBox.height); level.shapeArgs = { scaleX: scale, scaleY: scale, translateX: fromBox.x, translateY: fromBox.y }; each(this.points, function (point) { if (point.graphic) { point.graphic .attr(level.shapeArgs) .animate({ scaleX: 1, scaleY: 1, translateX: 0, translateY: 0 }, animationOptions); } }); this.animate = null; } }, drawLegendSymbol: LegendSymbolMixin.drawRectangle, /** * When drilling up, pull out the individual point graphics from the lower series * and animate them into the origin point in the upper series. */ animateDrillupFrom: function (level) { seriesTypes.column.prototype.animateDrillupFrom.call(this, level); }, /** * When drilling up, keep the upper series invisible until the lower series has * moved into place */ animateDrillupTo: function (init) { seriesTypes.column.prototype.animateDrillupTo.call(this, init); } })); /** * Highcharts module to hide overlapping data labels. This module is included in Highcharts. */ (function (H) { var Chart = H.Chart, each = H.each, pick = H.pick, addEvent = H.addEvent; // Collect potensial overlapping data labels. Stack labels probably don't need to be // considered because they are usually accompanied by data labels that lie inside the columns. Chart.prototype.callbacks.push(function (chart) { function collectAndHide() { var labels = []; each(chart.series, function (series) { var dlOptions = series.options.dataLabels, collections = series.dataLabelCollections || ['dataLabel']; // Range series have two collections if ((dlOptions.enabled || series._hasPointLabels) && !dlOptions.allowOverlap && series.visible) { // #3866 each(collections, function (coll) { each(series.points, function (point) { if (point[coll]) { point[coll].labelrank = pick(point.labelrank, point.shapeArgs && point.shapeArgs.height); // #4118 labels.push(point[coll]); } }); }); } }); chart.hideOverlappingLabels(labels); } // Do it now ... collectAndHide(); // ... and after each chart redraw addEvent(chart, 'redraw', collectAndHide); }); /** * Hide overlapping labels. Labels are moved and faded in and out on zoom to provide a smooth * visual imression. */ Chart.prototype.hideOverlappingLabels = function (labels) { var len = labels.length, label, i, j, label1, label2, isIntersecting, pos1, pos2, parent1, parent2, padding, intersectRect = function (x1, y1, w1, h1, x2, y2, w2, h2) { return !( x2 > x1 + w1 || x2 + w2 < x1 || y2 > y1 + h1 || y2 + h2 < y1 ); }; // Mark with initial opacity for (i = 0; i < len; i++) { label = labels[i]; if (label) { label.oldOpacity = label.opacity; label.newOpacity = 1; } } // Prevent a situation in a gradually rising slope, that each label // will hide the previous one because the previous one always has // lower rank. labels.sort(function (a, b) { return (b.labelrank || 0) - (a.labelrank || 0); }); // Detect overlapping labels for (i = 0; i < len; i++) { label1 = labels[i]; for (j = i + 1; j < len; ++j) { label2 = labels[j]; if (label1 && label2 && label1.placed && label2.placed && label1.newOpacity !== 0 && label2.newOpacity !== 0) { pos1 = label1.alignAttr; pos2 = label2.alignAttr; parent1 = label1.parentGroup; // Different panes have different positions parent2 = label2.parentGroup; padding = 2 * (label1.box ? 0 : label1.padding); // Substract the padding if no background or border (#4333) isIntersecting = intersectRect( pos1.x + parent1.translateX, pos1.y + parent1.translateY, label1.width - padding, label1.height - padding, pos2.x + parent2.translateX, pos2.y + parent2.translateY, label2.width - padding, label2.height - padding ); if (isIntersecting) { (label1.labelrank < label2.labelrank ? label1 : label2).newOpacity = 0; } } } } // Hide or show each(labels, function (label) { var complete, newOpacity; if (label) { newOpacity = label.newOpacity; if (label.oldOpacity !== newOpacity && label.placed) { // Make sure the label is completely hidden to avoid catching clicks (#4362) if (newOpacity) { label.show(true); } else { complete = function () { label.hide(); }; } // Animate or set the opacity label.alignAttr.opacity = newOpacity; label[label.isOld ? 'animate' : 'attr'](label.alignAttr, null, complete); } label.isOld = true; } }); }; }(Highcharts)); // Add events to the Chart object itself extend(Chart.prototype, { renderMapNavigation: function () { var chart = this, options = this.options.mapNavigation, buttons = options.buttons, n, button, buttonOptions, attr, states, stopEvent = function (e) { if (e) { if (e.preventDefault) { e.preventDefault(); } if (e.stopPropagation) { e.stopPropagation(); } e.cancelBubble = true; } }, outerHandler = function (e) { this.handler.call(chart, e); stopEvent(e); // Stop default click event (#4444) }; if (pick(options.enableButtons, options.enabled) && !chart.renderer.forExport) { for (n in buttons) { if (buttons.hasOwnProperty(n)) { buttonOptions = merge(options.buttonOptions, buttons[n]); attr = buttonOptions.theme; attr.style = merge(buttonOptions.theme.style, buttonOptions.style); // #3203 states = attr.states; button = chart.renderer.button( buttonOptions.text, 0, 0, outerHandler, attr, states && states.hover, states && states.select, 0, n === 'zoomIn' ? 'topbutton' : 'bottombutton' ) .attr({ width: buttonOptions.width, height: buttonOptions.height, title: chart.options.lang[n], zIndex: 5 }) .add(); button.handler = buttonOptions.onclick; button.align(extend(buttonOptions, { width: button.width, height: 2 * button.height }), null, buttonOptions.alignTo); addEvent(button.element, 'dblclick', stopEvent); // Stop double click event (#4444) } } } }, /** * Fit an inner box to an outer. If the inner box overflows left or right, align it to the sides of the * outer. If it overflows both sides, fit it within the outer. This is a pattern that occurs more places * in Highcharts, perhaps it should be elevated to a common utility function. */ fitToBox: function (inner, outer) { each([['x', 'width'], ['y', 'height']], function (dim) { var pos = dim[0], size = dim[1]; if (inner[pos] + inner[size] > outer[pos] + outer[size]) { // right overflow if (inner[size] > outer[size]) { // the general size is greater, fit fully to outer inner[size] = outer[size]; inner[pos] = outer[pos]; } else { // align right inner[pos] = outer[pos] + outer[size] - inner[size]; } } if (inner[size] > outer[size]) { inner[size] = outer[size]; } if (inner[pos] < outer[pos]) { inner[pos] = outer[pos]; } }); return inner; }, /** * Zoom the map in or out by a certain amount. Less than 1 zooms in, greater than 1 zooms out. */ mapZoom: function (howMuch, centerXArg, centerYArg, mouseX, mouseY) { /*if (this.isMapZooming) { this.mapZoomQueue = arguments; return; }*/ var chart = this, xAxis = chart.xAxis[0], xRange = xAxis.max - xAxis.min, centerX = pick(centerXArg, xAxis.min + xRange / 2), newXRange = xRange * howMuch, yAxis = chart.yAxis[0], yRange = yAxis.max - yAxis.min, centerY = pick(centerYArg, yAxis.min + yRange / 2), newYRange = yRange * howMuch, fixToX = mouseX ? ((mouseX - xAxis.pos) / xAxis.len) : 0.5, fixToY = mouseY ? ((mouseY - yAxis.pos) / yAxis.len) : 0.5, newXMin = centerX - newXRange * fixToX, newYMin = centerY - newYRange * fixToY, newExt = chart.fitToBox({ x: newXMin, y: newYMin, width: newXRange, height: newYRange }, { x: xAxis.dataMin, y: yAxis.dataMin, width: xAxis.dataMax - xAxis.dataMin, height: yAxis.dataMax - yAxis.dataMin }); // When mousewheel zooming, fix the point under the mouse if (mouseX) { xAxis.fixTo = [mouseX - xAxis.pos, centerXArg]; } if (mouseY) { yAxis.fixTo = [mouseY - yAxis.pos, centerYArg]; } // Zoom if (howMuch !== undefined) { xAxis.setExtremes(newExt.x, newExt.x + newExt.width, false); yAxis.setExtremes(newExt.y, newExt.y + newExt.height, false); // Reset zoom } else { xAxis.setExtremes(undefined, undefined, false); yAxis.setExtremes(undefined, undefined, false); } // Prevent zooming until this one is finished animating /*chart.holdMapZoom = true; setTimeout(function () { chart.holdMapZoom = false; }, 200);*/ /*delay = animation ? animation.duration || 500 : 0; if (delay) { chart.isMapZooming = true; setTimeout(function () { chart.isMapZooming = false; if (chart.mapZoomQueue) { chart.mapZoom.apply(chart, chart.mapZoomQueue); } chart.mapZoomQueue = null; }, delay); }*/ chart.redraw(); } }); /** * Extend the Chart.render method to add zooming and panning */ wrap(Chart.prototype, 'render', function (proceed) { var chart = this, mapNavigation = chart.options.mapNavigation; // Render the plus and minus buttons. Doing this before the shapes makes getBBox much quicker, at least in Chrome. chart.renderMapNavigation(); proceed.call(chart); // Add the double click event if (pick(mapNavigation.enableDoubleClickZoom, mapNavigation.enabled) || mapNavigation.enableDoubleClickZoomTo) { addEvent(chart.container, 'dblclick', function (e) { chart.pointer.onContainerDblClick(e); }); } // Add the mousewheel event if (pick(mapNavigation.enableMouseWheelZoom, mapNavigation.enabled)) { addEvent(chart.container, doc.onmousewheel === undefined ? 'DOMMouseScroll' : 'mousewheel', function (e) { chart.pointer.onContainerMouseWheel(e); return false; }); } }); // Extend the Pointer extend(Pointer.prototype, { /** * The event handler for the doubleclick event */ onContainerDblClick: function (e) { var chart = this.chart; e = this.normalize(e); if (chart.options.mapNavigation.enableDoubleClickZoomTo) { if (chart.pointer.inClass(e.target, 'highcharts-tracker')) { chart.hoverPoint.zoomTo(); } } else if (chart.isInsidePlot(e.chartX - chart.plotLeft, e.chartY - chart.plotTop)) { chart.mapZoom( 0.5, chart.xAxis[0].toValue(e.chartX), chart.yAxis[0].toValue(e.chartY), e.chartX, e.chartY ); } }, /** * The event handler for the mouse scroll event */ onContainerMouseWheel: function (e) { var chart = this.chart, delta; e = this.normalize(e); // Firefox uses e.detail, WebKit and IE uses wheelDelta delta = e.detail || -(e.wheelDelta / 120); if (chart.isInsidePlot(e.chartX - chart.plotLeft, e.chartY - chart.plotTop)) { chart.mapZoom( //delta > 0 ? 2 : 0.5, Math.pow(2, delta), chart.xAxis[0].toValue(e.chartX), chart.yAxis[0].toValue(e.chartY), e.chartX, e.chartY ); } } }); // Implement the pinchType option wrap(Pointer.prototype, 'init', function (proceed, chart, options) { proceed.call(this, chart, options); // Pinch status if (pick(options.mapNavigation.enableTouchZoom, options.mapNavigation.enabled)) { this.pinchX = this.pinchHor = this.pinchY = this.pinchVert = this.hasZoom = true; } }); // Extend the pinchTranslate method to preserve fixed ratio when zooming wrap(Pointer.prototype, 'pinchTranslate', function (proceed, pinchDown, touches, transform, selectionMarker, clip, lastValidTouch) { var xBigger; proceed.call(this, pinchDown, touches, transform, selectionMarker, clip, lastValidTouch); // Keep ratio if (this.chart.options.chart.type === 'map' && this.hasZoom) { xBigger = transform.scaleX > transform.scaleY; this.pinchTranslateDirection( !xBigger, pinchDown, touches, transform, selectionMarker, clip, lastValidTouch, xBigger ? transform.scaleX : transform.scaleY ); } }); // The mapline series type defaultPlotOptions.mapline = merge(defaultPlotOptions.map, { lineWidth: 1, fillColor: 'none' }); seriesTypes.mapline = extendClass(seriesTypes.map, { type: 'mapline', pointAttrToOptions: { // mapping between SVG attributes and the corresponding options stroke: 'color', 'stroke-width': 'lineWidth', fill: 'fillColor', dashstyle: 'dashStyle' }, drawLegendSymbol: seriesTypes.line.prototype.drawLegendSymbol }); // The mappoint series type defaultPlotOptions.mappoint = merge(defaultPlotOptions.scatter, { dataLabels: { enabled: true, formatter: function () { // #2945 return this.point.name; }, crop: false, defer: false, overflow: false, style: { color: '#000000' } } }); seriesTypes.mappoint = extendClass(seriesTypes.scatter, { type: 'mappoint', forceDL: true, pointClass: extendClass(Point, { applyOptions: function (options, x) { var point = Point.prototype.applyOptions.call(this, options, x); if (options.lat !== undefined && options.lon !== undefined) { point = extend(point, this.series.chart.fromLatLonToPoint(point)); } return point; } }) }); /* **************************************************************************** * Start Bubble series code * *****************************************************************************/ // 1 - set default options defaultPlotOptions.bubble = merge(defaultPlotOptions.scatter, { dataLabels: { formatter: function () { // #2945 return this.point.z; }, inside: true, verticalAlign: 'middle' }, // displayNegative: true, marker: { // fillOpacity: 0.5, lineColor: null, // inherit from series.color lineWidth: 1 }, minSize: 8, maxSize: '20%', // negativeColor: null, // sizeBy: 'area' softThreshold: false, states: { hover: { halo: { size: 5 } } }, tooltip: { pointFormat: '({point.x}, {point.y}), Size: {point.z}' }, turboThreshold: 0, zThreshold: 0, zoneAxis: 'z' }); var BubblePoint = extendClass(Point, { haloPath: function () { return Point.prototype.haloPath.call(this, this.shapeArgs.r + this.series.options.states.hover.halo.size); }, ttBelow: false }); // 2 - Create the series object seriesTypes.bubble = extendClass(seriesTypes.scatter, { type: 'bubble', pointClass: BubblePoint, pointArrayMap: ['y', 'z'], parallelArrays: ['x', 'y', 'z'], trackerGroups: ['group', 'dataLabelsGroup'], bubblePadding: true, zoneAxis: 'z', /** * Mapping between SVG attributes and the corresponding options */ pointAttrToOptions: { stroke: 'lineColor', 'stroke-width': 'lineWidth', fill: 'fillColor' }, /** * Apply the fillOpacity to all fill positions */ applyOpacity: function (fill) { var markerOptions = this.options.marker, fillOpacity = pick(markerOptions.fillOpacity, 0.5); // When called from Legend.colorizeItem, the fill isn't predefined fill = fill || markerOptions.fillColor || this.color; if (fillOpacity !== 1) { fill = Color(fill).setOpacity(fillOpacity).get('rgba'); } return fill; }, /** * Extend the convertAttribs method by applying opacity to the fill */ convertAttribs: function () { var obj = Series.prototype.convertAttribs.apply(this, arguments); obj.fill = this.applyOpacity(obj.fill); return obj; }, /** * Get the radius for each point based on the minSize, maxSize and each point's Z value. This * must be done prior to Series.translate because the axis needs to add padding in * accordance with the point sizes. */ getRadii: function (zMin, zMax, minSize, maxSize) { var len, i, pos, zData = this.zData, radii = [], options = this.options, sizeByArea = options.sizeBy !== 'width', zThreshold = options.zThreshold, zRange = zMax - zMin, value, radius; // Set the shape type and arguments to be picked up in drawPoints for (i = 0, len = zData.length; i < len; i++) { value = zData[i]; // When sizing by threshold, the absolute value of z determines the size // of the bubble. if (options.sizeByAbsoluteValue && value !== null) { value = Math.abs(value - zThreshold); zMax = Math.max(zMax - zThreshold, Math.abs(zMin - zThreshold)); zMin = 0; } if (value === null) { radius = null; // Issue #4419 - if value is less than zMin, push a radius that's always smaller than the minimum size } else if (value < zMin) { radius = minSize / 2 - 1; } else { // Relative size, a number between 0 and 1 pos = zRange > 0 ? (value - zMin) / zRange : 0.5; if (sizeByArea && pos >= 0) { pos = Math.sqrt(pos); } radius = math.ceil(minSize + pos * (maxSize - minSize)) / 2; } radii.push(radius); } this.radii = radii; }, /** * Perform animation on the bubbles */ animate: function (init) { var animation = this.options.animation; if (!init) { // run the animation each(this.points, function (point) { var graphic = point.graphic, shapeArgs = point.shapeArgs; if (graphic && shapeArgs) { // start values graphic.attr('r', 1); // animate graphic.animate({ r: shapeArgs.r }, animation); } }); // delete this function to allow it only once this.animate = null; } }, /** * Extend the base translate method to handle bubble size */ translate: function () { var i, data = this.data, point, radius, radii = this.radii; // Run the parent method seriesTypes.scatter.prototype.translate.call(this); // Set the shape type and arguments to be picked up in drawPoints i = data.length; while (i--) { point = data[i]; radius = radii ? radii[i] : 0; // #1737 if (typeof radius === 'number' && radius >= this.minPxSize / 2) { // Shape arguments point.shapeType = 'circle'; point.shapeArgs = { x: point.plotX, y: point.plotY, r: radius }; // Alignment box for the data label point.dlBox = { x: point.plotX - radius, y: point.plotY - radius, width: 2 * radius, height: 2 * radius }; } else { // below zThreshold or z = null point.shapeArgs = point.plotY = point.dlBox = UNDEFINED; // #1691 } } }, /** * Get the series' symbol in the legend * * @param {Object} legend The legend object * @param {Object} item The series (this) or point */ drawLegendSymbol: function (legend, item) { var renderer = this.chart.renderer, radius = renderer.fontMetrics(legend.itemStyle.fontSize).f / 2; item.legendSymbol = renderer.circle( radius, legend.baseline - radius, radius ).attr({ zIndex: 3 }).add(item.legendGroup); item.legendSymbol.isMarker = true; }, drawPoints: seriesTypes.column.prototype.drawPoints, alignDataLabel: seriesTypes.column.prototype.alignDataLabel, buildKDTree: noop, applyZones: noop }); /** * Add logic to pad each axis with the amount of pixels * necessary to avoid the bubbles to overflow. */ Axis.prototype.beforePadding = function () { var axis = this, axisLength = this.len, chart = this.chart, pxMin = 0, pxMax = axisLength, isXAxis = this.isXAxis, dataKey = isXAxis ? 'xData' : 'yData', min = this.min, extremes = {}, smallestSize = math.min(chart.plotWidth, chart.plotHeight), zMin = Number.MAX_VALUE, zMax = -Number.MAX_VALUE, range = this.max - min, transA = axisLength / range, activeSeries = []; // Handle padding on the second pass, or on redraw each(this.series, function (series) { var seriesOptions = series.options, zData; if (series.bubblePadding && (series.visible || !chart.options.chart.ignoreHiddenSeries)) { // Correction for #1673 axis.allowZoomOutside = true; // Cache it activeSeries.push(series); if (isXAxis) { // because X axis is evaluated first // For each series, translate the size extremes to pixel values each(['minSize', 'maxSize'], function (prop) { var length = seriesOptions[prop], isPercent = /%$/.test(length); length = pInt(length); extremes[prop] = isPercent ? smallestSize * length / 100 : length; }); series.minPxSize = extremes.minSize; series.maxPxSize = extremes.maxSize; // Find the min and max Z zData = series.zData; if (zData.length) { // #1735 zMin = pick(seriesOptions.zMin, math.min( zMin, math.max( arrayMin(zData), seriesOptions.displayNegative === false ? seriesOptions.zThreshold : -Number.MAX_VALUE ) )); zMax = pick(seriesOptions.zMax, math.max(zMax, arrayMax(zData))); } } } }); each(activeSeries, function (series) { var data = series[dataKey], i = data.length, radius; if (isXAxis) { series.getRadii(zMin, zMax, series.minPxSize, series.maxPxSize); } if (range > 0) { while (i--) { if (typeof data[i] === 'number') { radius = series.radii[i]; pxMin = Math.min(((data[i] - min) * transA) - radius, pxMin); pxMax = Math.max(((data[i] - min) * transA) + radius, pxMax); } } } }); if (activeSeries.length && range > 0 && !this.isLog) { pxMax -= axisLength; transA *= (axisLength + pxMin - pxMax) / axisLength; each([['min', 'userMin', pxMin], ['max', 'userMax', pxMax]], function (keys) { if (pick(axis.options[keys[0]], axis[keys[1]]) === UNDEFINED) { axis[keys[0]] += keys[2] / transA; } }); } }; /* **************************************************************************** * End Bubble series code * *****************************************************************************/ // The mapbubble series type if (seriesTypes.bubble) { defaultPlotOptions.mapbubble = merge(defaultPlotOptions.bubble, { animationLimit: 500, tooltip: { pointFormat: '{point.name}: {point.z}' } }); seriesTypes.mapbubble = extendClass(seriesTypes.bubble, { pointClass: extendClass(Point, { applyOptions: function (options, x) { var point; if (options && options.lat !== undefined && options.lon !== undefined) { point = Point.prototype.applyOptions.call(this, options, x); point = extend(point, this.series.chart.fromLatLonToPoint(point)); } else { point = MapAreaPoint.prototype.applyOptions.call(this, options, x); } return point; }, ttBelow: false }), xyFromShape: true, type: 'mapbubble', pointArrayMap: ['z'], // If one single value is passed, it is interpreted as z /** * Return the map area identified by the dataJoinBy option */ getMapData: seriesTypes.map.prototype.getMapData, getBox: seriesTypes.map.prototype.getBox, setData: seriesTypes.map.prototype.setData }); } /** * Test for point in polygon. Polygon defined as array of [x,y] points. */ function pointInPolygon(point, polygon) { var i, j, rel1, rel2, c = false, x = point.x, y = point.y; for (i = 0, j = polygon.length - 1; i < polygon.length; j = i++) { rel1 = polygon[i][1] > y; rel2 = polygon[j][1] > y; if (rel1 !== rel2 && (x < (polygon[j][0] - polygon[i][0]) * (y - polygon[i][1]) / (polygon[j][1] - polygon[i][1]) + polygon[i][0])) { c = !c; } } return c; } /** * Get point from latLon using specified transform definition */ Chart.prototype.transformFromLatLon = function (latLon, transform) { if (win.proj4 === undefined) { error(21); return { x: 0, y: null }; } var projected = win.proj4(transform.crs, [latLon.lon, latLon.lat]), cosAngle = transform.cosAngle || (transform.rotation && Math.cos(transform.rotation)), sinAngle = transform.sinAngle || (transform.rotation && Math.sin(transform.rotation)), rotated = transform.rotation ? [projected[0] * cosAngle + projected[1] * sinAngle, -projected[0] * sinAngle + projected[1] * cosAngle] : projected; return { x: ((rotated[0] - (transform.xoffset || 0)) * (transform.scale || 1) + (transform.xpan || 0)) * (transform.jsonres || 1) + (transform.jsonmarginX || 0), y: (((transform.yoffset || 0) - rotated[1]) * (transform.scale || 1) + (transform.ypan || 0)) * (transform.jsonres || 1) - (transform.jsonmarginY || 0) }; }; /** * Get latLon from point using specified transform definition */ Chart.prototype.transformToLatLon = function (point, transform) { if (win.proj4 === undefined) { error(21); return; } var normalized = { x: ((point.x - (transform.jsonmarginX || 0)) / (transform.jsonres || 1) - (transform.xpan || 0)) / (transform.scale || 1) + (transform.xoffset || 0), y: ((-point.y - (transform.jsonmarginY || 0)) / (transform.jsonres || 1) + (transform.ypan || 0)) / (transform.scale || 1) + (transform.yoffset || 0) }, cosAngle = transform.cosAngle || (transform.rotation && Math.cos(transform.rotation)), sinAngle = transform.sinAngle || (transform.rotation && Math.sin(transform.rotation)), // Note: Inverted sinAngle to reverse rotation direction projected = win.proj4(transform.crs, 'WGS84', transform.rotation ? { x: normalized.x * cosAngle + normalized.y * -sinAngle, y: normalized.x * sinAngle + normalized.y * cosAngle } : normalized); return { lat: projected.y, lon: projected.x }; }; Chart.prototype.fromPointToLatLon = function (point) { var transforms = this.mapTransforms, transform; if (!transforms) { error(22); return; } for (transform in transforms) { if (transforms.hasOwnProperty(transform) && transforms[transform].hitZone && pointInPolygon({ x: point.x, y: -point.y }, transforms[transform].hitZone.coordinates[0])) { return this.transformToLatLon(point, transforms[transform]); } } return this.transformToLatLon(point, transforms['default']); // eslint-disable-line dot-notation }; Chart.prototype.fromLatLonToPoint = function (latLon) { var transforms = this.mapTransforms, transform, coords; if (!transforms) { error(22); return { x: 0, y: null }; } for (transform in transforms) { if (transforms.hasOwnProperty(transform) && transforms[transform].hitZone) { coords = this.transformFromLatLon(latLon, transforms[transform]); if (pointInPolygon({ x: coords.x, y: -coords.y }, transforms[transform].hitZone.coordinates[0])) { return coords; } } } return this.transformFromLatLon(latLon, transforms['default']); // eslint-disable-line dot-notation }; /** * Convert a geojson object to map data of a given Highcharts type (map, mappoint or mapline). */ Highcharts.geojson = function (geojson, hType, series) { var mapData = [], path = [], polygonToPath = function (polygon) { var i, len = polygon.length; path.push('M'); for (i = 0; i < len; i++) { if (i === 1) { path.push('L'); } path.push(polygon[i][0], -polygon[i][1]); } }; hType = hType || 'map'; each(geojson.features, function (feature) { var geometry = feature.geometry, type = geometry.type, coordinates = geometry.coordinates, properties = feature.properties, point; path = []; if (hType === 'map' || hType === 'mapbubble') { if (type === 'Polygon') { each(coordinates, polygonToPath); path.push('Z'); } else if (type === 'MultiPolygon') { each(coordinates, function (items) { each(items, polygonToPath); }); path.push('Z'); } if (path.length) { point = { path: path }; } } else if (hType === 'mapline') { if (type === 'LineString') { polygonToPath(coordinates); } else if (type === 'MultiLineString') { each(coordinates, polygonToPath); } if (path.length) { point = { path: path }; } } else if (hType === 'mappoint') { if (type === 'Point') { point = { x: coordinates[0], y: -coordinates[1] }; } } if (point) { mapData.push(extend(point, { name: properties.name || properties.NAME, properties: properties })); } }); // Create a credits text that includes map source, to be picked up in Chart.showCredits if (series && geojson.copyrightShort) { series.chart.mapCredits = format(series.chart.options.credits.mapText, { geojson: geojson }); series.chart.mapCreditsFull = format(series.chart.options.credits.mapTextFull, { geojson: geojson }); } return mapData; }; /** * Override showCredits to include map source by default */ wrap(Chart.prototype, 'showCredits', function (proceed, credits) { // Disable credits link if map credits enabled. This to allow for in-text anchors. if (this.mapCredits) { credits.href = null; } proceed.call(this, Highcharts.merge(credits, { text: credits.text + (this.mapCredits || '') // Add map credits to credits text })); // Add full map credits to hover if (this.credits && this.mapCreditsFull) { this.credits.attr({ title: this.mapCreditsFull }); } }); // Add language extend(defaultOptions.lang, { zoomIn: 'Zoom in', zoomOut: 'Zoom out' }); // Set the default map navigation options defaultOptions.mapNavigation = { buttonOptions: { alignTo: 'plotBox', align: 'left', verticalAlign: 'top', x: 0, width: 18, height: 18, style: { fontSize: '15px', fontWeight: 'bold', textAlign: 'center' }, theme: { 'stroke-width': 1 } }, buttons: { zoomIn: { onclick: function () { this.mapZoom(0.5); }, text: '+', y: 0 }, zoomOut: { onclick: function () { this.mapZoom(2); }, text: '-', y: 28 } } // enabled: false, // enableButtons: null, // inherit from enabled // enableTouchZoom: null, // inherit from enabled // enableDoubleClickZoom: null, // inherit from enabled // enableDoubleClickZoomTo: false // enableMouseWheelZoom: null, // inherit from enabled }; /** * Utility for reading SVG paths directly. */ Highcharts.splitPath = function (path) { var i; // Move letters apart path = path.replace(/([A-Za-z])/g, ' $1 '); // Trim path = path.replace(/^\s*/, '').replace(/\s*$/, ''); // Split on spaces and commas path = path.split(/[ ,]+/); // Parse numbers for (i = 0; i < path.length; i++) { if (!/[a-zA-Z]/.test(path[i])) { path[i] = parseFloat(path[i]); } } return path; }; // A placeholder for map definitions Highcharts.maps = {}; // Create symbols for the zoom buttons function selectiveRoundedRect(x, y, w, h, rTopLeft, rTopRight, rBottomRight, rBottomLeft) { return ['M', x + rTopLeft, y, // top side 'L', x + w - rTopRight, y, // top right corner 'C', x + w - rTopRight / 2, y, x + w, y + rTopRight / 2, x + w, y + rTopRight, // right side 'L', x + w, y + h - rBottomRight, // bottom right corner 'C', x + w, y + h - rBottomRight / 2, x + w - rBottomRight / 2, y + h, x + w - rBottomRight, y + h, // bottom side 'L', x + rBottomLeft, y + h, // bottom left corner 'C', x + rBottomLeft / 2, y + h, x, y + h - rBottomLeft / 2, x, y + h - rBottomLeft, // left side 'L', x, y + rTopLeft, // top left corner 'C', x, y + rTopLeft / 2, x + rTopLeft / 2, y, x + rTopLeft, y, 'Z' ]; } SVGRenderer.prototype.symbols.topbutton = function (x, y, w, h, attr) { return selectiveRoundedRect(x - 1, y - 1, w, h, attr.r, attr.r, 0, 0); }; SVGRenderer.prototype.symbols.bottombutton = function (x, y, w, h, attr) { return selectiveRoundedRect(x - 1, y - 1, w, h, 0, 0, attr.r, attr.r); }; // The symbol callbacks are generated on the SVGRenderer object in all browsers. Even // VML browsers need this in order to generate shapes in export. Now share // them with the VMLRenderer. if (Renderer === VMLRenderer) { each(['topbutton', 'bottombutton'], function (shape) { VMLRenderer.prototype.symbols[shape] = SVGRenderer.prototype.symbols[shape]; }); } /** * A wrapper for Chart with all the default values for a Map */ Highcharts.Map = Highcharts.mapChart = function (a, b, c) { var hasRenderToArg = typeof a === 'string' || a.nodeName, options = arguments[hasRenderToArg ? 1 : 0], hiddenAxis = { endOnTick: false, gridLineWidth: 0, lineWidth: 0, minPadding: 0, maxPadding: 0, startOnTick: false, title: null, tickPositions: [] }, seriesOptions, defaultCreditsOptions = Highcharts.getOptions().credits; /* For visual testing hiddenAxis.gridLineWidth = 1; hiddenAxis.gridZIndex = 10; hiddenAxis.tickPositions = undefined; // */ // Don't merge the data seriesOptions = options.series; options.series = null; options = merge( { chart: { panning: 'xy', type: 'map' }, credits: { mapText: pick(defaultCreditsOptions.mapText, ' \u00a9 <a href="{geojson.copyrightUrl}">{geojson.copyrightShort}</a>'), mapTextFull: pick(defaultCreditsOptions.mapTextFull, '{geojson.copyright}') }, xAxis: hiddenAxis, yAxis: merge(hiddenAxis, { reversed: true }) }, options, // user's options { // forced options chart: { inverted: false, alignTicks: false } } ); options.series = seriesOptions; return hasRenderToArg ? new Chart(a, options, c) : new Chart(options, b); }; /** * Extend the default options with map options */ defaultOptions.plotOptions.heatmap = merge(defaultOptions.plotOptions.scatter, { animation: false, borderWidth: 0, nullColor: '#F8F8F8', dataLabels: { formatter: function () { // #2945 return this.point.value; }, inside: true, verticalAlign: 'middle', crop: false, overflow: false, padding: 0 // #3837 }, marker: null, pointRange: null, // dynamically set to colsize by default tooltip: { pointFormat: '{point.x}, {point.y}: {point.value}<br/>' }, states: { normal: { animation: true }, hover: { halo: false, // #3406, halo is not required on heatmaps brightness: 0.2 } } }); // The Heatmap series type seriesTypes.heatmap = extendClass(seriesTypes.scatter, merge(colorSeriesMixin, { type: 'heatmap', pointArrayMap: ['y', 'value'], hasPointSpecificOptions: true, pointClass: extendClass(Point, colorPointMixin), supportsDrilldown: true, getExtremesFromAll: true, directTouch: true, /** * Override the init method to add point ranges on both axes. */ init: function () { var options; seriesTypes.scatter.prototype.init.apply(this, arguments); options = this.options; options.pointRange = pick(options.pointRange, options.colsize || 1); // #3758, prevent resetting in setData this.yAxis.axisPointRange = options.rowsize || 1; // general point range }, translate: function () { var series = this, options = series.options, xAxis = series.xAxis, yAxis = series.yAxis, between = function (x, a, b) { return Math.min(Math.max(a, x), b); }; series.generatePoints(); each(series.points, function (point) { var xPad = (options.colsize || 1) / 2, yPad = (options.rowsize || 1) / 2, x1 = between(Math.round(xAxis.len - xAxis.translate(point.x - xPad, 0, 1, 0, 1)), 0, xAxis.len), x2 = between(Math.round(xAxis.len - xAxis.translate(point.x + xPad, 0, 1, 0, 1)), 0, xAxis.len), y1 = between(Math.round(yAxis.translate(point.y - yPad, 0, 1, 0, 1)), 0, yAxis.len), y2 = between(Math.round(yAxis.translate(point.y + yPad, 0, 1, 0, 1)), 0, yAxis.len); // Set plotX and plotY for use in K-D-Tree and more point.plotX = point.clientX = (x1 + x2) / 2; point.plotY = (y1 + y2) / 2; point.shapeType = 'rect'; point.shapeArgs = { x: Math.min(x1, x2), y: Math.min(y1, y2), width: Math.abs(x2 - x1), height: Math.abs(y2 - y1) }; }); series.translateColors(); // Make sure colors are updated on colorAxis update (#2893) if (this.chart.hasRendered) { each(series.points, function (point) { point.shapeArgs.fill = point.options.color || point.color; // #3311 }); } }, drawPoints: seriesTypes.column.prototype.drawPoints, animate: noop, getBox: noop, drawLegendSymbol: LegendSymbolMixin.drawRectangle, getExtremes: function () { // Get the extremes from the value data Series.prototype.getExtremes.call(this, this.valueData); this.valueMin = this.dataMin; this.valueMax = this.dataMax; // Get the extremes from the y data Series.prototype.getExtremes.call(this); } })); /** * TrackerMixin for points and graphs */ var TrackerMixin = Highcharts.TrackerMixin = { drawTrackerPoint: function () { var series = this, chart = series.chart, pointer = chart.pointer, cursor = series.options.cursor, css = cursor && { cursor: cursor }, onMouseOver = function (e) { var target = e.target, point; while (target && !point) { point = target.point; target = target.parentNode; } if (point !== UNDEFINED && point !== chart.hoverPoint) { // undefined on graph in scatterchart point.onMouseOver(e); } }; // Add reference to the point each(series.points, function (point) { if (point.graphic) { point.graphic.element.point = point; } if (point.dataLabel) { point.dataLabel.element.point = point; } }); // Add the event listeners, we need to do this only once if (!series._hasTracking) { each(series.trackerGroups, function (key) { if (series[key]) { // we don't always have dataLabelsGroup series[key] .addClass(PREFIX + 'tracker') .on('mouseover', onMouseOver) .on('mouseout', function (e) { pointer.onTrackerMouseOut(e); }) .css(css); if (hasTouch) { series[key].on('touchstart', onMouseOver); } } }); series._hasTracking = true; } }, /** * Draw the tracker object that sits above all data labels and markers to * track mouse events on the graph or points. For the line type charts * the tracker uses the same graphPath, but with a greater stroke width * for better control. */ drawTrackerGraph: function () { var series = this, options = series.options, trackByArea = options.trackByArea, trackerPath = [].concat(trackByArea ? series.areaPath : series.graphPath), trackerPathLength = trackerPath.length, chart = series.chart, pointer = chart.pointer, renderer = chart.renderer, snap = chart.options.tooltip.snap, tracker = series.tracker, cursor = options.cursor, css = cursor && { cursor: cursor }, i, onMouseOver = function () { if (chart.hoverSeries !== series) { series.onMouseOver(); } }, /* * Empirical lowest possible opacities for TRACKER_FILL for an element to stay invisible but clickable * IE6: 0.002 * IE7: 0.002 * IE8: 0.002 * IE9: 0.00000000001 (unlimited) * IE10: 0.0001 (exporting only) * FF: 0.00000000001 (unlimited) * Chrome: 0.000001 * Safari: 0.000001 * Opera: 0.00000000001 (unlimited) */ TRACKER_FILL = 'rgba(192,192,192,' + (hasSVG ? 0.0001 : 0.002) + ')'; // Extend end points. A better way would be to use round linecaps, // but those are not clickable in VML. if (trackerPathLength && !trackByArea) { i = trackerPathLength + 1; while (i--) { if (trackerPath[i] === M) { // extend left side trackerPath.splice(i + 1, 0, trackerPath[i + 1] - snap, trackerPath[i + 2], L); } if ((i && trackerPath[i] === M) || i === trackerPathLength) { // extend right side trackerPath.splice(i, 0, L, trackerPath[i - 2] + snap, trackerPath[i - 1]); } } } // handle single points /*for (i = 0; i < singlePoints.length; i++) { singlePoint = singlePoints[i]; trackerPath.push(M, singlePoint.plotX - snap, singlePoint.plotY, L, singlePoint.plotX + snap, singlePoint.plotY); }*/ // draw the tracker if (tracker) { tracker.attr({ d: trackerPath }); } else { // create series.tracker = renderer.path(trackerPath) .attr({ 'stroke-linejoin': 'round', // #1225 visibility: series.visible ? VISIBLE : HIDDEN, stroke: TRACKER_FILL, fill: trackByArea ? TRACKER_FILL : NONE, 'stroke-width': options.lineWidth + (trackByArea ? 0 : 2 * snap), zIndex: 2 }) .add(series.group); // The tracker is added to the series group, which is clipped, but is covered // by the marker group. So the marker group also needs to capture events. each([series.tracker, series.markerGroup], function (tracker) { tracker.addClass(PREFIX + 'tracker') .on('mouseover', onMouseOver) .on('mouseout', function (e) { pointer.onTrackerMouseOut(e); }) .css(css); if (hasTouch) { tracker.on('touchstart', onMouseOver); } }); } } }; /* End TrackerMixin */ /** * Add tracking event listener to the series group, so the point graphics * themselves act as trackers */ if (seriesTypes.column) { ColumnSeries.prototype.drawTracker = TrackerMixin.drawTrackerPoint; } if (seriesTypes.pie) { seriesTypes.pie.prototype.drawTracker = TrackerMixin.drawTrackerPoint; } if (seriesTypes.scatter) { ScatterSeries.prototype.drawTracker = TrackerMixin.drawTrackerPoint; } /* * Extend Legend for item events */ extend(Legend.prototype, { setItemEvents: function (item, legendItem, useHTML, itemStyle, itemHiddenStyle) { var legend = this; // Set the events on the item group, or in case of useHTML, the item itself (#1249) (useHTML ? legendItem : item.legendGroup).on('mouseover', function () { item.setState(HOVER_STATE); legendItem.css(legend.options.itemHoverStyle); }) .on('mouseout', function () { legendItem.css(item.visible ? itemStyle : itemHiddenStyle); item.setState(); }) .on('click', function (event) { var strLegendItemClick = 'legendItemClick', fnLegendItemClick = function () { if (item.setVisible) { item.setVisible(); } }; // Pass over the click/touch event. #4. event = { browserEvent: event }; // click the name or symbol if (item.firePointEvent) { // point item.firePointEvent(strLegendItemClick, event, fnLegendItemClick); } else { fireEvent(item, strLegendItemClick, event, fnLegendItemClick); } }); }, createCheckboxForItem: function (item) { var legend = this; item.checkbox = createElement('input', { type: 'checkbox', checked: item.selected, defaultChecked: item.selected // required by IE7 }, legend.options.itemCheckboxStyle, legend.chart.container); addEvent(item.checkbox, 'click', function (event) { var target = event.target; fireEvent( item.series || item, 'checkboxClick', { // #3712 checked: target.checked, item: item }, function () { item.select(); } ); }); } }); /* * Add pointer cursor to legend itemstyle in defaultOptions */ defaultOptions.legend.itemStyle.cursor = 'pointer'; /* * Extend the Chart object with interaction */ extend(Chart.prototype, { /** * Display the zoom button */ showResetZoom: function () { var chart = this, lang = defaultOptions.lang, btnOptions = chart.options.chart.resetZoomButton, theme = btnOptions.theme, states = theme.states, alignTo = btnOptions.relativeTo === 'chart' ? null : 'plotBox'; function zoomOut() { chart.zoomOut(); } this.resetZoomButton = chart.renderer.button(lang.resetZoom, null, null, zoomOut, theme, states && states.hover) .attr({ align: btnOptions.position.align, title: lang.resetZoomTitle }) .add() .align(btnOptions.position, false, alignTo); }, /** * Zoom out to 1:1 */ zoomOut: function () { var chart = this; fireEvent(chart, 'selection', { resetSelection: true }, function () { chart.zoom(); }); }, /** * Zoom into a given portion of the chart given by axis coordinates * @param {Object} event */ zoom: function (event) { var chart = this, hasZoomed, pointer = chart.pointer, displayButton = false, resetZoomButton; // If zoom is called with no arguments, reset the axes if (!event || event.resetSelection) { each(chart.axes, function (axis) { hasZoomed = axis.zoom(); }); } else { // else, zoom in on all axes each(event.xAxis.concat(event.yAxis), function (axisData) { var axis = axisData.axis, isXAxis = axis.isXAxis; // don't zoom more than minRange if (pointer[isXAxis ? 'zoomX' : 'zoomY'] || pointer[isXAxis ? 'pinchX' : 'pinchY']) { hasZoomed = axis.zoom(axisData.min, axisData.max); if (axis.displayBtn) { displayButton = true; } } }); } // Show or hide the Reset zoom button resetZoomButton = chart.resetZoomButton; if (displayButton && !resetZoomButton) { chart.showResetZoom(); } else if (!displayButton && isObject(resetZoomButton)) { chart.resetZoomButton = resetZoomButton.destroy(); } // Redraw if (hasZoomed) { chart.redraw( pick(chart.options.chart.animation, event && event.animation, chart.pointCount < 100) // animation ); } }, /** * Pan the chart by dragging the mouse across the pane. This function is called * on mouse move, and the distance to pan is computed from chartX compared to * the first chartX position in the dragging operation. */ pan: function (e, panning) { var chart = this, hoverPoints = chart.hoverPoints, doRedraw; // remove active points for shared tooltip if (hoverPoints) { each(hoverPoints, function (point) { point.setState(); }); } each(panning === 'xy' ? [1, 0] : [1], function (isX) { // xy is used in maps var axis = chart[isX ? 'xAxis' : 'yAxis'][0], horiz = axis.horiz, mousePos = e[horiz ? 'chartX' : 'chartY'], mouseDown = horiz ? 'mouseDownX' : 'mouseDownY', startPos = chart[mouseDown], halfPointRange = (axis.pointRange || 0) / 2, extremes = axis.getExtremes(), newMin = axis.toValue(startPos - mousePos, true) + halfPointRange, newMax = axis.toValue(startPos + axis.len - mousePos, true) - halfPointRange, goingLeft = startPos > mousePos; // #3613 if (axis.series.length && (goingLeft || newMin > mathMin(extremes.dataMin, extremes.min)) && (!goingLeft || newMax < mathMax(extremes.dataMax, extremes.max))) { axis.setExtremes(newMin, newMax, false, false, { trigger: 'pan' }); doRedraw = true; } chart[mouseDown] = mousePos; // set new reference for next run }); if (doRedraw) { chart.redraw(false); } css(chart.container, { cursor: 'move' }); } }); /* * Extend the Point object with interaction */ extend(Point.prototype, { /** * Toggle the selection status of a point * @param {Boolean} selected Whether to select or unselect the point. * @param {Boolean} accumulate Whether to add to the previous selection. By default, * this happens if the control key (Cmd on Mac) was pressed during clicking. */ select: function (selected, accumulate) { var point = this, series = point.series, chart = series.chart; selected = pick(selected, !point.selected); // fire the event with the default handler point.firePointEvent(selected ? 'select' : 'unselect', { accumulate: accumulate }, function () { point.selected = point.options.selected = selected; series.options.data[inArray(point, series.data)] = point.options; point.setState(selected && SELECT_STATE); // unselect all other points unless Ctrl or Cmd + click if (!accumulate) { each(chart.getSelectedPoints(), function (loopPoint) { if (loopPoint.selected && loopPoint !== point) { loopPoint.selected = loopPoint.options.selected = false; series.options.data[inArray(loopPoint, series.data)] = loopPoint.options; loopPoint.setState(NORMAL_STATE); loopPoint.firePointEvent('unselect'); } }); } }); }, /** * Runs on mouse over the point * * @param {Object} e The event arguments * @param {Boolean} byProximity Falsy for kd points that are closest to the mouse, or to * actually hovered points. True for other points in shared tooltip. */ onMouseOver: function (e, byProximity) { var point = this, series = point.series, chart = series.chart, tooltip = chart.tooltip, hoverPoint = chart.hoverPoint; if (chart.hoverSeries !== series) { series.onMouseOver(); } // set normal state to previous series if (hoverPoint && hoverPoint !== point) { hoverPoint.onMouseOut(); } if (point.series) { // It may have been destroyed, #4130 // trigger the event point.firePointEvent('mouseOver'); // update the tooltip if (tooltip && (!tooltip.shared || series.noSharedTooltip)) { tooltip.refresh(point, e); } // hover this point.setState(HOVER_STATE); if (!byProximity) { chart.hoverPoint = point; } } }, /** * Runs on mouse out from the point */ onMouseOut: function () { var chart = this.series.chart, hoverPoints = chart.hoverPoints; this.firePointEvent('mouseOut'); if (!hoverPoints || inArray(this, hoverPoints) === -1) { // #887, #2240 this.setState(); chart.hoverPoint = null; } }, /** * Import events from the series' and point's options. Only do it on * demand, to save processing time on hovering. */ importEvents: function () { if (!this.hasImportedEvents) { var point = this, options = merge(point.series.options.point, point.options), events = options.events, eventType; point.events = events; for (eventType in events) { addEvent(point, eventType, events[eventType]); } this.hasImportedEvents = true; } }, /** * Set the point's state * @param {String} state */ setState: function (state, move) { var point = this, plotX = mathFloor(point.plotX), // #4586 plotY = point.plotY, series = point.series, stateOptions = series.options.states, markerOptions = defaultPlotOptions[series.type].marker && series.options.marker, normalDisabled = markerOptions && !markerOptions.enabled, markerStateOptions = markerOptions && markerOptions.states[state], stateDisabled = markerStateOptions && markerStateOptions.enabled === false, stateMarkerGraphic = series.stateMarkerGraphic, pointMarker = point.marker || {}, chart = series.chart, radius, halo = series.halo, haloOptions, newSymbol, pointAttr; state = state || NORMAL_STATE; // empty string pointAttr = point.pointAttr[state] || series.pointAttr[state]; if ( // already has this state (state === point.state && !move) || // selected points don't respond to hover (point.selected && state !== SELECT_STATE) || // series' state options is disabled (stateOptions[state] && stateOptions[state].enabled === false) || // general point marker's state options is disabled (state && (stateDisabled || (normalDisabled && markerStateOptions.enabled === false))) || // individual point marker's state options is disabled (state && pointMarker.states && pointMarker.states[state] && pointMarker.states[state].enabled === false) // #1610 ) { return; } // apply hover styles to the existing point if (point.graphic) { radius = markerOptions && point.graphic.symbolName && pointAttr.r; point.graphic.attr(merge( pointAttr, radius ? { // new symbol attributes (#507, #612) x: plotX - radius, y: plotY - radius, width: 2 * radius, height: 2 * radius } : {} )); // Zooming in from a range with no markers to a range with markers if (stateMarkerGraphic) { stateMarkerGraphic.hide(); } } else { // if a graphic is not applied to each point in the normal state, create a shared // graphic for the hover state if (state && markerStateOptions) { radius = markerStateOptions.radius; newSymbol = pointMarker.symbol || series.symbol; // If the point has another symbol than the previous one, throw away the // state marker graphic and force a new one (#1459) if (stateMarkerGraphic && stateMarkerGraphic.currentSymbol !== newSymbol) { stateMarkerGraphic = stateMarkerGraphic.destroy(); } // Add a new state marker graphic if (!stateMarkerGraphic) { if (newSymbol) { series.stateMarkerGraphic = stateMarkerGraphic = chart.renderer.symbol( newSymbol, plotX - radius, plotY - radius, 2 * radius, 2 * radius ) .attr(pointAttr) .add(series.markerGroup); stateMarkerGraphic.currentSymbol = newSymbol; } // Move the existing graphic } else { stateMarkerGraphic[move ? 'animate' : 'attr']({ // #1054 x: plotX - radius, y: plotY - radius }); } } if (stateMarkerGraphic) { stateMarkerGraphic[state && chart.isInsidePlot(plotX, plotY, chart.inverted) ? 'show' : 'hide'](); // #2450 stateMarkerGraphic.element.point = point; // #4310 } } // Show me your halo haloOptions = stateOptions[state] && stateOptions[state].halo; if (haloOptions && haloOptions.size) { if (!halo) { series.halo = halo = chart.renderer.path() .add(chart.seriesGroup); } halo.attr(extend({ 'fill': point.color || series.color, 'fill-opacity': haloOptions.opacity, 'zIndex': -1 // #4929, IE8 added halo above everything }, haloOptions.attributes))[move ? 'animate' : 'attr']({ d: point.haloPath(haloOptions.size) }); } else if (halo) { halo.attr({ d: [] }); } point.state = state; }, /** * Get the circular path definition for the halo * @param {Number} size The radius of the circular halo * @returns {Array} The path definition */ haloPath: function (size) { var series = this.series, chart = series.chart, plotBox = series.getPlotBox(), inverted = chart.inverted, plotX = Math.floor(this.plotX); return chart.renderer.symbols.circle( plotBox.translateX + (inverted ? series.yAxis.len - this.plotY : plotX) - size, plotBox.translateY + (inverted ? series.xAxis.len - plotX : this.plotY) - size, size * 2, size * 2 ); } }); /* * Extend the Series object with interaction */ extend(Series.prototype, { /** * Series mouse over handler */ onMouseOver: function () { var series = this, chart = series.chart, hoverSeries = chart.hoverSeries; // set normal state to previous series if (hoverSeries && hoverSeries !== series) { hoverSeries.onMouseOut(); } // trigger the event, but to save processing time, // only if defined if (series.options.events.mouseOver) { fireEvent(series, 'mouseOver'); } // hover this series.setState(HOVER_STATE); chart.hoverSeries = series; }, /** * Series mouse out handler */ onMouseOut: function () { // trigger the event only if listeners exist var series = this, options = series.options, chart = series.chart, tooltip = chart.tooltip, hoverPoint = chart.hoverPoint; chart.hoverSeries = null; // #182, set to null before the mouseOut event fires // trigger mouse out on the point, which must be in this series if (hoverPoint) { hoverPoint.onMouseOut(); } // fire the mouse out event if (series && options.events.mouseOut) { fireEvent(series, 'mouseOut'); } // hide the tooltip if (tooltip && !options.stickyTracking && (!tooltip.shared || series.noSharedTooltip)) { tooltip.hide(); } // set normal state series.setState(); }, /** * Set the state of the graph */ setState: function (state) { var series = this, options = series.options, graph = series.graph, stateOptions = options.states, lineWidth = options.lineWidth, attribs, i = 0; state = state || NORMAL_STATE; if (series.state !== state) { series.state = state; if (stateOptions[state] && stateOptions[state].enabled === false) { return; } if (state) { lineWidth = stateOptions[state].lineWidth || lineWidth + (stateOptions[state].lineWidthPlus || 0); // #4035 } if (graph && !graph.dashstyle) { // hover is turned off for dashed lines in VML attribs = { 'stroke-width': lineWidth }; // use attr because animate will cause any other animation on the graph to stop graph.attr(attribs); while (series['zoneGraph' + i]) { series['zoneGraph' + i].attr(attribs); i = i + 1; } } } }, /** * Set the visibility of the graph * * @param vis {Boolean} True to show the series, false to hide. If UNDEFINED, * the visibility is toggled. */ setVisible: function (vis, redraw) { var series = this, chart = series.chart, legendItem = series.legendItem, showOrHide, ignoreHiddenSeries = chart.options.chart.ignoreHiddenSeries, oldVisibility = series.visible; // if called without an argument, toggle visibility series.visible = vis = series.userOptions.visible = vis === UNDEFINED ? !oldVisibility : vis; showOrHide = vis ? 'show' : 'hide'; // show or hide elements each(['group', 'dataLabelsGroup', 'markerGroup', 'tracker'], function (key) { if (series[key]) { series[key][showOrHide](); } }); // hide tooltip (#1361) if (chart.hoverSeries === series || (chart.hoverPoint && chart.hoverPoint.series) === series) { series.onMouseOut(); } if (legendItem) { chart.legend.colorizeItem(series, vis); } // rescale or adapt to resized chart series.isDirty = true; // in a stack, all other series are affected if (series.options.stacking) { each(chart.series, function (otherSeries) { if (otherSeries.options.stacking && otherSeries.visible) { otherSeries.isDirty = true; } }); } // show or hide linked series each(series.linkedSeries, function (otherSeries) { otherSeries.setVisible(vis, false); }); if (ignoreHiddenSeries) { chart.isDirtyBox = true; } if (redraw !== false) { chart.redraw(); } fireEvent(series, showOrHide); }, /** * Show the graph */ show: function () { this.setVisible(true); }, /** * Hide the graph */ hide: function () { this.setVisible(false); }, /** * Set the selected state of the graph * * @param selected {Boolean} True to select the series, false to unselect. If * UNDEFINED, the selection state is toggled. */ select: function (selected) { var series = this; // if called without an argument, toggle series.selected = selected = (selected === UNDEFINED) ? !series.selected : selected; if (series.checkbox) { series.checkbox.checked = selected; } fireEvent(series, selected ? 'select' : 'unselect'); }, drawTracker: TrackerMixin.drawTrackerGraph }); // global variables extend(Highcharts, { // Constructors Color: Color, Point: Point, Tick: Tick, Renderer: Renderer, SVGElement: SVGElement, SVGRenderer: SVGRenderer, // Various arrayMin: arrayMin, arrayMax: arrayMax, charts: charts, dateFormat: dateFormat, error: error, format: format, pathAnim: pathAnim, getOptions: getOptions, hasBidiBug: hasBidiBug, isTouchDevice: isTouchDevice, setOptions: setOptions, addEvent: addEvent, removeEvent: removeEvent, createElement: createElement, discardElement: discardElement, css: css, each: each, map: map, merge: merge, splat: splat, stableSort: stableSort, extendClass: extendClass, pInt: pInt, svg: hasSVG, canvas: useCanVG, vml: !hasSVG && !useCanVG, product: PRODUCT, version: VERSION }); return Highcharts; }));
/*! * is-extendable <https://github.com/jonschlinkert/is-extendable> * * Copyright (c) 2015, Jon Schlinkert. * Licensed under the MIT License. */ 'use strict'; module.exports = function isExtendable(val) { return typeof val !== 'undefined' && val !== null && (typeof val === 'object' || typeof val === 'function'); };
timing_test(function() { at(0 * 1000, function() { assert_styles(".anim", [ {'transform':'none'}, {'transform':'matrix(0.5, 0, 0, 0.5, 0, 0)'}, {'transform':'matrix(0.7071, 0.7071, -0.7071, 0.7071, 0, 0)'}, {'transform':'matrix(0.7071, 0.7071, -0.7071, 0.7071, 70.7107, 70.7107)'}, {'transform':'matrix(1.4142, 1.4142, -1.4142, 1.4142, 141.4214, 141.4214)'}, ]); }); at(0.4 * 1000, function() { assert_styles(".anim", [ {'transform':'matrix(1, 0, 0, 1, 20, 0)'}, {'transform':'matrix(0.6, 0, 0, 0.6, 20, 0)'}, {'transform':'matrix(0.809, 0.5878, -0.5878, 0.809, 20, 0)'}, {'transform':'matrix(0.7071, 0.7071, -0.7071, 0.7071, 76.5685, 56.5685)'}, {'transform':'matrix(1.3023, 1.0927, -1.0927, 1.3023, 133.1371, 113.1371)'}, ]); }); at(0.8 * 1000, function() { assert_styles(".anim", [ {'transform':'matrix(1, 0, 0, 1, 40, 0)'}, {'transform':'matrix(0.7, 0, 0, 0.7, 40, 0)'}, {'transform':'matrix(0.891, 0.454, -0.454, 0.891, 40, 0)'}, {'transform':'matrix(0.7071, 0.7071, -0.7071, 0.7071, 82.4264, 42.4264)'}, {'transform':'matrix(1.1468, 0.803, -0.803, 1.1468, 124.8528, 84.8528)'}, ]); }); at(1.2000000000000002 * 1000, function() { assert_styles(".anim", [ {'transform':'matrix(1, 0, 0, 1, 60, 0)'}, {'transform':'matrix(0.8, 0, 0, 0.8, 60, 0)'}, {'transform':'matrix(0.9511, 0.309, -0.309, 0.9511, 60, 0)'}, {'transform':'matrix(0.7071, 0.7071, -0.7071, 0.7071, 88.2843, 28.2843)'}, {'transform':'matrix(0.9526, 0.55, -0.55, 0.9526, 116.5685, 56.5685)'}, ]); }); at(1.6 * 1000, function() { assert_styles(".anim", [ {'transform':'matrix(1, 0, 0, 1, 80, 0)'}, {'transform':'matrix(0.9, 0, 0, 0.9, 80, 0)'}, {'transform':'matrix(0.9877, 0.1564, -0.1564, 0.9877, 80, 0)'}, {'transform':'matrix(0.7071, 0.7071, -0.7071, 0.7071, 94.1421, 14.1421)'}, {'transform':'matrix(0.725, 0.3381, -0.3381, 0.725, 108.2843, 28.2843)'}, ]); }); at(2 * 1000, function() { assert_styles(".anim", [ {'transform':'matrix(1, 0, 0, 1, 100, 0)'}, {'transform':'matrix(1, 0, 0, 1, 100, 0)'}, {'transform':'matrix(1, 0, 0, 1, 100, 0)'}, {'transform':'matrix(0.7071067811865476, 0.7071067811865475, -0.7071067811865475, 0.7071067811865476, 100, 0)'}, {'transform':'matrix(0.4698463103929542, 0.17101007166283436, -0.17101007166283436, 0.4698463103929542, 100, 0)'}, ]); }); }, "Auto generated tests");
/*! * Qoopido.js library v3.2.7, 2014-5-19 * https://github.com/dlueth/qoopido.js * (c) 2014 Dirk Lueth * Dual licensed under MIT and GPL */ !function(e){window.qoopido.register("support/element/video/mp4",e,["../../../support","../video"])}(function(e,o,t,n,i,p){"use strict";var d=e.support;return d.addTest("/element/video/mp4",function(o){e["support/element/video"]().then(function(){var e=d.pool?d.pool.obtain("video"):p.createElement("video");e.canPlayType('video/mp4; codecs="avc1.42E01E, mp4a.40.2"')?o.resolve():o.reject(),e.dispose&&e.dispose()},function(){o.reject()}).done()})});
//! moment.js locale configuration //! locale : Spanish [es] //! author : Julio Napurí : https://github.com/julionc import moment from '../moment'; var monthsShortDot = 'ene._feb._mar._abr._may._jun._jul._ago._sep._oct._nov._dic.'.split('_'), monthsShort = 'ene_feb_mar_abr_may_jun_jul_ago_sep_oct_nov_dic'.split('_'); var monthsParse = [/^ene/i, /^feb/i, /^mar/i, /^abr/i, /^may/i, /^jun/i, /^jul/i, /^ago/i, /^sep/i, /^oct/i, /^nov/i, /^dic/i]; var monthsRegex = /^(enero|febrero|marzo|abril|mayo|junio|julio|agosto|septiembre|octubre|noviembre|diciembre|ene\.?|feb\.?|mar\.?|abr\.?|may\.?|jun\.?|jul\.?|ago\.?|sep\.?|oct\.?|nov\.?|dic\.?)/i; export default moment.defineLocale('es', { months : 'enero_febrero_marzo_abril_mayo_junio_julio_agosto_septiembre_octubre_noviembre_diciembre'.split('_'), monthsShort : function (m, format) { if (!m) { return monthsShortDot; } else if (/-MMM-/.test(format)) { return monthsShort[m.month()]; } else { return monthsShortDot[m.month()]; } }, monthsRegex : monthsRegex, monthsShortRegex : monthsRegex, monthsStrictRegex : /^(enero|febrero|marzo|abril|mayo|junio|julio|agosto|septiembre|octubre|noviembre|diciembre)/i, monthsShortStrictRegex : /^(ene\.?|feb\.?|mar\.?|abr\.?|may\.?|jun\.?|jul\.?|ago\.?|sep\.?|oct\.?|nov\.?|dic\.?)/i, monthsParse : monthsParse, longMonthsParse : monthsParse, shortMonthsParse : monthsParse, weekdays : 'domingo_lunes_martes_miércoles_jueves_viernes_sábado'.split('_'), weekdaysShort : 'dom._lun._mar._mié._jue._vie._sáb.'.split('_'), weekdaysMin : 'do_lu_ma_mi_ju_vi_sá'.split('_'), weekdaysParseExact : true, longDateFormat : { LT : 'H:mm', LTS : 'H:mm:ss', L : 'DD/MM/YYYY', LL : 'D [de] MMMM [de] YYYY', LLL : 'D [de] MMMM [de] YYYY H:mm', LLLL : 'dddd, D [de] MMMM [de] YYYY H:mm' }, calendar : { sameDay : function () { return '[hoy a la' + ((this.hours() !== 1) ? 's' : '') + '] LT'; }, nextDay : function () { return '[mañana a la' + ((this.hours() !== 1) ? 's' : '') + '] LT'; }, nextWeek : function () { return 'dddd [a la' + ((this.hours() !== 1) ? 's' : '') + '] LT'; }, lastDay : function () { return '[ayer a la' + ((this.hours() !== 1) ? 's' : '') + '] LT'; }, lastWeek : function () { return '[el] dddd [pasado a la' + ((this.hours() !== 1) ? 's' : '') + '] LT'; }, sameElse : 'L' }, relativeTime : { future : 'en %s', past : 'hace %s', s : 'unos segundos', ss : '%d segundos', m : 'un minuto', mm : '%d minutos', h : 'una hora', hh : '%d horas', d : 'un día', dd : '%d días', M : 'un mes', MM : '%d meses', y : 'un año', yy : '%d años' }, dayOfMonthOrdinalParse : /\d{1,2}º/, ordinal : '%dº', week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } });
add(...numbers);
tinyMCE.addI18n('de.umbraco',{ style_select:"Format", font_size:"Schriftgr\u00F6\u00DFe", fontdefault:"Schriftart", block:"Vorlage", paragraph:"Absatz", div:"Zusammenh\u00E4ngender Bereich", address:"Addresse", pre:"Rohdaten", h1:"\u00DCberschrift 1", h2:"\u00DCberschrift 2", h3:"\u00DCberschrift 3", h4:"\u00DCberschrift 4", h5:"\u00DCberschrift 5", h6:"\u00DCberschrift 6", blockquote:"Zitatblock", code:"Code", samp:"Beispiel", dt:"Definitionsbegriff", dd:"Definitionsbeschreibung", bold_desc:"Fett (Strg+B)", italic_desc:"Kursiv (Strg+I)", underline_desc:"Unterstrichen (Strg+U)", striketrough_desc:"Durchgestrichen", justifyleft_desc:"Links ausgerichtet", justifycenter_desc:"Mittig ausgerichtet", justifyright_desc:"Rechts ausgerichtet", justifyfull_desc:"Blocksatz", bullist_desc:"Unsortierte Liste", numlist_desc:"Sortierte Liste", outdent_desc:"Ausr\u00FCcken", indent_desc:"Einr\u00FCcken", undo_desc:"R\u00FCckg\u00E4ngig (Strg+Z)", redo_desc:"Wiederholen (Strg+Y)", link_desc:"Link einf\u00FCgen/ver\u00E4ndern", unlink_desc:"Link entfernen", image_desc:"Bild einf\u00FCgen/ver\u00E4ndern", cleanup_desc:"Quellcode aufr\u00E4umen", code_desc:"HTML-Quellcode bearbeiten", sub_desc:"Tiefgestellt", sup_desc:"Hochgestellt", hr_desc:"Trennlinie einf\u00FCgen", removeformat_desc:"Formatierungen zur\u00FCcksetzen", custom1_desc:"Benutzerdefinierte Beschreibung", forecolor_desc:"Textfarbe", backcolor_desc:"Hintergrundfarbe", charmap_desc:"Sonderzeichen einf\u00FCgen", visualaid_desc:"Hilfslinien und unsichtbare Elemente ein-/ausblenden", anchor_desc:"Anker einf\u00FCgen/ver\u00E4ndern", cut_desc:"Ausschneiden", copy_desc:"Kopieren", paste_desc:"Einf\u00FCgen", image_props_desc:"Bildeigenschaften", newdocument_desc:"Neues Dokument", help_desc:"Hilfe", blockquote_desc:"Zitatblock", clipboard_msg:"Kopieren, Ausschneiden und Einf\u00FCgen sind im Mozilla Firefox nicht m\u00F6glich.\r\nWollen Sie mehr \u00FCber dieses Problem erfahren?", path:"Pfad", newdocument:"Wollen Sie wirklich den ganzen Inhalt l\u00F6schen?", toolbar_focus:"Zur Werkzeugleiste springen: Alt+Q; Zum Editor springen: Alt-Z; Zum Elementpfad springen: Alt-X", more_colors:"Weitere Farben", anchor_delta_width:"13" });
(function(global) { var define = global.define; var require = global.require; var Ember = global.Ember; if (typeof Ember === 'undefined' && typeof require !== 'undefined') { Ember = require('ember'); } Ember.libraries.register('Ember Simple Auth Cookie Store', '0.8.0-beta.3'); define("simple-auth-cookie-store/configuration", ["simple-auth/utils/load-config","exports"], function(__dependency1__, __exports__) { "use strict"; var loadConfig = __dependency1__["default"]; var defaults = { cookieName: 'ember_simple_auth:session', cookieDomain: null, cookieExpirationTime: null }; /** Ember Simple Auth Cookie Store's configuration object. To change any of these values, set them on the application's environment object: ```js ENV['simple-auth-cookie-store'] = { cookieName: 'my_app_auth_session' } ``` @class CookieStore @namespace SimpleAuth.Configuration @module simple-auth/configuration */ __exports__["default"] = { /** The domain to use for the cookie, e.g., "example.com", ".example.com" (includes all subdomains) or "subdomain.example.com". If not configured the cookie domain defaults to the domain the session was authneticated on. This value can be configured via [`SimpleAuth.Configuration.CookieStore#cookieDomain`](#SimpleAuth-Configuration-CookieStore-cookieDomain). @property cookieDomain @type String @default null */ cookieDomain: defaults.cookieDomain, /** The name of the cookie the store stores its data in. @property cookieName @readOnly @static @type String @default 'ember_simple_auth:' */ cookieName: defaults.cookieName, /** The expiration time in seconds to use for the cookie. A value of `null` will make the cookie a session cookie that expires when the browser is closed. @property cookieExpirationTime @readOnly @static @type Integer @default null */ cookieExpirationTime: defaults.cookieExpirationTime, /** @method load @private */ load: loadConfig(defaults) }; }); define("simple-auth-cookie-store/ember", ["./initializer"], function(__dependency1__) { "use strict"; var initializer = __dependency1__["default"]; Ember.onLoad('Ember.Application', function(Application) { Application.initializer(initializer); }); }); define("simple-auth-cookie-store/initializer", ["./configuration","simple-auth/utils/get-global-config","simple-auth-cookie-store/stores/cookie","exports"], function(__dependency1__, __dependency2__, __dependency3__, __exports__) { "use strict"; var Configuration = __dependency1__["default"]; var getGlobalConfig = __dependency2__["default"]; var Store = __dependency3__["default"]; __exports__["default"] = { name: 'simple-auth-cookie-store', before: 'simple-auth', initialize: function(container, application) { var config = getGlobalConfig('simple-auth-cookie-store'); Configuration.load(container, config); application.register('simple-auth-session-store:cookie', Store); } }; }); define("simple-auth-cookie-store/stores/cookie", ["simple-auth/stores/base","simple-auth/utils/objects-are-equal","./../configuration","exports"], function(__dependency1__, __dependency2__, __dependency3__, __exports__) { "use strict"; var Base = __dependency1__["default"]; var objectsAreEqual = __dependency2__["default"]; var Configuration = __dependency3__["default"]; /** Store that saves its data in a cookie. __In order to keep multiple tabs/windows of an application in sync, this store has to periodically (every 500ms) check the cookie__ for changes as there are no events that notify of changes in cookies. The recommended alternative is `Stores.LocalStorage` that also persistently stores data but instead of cookies relies on the `localStorage` API and does not need to poll for external changes. By default the cookie store will use a session cookie that expires and is deleted when the browser is closed. The cookie expiration period can be configured via setting [`Stores.Cooke#cookieExpirationTime`](#SimpleAuth-Stores-Cookie-cookieExpirationTime) though. This can also be used to implement "remember me" functionality that will either store the session persistently or in a session cookie depending whether the user opted in or not: ```js // app/controllers/login.js export default Ember.Controller.extend({ rememberMe: false, rememberMeChanged: function() { this.get('session.store').cookieExpirationTime = this.get('rememberMe') ? (14 * 24 * 60 * 60) : null; }.observes('rememberMe') }); ``` _The factory for this store is registered as `'simple-auth-session-store:cookie'` in Ember's container._ @class Cookie @namespace SimpleAuth.Stores @module simple-auth-cookie-store/stores/cookie @extends Stores.Base */ __exports__["default"] = Base.extend({ /** The domain to use for the cookie, e.g., "example.com", ".example.com" (includes all subdomains) or "subdomain.example.com". If not configured the cookie domain defaults to the domain the session was authneticated on. This value can be configured via [`SimpleAuth.Configuration.CookieStore#cookieDomain`](#SimpleAuth-Configuration-CookieStore-cookieDomain). @property cookieDomain @type String @default null */ cookieDomain: null, /** The name of the cookie the store stores its data in. This value can be configured via [`SimpleAuth.Configuration.CookieStore#cookieName`](#SimpleAuth-Configuration-CookieStore-cookieName). @property cookieName @readOnly @type String */ cookieName: 'ember_simple_auth:session', /** The expiration time in seconds to use for the cookie. A value of `null` will make the cookie a session cookie that expires when the browser is closed. This value can be configured via [`SimpleAuth.Configuration.CookieStore#cookieExpirationTime`](#SimpleAuth-Configuration-CookieStore-cookieExpirationTime). @property cookieExpirationTime @readOnly @type Integer */ cookieExpirationTime: null, /** @property _secureCookies @private */ _secureCookies: window.location.protocol === 'https:', /** @property _syncDataTimeout @private */ _syncDataTimeout: null, /** @property renewExpirationTimeout @private */ renewExpirationTimeout: null, /** @property isPageVisible @private */ isPageVisible: null, /** @method init @private */ init: function() { this.cookieName = Configuration.cookieName; this.cookieExpirationTime = Configuration.cookieExpirationTime; this.cookieDomain = Configuration.cookieDomain; this.isPageVisible = this.initPageVisibility(); this.syncData(); this.renewExpiration(); }, /** Persists the `data` in session cookies. @method persist @param {Object} data The data to persist */ persist: function(data) { data = JSON.stringify(data || {}); var expiration = this.calculateExpirationTime(); this.write(data, expiration); this._lastData = this.restore(); }, /** Restores all data currently saved in the cookie as a plain object. @method restore @return {Object} All data currently persisted in the cookie */ restore: function() { var data = this.read(this.cookieName); if (Ember.isEmpty(data)) { return {}; } else { return JSON.parse(data); } }, /** Clears the store by deleting all session cookies prefixed with the `cookieName` (see [`SimpleAuth.Stores.Cookie#cookieName`](#SimpleAuth-Stores-Cookie-cookieName)). @method clear */ clear: function() { this.write(null, 0); this._lastData = {}; }, /** @method read @private */ read: function(name) { var value = document.cookie.match(new RegExp(name + '=([^;]+)')) || []; return decodeURIComponent(value[1] || ''); }, /** @method calculateExpirationTime @private */ calculateExpirationTime: function() { var cachedExpirationTime = this.read(this.cookieName + ':expiration_time'); cachedExpirationTime = !!cachedExpirationTime ? new Date().getTime() + cachedExpirationTime * 1000 : null; return !!this.cookieExpirationTime ? new Date().getTime() + this.cookieExpirationTime * 1000 : cachedExpirationTime; }, /** @method write @private */ write: function(value, expiration) { var path = '; path=/'; var domain = Ember.isEmpty(this.cookieDomain) ? '' : '; domain=' + this.cookieDomain; var expires = Ember.isEmpty(expiration) ? '' : '; expires=' + new Date(expiration).toUTCString(); var secure = !!this._secureCookies ? ';secure' : ''; document.cookie = this.cookieName + '=' + encodeURIComponent(value) + domain + path + expires + secure; if(expiration !== null) { var cachedExpirationTime = this.read(this.cookieName + ':expiration_time'); document.cookie = this.cookieName + ':expiration_time=' + encodeURIComponent(this.cookieExpirationTime || cachedExpirationTime) + domain + path + expires + secure; } }, /** @method syncData @private */ syncData: function() { var data = this.restore(); if (!objectsAreEqual(data, this._lastData)) { this._lastData = data; this.trigger('sessionDataUpdated', data); } if (!Ember.testing) { Ember.run.cancel(this._syncDataTimeout); this._syncDataTimeout = Ember.run.later(this, this.syncData, 500); } }, /** @method initPageVisibility @private */ initPageVisibility: function(){ var keys = { hidden: 'visibilitychange', webkitHidden: 'webkitvisibilitychange', mozHidden: 'mozvisibilitychange', msHidden: 'msvisibilitychange' }; for (var stateKey in keys) { if (stateKey in document) { var eventKey = keys[stateKey]; break; } } return function() { return !document[stateKey]; }; }, /** @method renew @private */ renew: function() { var data = this.restore(); if (!Ember.isEmpty(data) && data !== {}) { data = Ember.typeOf(data) === 'string' ? data : JSON.stringify(data || {}); var expiration = this.calculateExpirationTime(); this.write(data, expiration); } }, /** @method renewExpiration @private */ renewExpiration: function() { if (this.isPageVisible()) { this.renew(); } if (!Ember.testing) { Ember.run.cancel(this.renewExpirationTimeout); this.renewExpirationTimeout = Ember.run.later(this, this.renewExpiration, 60000); } } }); }); })(this);
/* YUI 3.16.0 (build 76f0e08) Copyright 2014 Yahoo! Inc. All rights reserved. Licensed under the BSD License. http://yuilibrary.com/license/ */ YUI.add('console-filters', function (Y, NAME) { /** * <p>Provides Plugin.ConsoleFilters plugin class.</p> * * <p>This plugin adds the ability to control which Console entries display by filtering on category and source. Two groups of checkboxes are added to the Console footer, one for categories and the other for sources. Only those messages that match a checked category or source are displayed.</p> * * @module console-filters * @namespace Plugin * @class ConsoleFilters */ // Some common strings and functions var getCN = Y.ClassNameManager.getClassName, CONSOLE = 'console', FILTERS = 'filters', FILTER = 'filter', CATEGORY = 'category', SOURCE = 'source', CATEGORY_DOT = 'category.', SOURCE_DOT = 'source.', HOST = 'host', CHECKED = 'checked', DEF_VISIBILITY = 'defaultVisibility', DOT = '.', EMPTY = '', C_BODY = DOT + Y.Console.CHROME_CLASSES.console_bd_class, C_FOOT = DOT + Y.Console.CHROME_CLASSES.console_ft_class, SEL_CHECK = 'input[type=checkbox].', isString = Y.Lang.isString; function ConsoleFilters() { ConsoleFilters.superclass.constructor.apply(this,arguments); } Y.namespace('Plugin').ConsoleFilters = Y.extend(ConsoleFilters, Y.Plugin.Base, // Y.Plugin.ConsoleFilters prototype { /** * Collection of all log messages passed through since the plugin's * instantiation. This holds all messages regardless of filter status. * Used as a single source of truth for repopulating the Console body when * filters are changed. * * @property _entries * @type Array * @protected */ _entries : null, /** * Maximum number of entries to store in the message cache. * * @property _cacheLimit * @type {Number} * @default Infinity * @protected */ _cacheLimit : Number.POSITIVE_INFINITY, /** * The container node created to house the category filters. * * @property _categories * @type Node * @protected */ _categories : null, /** * The container node created to house the source filters. * * @property _sources * @type Node * @protected */ _sources : null, /** * Initialize entries collection and attach listeners to host events and * methods. * * @method initializer * @protected */ initializer : function () { this._entries = []; this.get(HOST).on("entry", this._onEntry, this); this.doAfter("renderUI", this.renderUI); this.doAfter("syncUI", this.syncUI); this.doAfter("bindUI", this.bindUI); this.doAfter("clearConsole", this._afterClearConsole); if (this.get(HOST).get('rendered')) { this.renderUI(); this.syncUI(); this.bindUI(); } this.after("cacheLimitChange", this._afterCacheLimitChange); }, /** * Removes the plugin UI and unwires events. * * @method destructor * @protected */ destructor : function () { //TODO: grab last {consoleLimit} entries and update the console with //them (no filtering) this._entries = []; if (this._categories) { this._categories.remove(); } if (this._sources) { this._sources.remove(); } }, /** * Adds the category and source filter sections to the Console footer. * * @method renderUI * @protected */ renderUI : function () { var foot = this.get(HOST).get('contentBox').one(C_FOOT), html; if (foot) { html = Y.Lang.sub( ConsoleFilters.CATEGORIES_TEMPLATE, ConsoleFilters.CHROME_CLASSES); this._categories = foot.appendChild(Y.Node.create(html)); html = Y.Lang.sub( ConsoleFilters.SOURCES_TEMPLATE, ConsoleFilters.CHROME_CLASSES); this._sources = foot.appendChild(Y.Node.create(html)); } }, /** * Binds to checkbox click events and internal attribute change events to * maintain the UI state. * * @method bindUI * @protected */ bindUI : function () { this._categories.on('click', Y.bind(this._onCategoryCheckboxClick, this)); this._sources.on('click', Y.bind(this._onSourceCheckboxClick, this)); this.after('categoryChange',this._afterCategoryChange); this.after('sourceChange', this._afterSourceChange); }, /** * Updates the UI to be in accordance with the current state of the plugin. * * @method syncUI */ syncUI : function () { Y.each(this.get(CATEGORY), function (v, k) { this._uiSetCheckbox(CATEGORY, k, v); }, this); Y.each(this.get(SOURCE), function (v, k) { this._uiSetCheckbox(SOURCE, k, v); }, this); this.refreshConsole(); }, /** * Ensures a filter is set up for any new categories or sources and * collects the messages in _entries. If the message is stamped with a * category or source that is currently being filtered out, the message * will not pass to the Console's print buffer. * * @method _onEntry * @param e {Event} the custom event object * @protected */ _onEntry : function (e) { this._entries.push(e.message); var cat = CATEGORY_DOT + e.message.category, src = SOURCE_DOT + e.message.source, cat_filter = this.get(cat), src_filter = this.get(src), overLimit = this._entries.length - this._cacheLimit, visible; if (overLimit > 0) { this._entries.splice(0, overLimit); } if (cat_filter === undefined) { visible = this.get(DEF_VISIBILITY); this.set(cat, visible); cat_filter = visible; } if (src_filter === undefined) { visible = this.get(DEF_VISIBILITY); this.set(src, visible); src_filter = visible; } if (!cat_filter || !src_filter) { e.preventDefault(); } }, /** * Flushes the cached entries after a call to the Console's clearConsole(). * * @method _afterClearConsole * @protected */ _afterClearConsole : function () { this._entries = []; }, /** * Triggers the Console to update if a known category filter * changes value (e.g. visible => hidden). Updates the appropriate * checkbox's checked state if necessary. * * @method _afterCategoryChange * @param e {Event} the attribute change event object * @protected */ _afterCategoryChange : function (e) { var cat = e.subAttrName.replace(/category\./, EMPTY), before = e.prevVal, after = e.newVal; // Don't update the console for new categories if (!cat || before[cat] !== undefined) { this.refreshConsole(); this._filterBuffer(); } if (cat && !e.fromUI) { this._uiSetCheckbox(CATEGORY, cat, after[cat]); } }, /** * Triggers the Console to update if a known source filter * changes value (e.g. visible => hidden). Updates the appropriate * checkbox's checked state if necessary. * * @method _afterSourceChange * @param e {Event} the attribute change event object * @protected */ _afterSourceChange : function (e) { var src = e.subAttrName.replace(/source\./, EMPTY), before = e.prevVal, after = e.newVal; // Don't update the console for new sources if (!src || before[src] !== undefined) { this.refreshConsole(); this._filterBuffer(); } if (src && !e.fromUI) { this._uiSetCheckbox(SOURCE, src, after[src]); } }, /** * Flushes the Console's print buffer of any entries that have a category * or source that is currently being excluded. * * @method _filterBuffer * @protected */ _filterBuffer : function () { var cats = this.get(CATEGORY), srcs = this.get(SOURCE), buffer = this.get(HOST).buffer, start = null, i; for (i = buffer.length - 1; i >= 0; --i) { if (!cats[buffer[i].category] || !srcs[buffer[i].source]) { start = start || i; } else if (start) { buffer.splice(i,(start - i)); start = null; } } if (start) { buffer.splice(0,start + 1); } }, /** * Trims the cache of entries to the appropriate new length. * * @method _afterCacheLimitChange * @param e {Event} the attribute change event object * @protected */ _afterCacheLimitChange : function (e) { if (isFinite(e.newVal)) { var delta = this._entries.length - e.newVal; if (delta > 0) { this._entries.splice(0,delta); } } }, /** * Repopulates the Console with entries appropriate to the current filter * settings. * * @method refreshConsole */ refreshConsole : function () { var entries = this._entries, host = this.get(HOST), body = host.get('contentBox').one(C_BODY), remaining = host.get('consoleLimit'), cats = this.get(CATEGORY), srcs = this.get(SOURCE), buffer = [], i,e; if (body) { host._cancelPrintLoop(); // Evaluate all entries from latest to oldest for (i = entries.length - 1; i >= 0 && remaining >= 0; --i) { e = entries[i]; if (cats[e.category] && srcs[e.source]) { buffer.unshift(e); --remaining; } } body.setHTML(EMPTY); host.buffer = buffer; host.printBuffer(); } }, /** * Updates the checked property of a filter checkbox of the specified type. * If no checkbox is found for the input params, one is created. * * @method _uiSetCheckbox * @param type {String} 'category' or 'source' * @param item {String} the name of the filter (e.g. 'info', 'event') * @param checked {Boolean} value to set the checkbox's checked property * @protected */ _uiSetCheckbox : function (type, item, checked) { if (type && item) { var container = type === CATEGORY ? this._categories : this._sources, sel = SEL_CHECK + getCN(CONSOLE,FILTER,item), checkbox = container.one(sel), host; if (!checkbox) { host = this.get(HOST); this._createCheckbox(container, item); checkbox = container.one(sel); host._uiSetHeight(host.get('height')); } checkbox.set(CHECKED, checked); } }, /** * Passes checkbox clicks on to the category attribute. * * @method _onCategoryCheckboxClick * @param e {Event} the DOM event * @protected */ _onCategoryCheckboxClick : function (e) { var t = e.target, cat; if (t.hasClass(ConsoleFilters.CHROME_CLASSES.filter)) { cat = t.get('value'); if (cat && cat in this.get(CATEGORY)) { this.set(CATEGORY_DOT + cat, t.get(CHECKED), { fromUI: true }); } } }, /** * Passes checkbox clicks on to the source attribute. * * @method _onSourceCheckboxClick * @param e {Event} the DOM event * @protected */ _onSourceCheckboxClick : function (e) { var t = e.target, src; if (t.hasClass(ConsoleFilters.CHROME_CLASSES.filter)) { src = t.get('value'); if (src && src in this.get(SOURCE)) { this.set(SOURCE_DOT + src, t.get(CHECKED), { fromUI: true }); } } }, /** * Hides any number of categories from the UI. Convenience method for * myConsole.filter.set('category.foo', false); set('category.bar', false); * and so on. * * @method hideCategory * @param cat* {String} 1..n categories to filter out of the UI */ hideCategory : function (cat, multiple) { if (isString(multiple)) { Y.Array.each(arguments, this.hideCategory, this); } else { this.set(CATEGORY_DOT + cat, false); } }, /** * Shows any number of categories in the UI. Convenience method for * myConsole.filter.set('category.foo', true); set('category.bar', true); * and so on. * * @method showCategory * @param cat* {String} 1..n categories to allow to display in the UI */ showCategory : function (cat, multiple) { if (isString(multiple)) { Y.Array.each(arguments, this.showCategory, this); } else { this.set(CATEGORY_DOT + cat, true); } }, /** * Hides any number of sources from the UI. Convenience method for * myConsole.filter.set('source.foo', false); set('source.bar', false); * and so on. * * @method hideSource * @param src* {String} 1..n sources to filter out of the UI */ hideSource : function (src, multiple) { if (isString(multiple)) { Y.Array.each(arguments, this.hideSource, this); } else { this.set(SOURCE_DOT + src, false); } }, /** * Shows any number of sources in the UI. Convenience method for * myConsole.filter.set('source.foo', true); set('source.bar', true); * and so on. * * @method showSource * @param src* {String} 1..n sources to allow to display in the UI */ showSource : function (src, multiple) { if (isString(multiple)) { Y.Array.each(arguments, this.showSource, this); } else { this.set(SOURCE_DOT + src, true); } }, /** * Creates a checkbox and label from the ConsoleFilters.FILTER_TEMPLATE for * the provided type and name. The checkbox and label are appended to the * container node passes as the first arg. * * @method _createCheckbox * @param container {Node} the parentNode of the new checkbox and label * @param name {String} the identifier of the filter * @protected */ _createCheckbox : function (container, name) { var info = Y.merge(ConsoleFilters.CHROME_CLASSES, { filter_name : name, filter_class : getCN(CONSOLE, FILTER, name) }), node = Y.Node.create( Y.Lang.sub(ConsoleFilters.FILTER_TEMPLATE, info)); container.appendChild(node); }, /** * Validates category updates are objects and the subattribute is not too * deep. * * @method _validateCategory * @param cat {String} the new category:visibility map * @param v {String} the subattribute path updated * @return Boolean * @protected */ _validateCategory : function (cat, v) { return Y.Lang.isObject(v,true) && cat.split(/\./).length < 3; }, /** * Validates source updates are objects and the subattribute is not too * deep. * * @method _validateSource * @param cat {String} the new source:visibility map * @param v {String} the subattribute path updated * @return Boolean * @protected */ _validateSource : function (src, v) { return Y.Lang.isObject(v,true) && src.split(/\./).length < 3; }, /** * Setter method for cacheLimit attribute. Basically a validator to ensure * numeric input. * * @method _setCacheLimit * @param v {Number} Maximum number of entries * @return {Number} * @protected */ _setCacheLimit: function (v) { if (Y.Lang.isNumber(v)) { this._cacheLimit = v; return v; } else { return Y.Attribute.INVALID_VALUE; } } }, // Y.Plugin.ConsoleFilters static properties { /** * Plugin name. * * @property NAME * @type String * @static * @default 'consoleFilters' */ NAME : 'consoleFilters', /** * The namespace hung off the host object that this plugin will inhabit. * * @property NS * @type String * @static * @default 'filter' */ NS : FILTER, /** * Markup template used to create the container for the category filters. * * @property CATEGORIES_TEMPLATE * @type String * @static */ CATEGORIES_TEMPLATE : '<div class="{categories}"></div>', /** * Markup template used to create the container for the source filters. * * @property SOURCES_TEMPLATE * @type String * @static */ SOURCES_TEMPLATE : '<div class="{sources}"></div>', /** * Markup template used to create the category and source filter checkboxes. * * @property FILTER_TEMPLATE * @type String * @static */ FILTER_TEMPLATE : // IE8 and FF3 don't permit breaking _between_ nowrap elements. IE8 // doesn't understand (non spec) wbr tag, nor does it create text nodes // for spaces in innerHTML strings. The thin-space entity suffices to // create a breakable point. '<label class="{filter_label}">'+ '<input type="checkbox" value="{filter_name}" '+ 'class="{filter} {filter_class}"> {filter_name}'+ '</label>&#8201;', /** * Classnames used by the templates when creating nodes. * * @property CHROME_CLASSES * @type Object * @static * @protected */ CHROME_CLASSES : { categories : getCN(CONSOLE,FILTERS,'categories'), sources : getCN(CONSOLE,FILTERS,'sources'), category : getCN(CONSOLE,FILTER,CATEGORY), source : getCN(CONSOLE,FILTER,SOURCE), filter : getCN(CONSOLE,FILTER), filter_label : getCN(CONSOLE,FILTER,'label') }, ATTRS : { /** * Default visibility applied to new categories and sources. * * @attribute defaultVisibility * @type {Boolean} * @default true */ defaultVisibility : { value : true, validator : Y.Lang.isBoolean }, /** * <p>Map of entry categories to their visibility status. Update a * particular category's visibility by setting the subattribute to true * (visible) or false (hidden).</p> * * <p>For example, yconsole.filter.set('category.info', false) to hide * log entries with the category/logLevel of 'info'.</p> * * <p>Similarly, yconsole.filter.get('category.warn') will return a * boolean indicating whether that category is currently being included * in the UI.</p> * * <p>Unlike the YUI instance configuration's logInclude and logExclude * properties, filtered entries are only hidden from the UI, but * can be made visible again.</p> * * @attribute category * @type Object */ category : { value : {}, validator : function (v,k) { return this._validateCategory(k,v); } }, /** * <p>Map of entry sources to their visibility status. Update a * particular sources's visibility by setting the subattribute to true * (visible) or false (hidden).</p> * * <p>For example, yconsole.filter.set('sources.slider', false) to hide * log entries originating from Y.Slider.</p> * * @attribute source * @type Object */ source : { value : {}, validator : function (v,k) { return this._validateSource(k,v); } }, /** * Maximum number of entries to store in the message cache. Use this to * limit the memory footprint in environments with heavy log usage. * By default, there is no limit (Number.POSITIVE_INFINITY). * * @attribute cacheLimit * @type {Number} * @default Number.POSITIVE_INFINITY */ cacheLimit : { value : Number.POSITIVE_INFINITY, setter : function (v) { return this._setCacheLimit(v); } } } }); }, '3.16.0', {"requires": ["plugin", "console"], "skinnable": true});
'use strict'; angular.module("ngLocale", [], ["$provide", function($provide) { var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"}; function getDecimals(n) { n = n + ''; var i = n.indexOf('.'); return (i == -1) ? 0 : n.length - i - 1; } function getVF(n, opt_precision) { var v = opt_precision; if (undefined === v) { v = Math.min(getDecimals(n), 3); } var base = Math.pow(10, v); var f = ((n * base) | 0) % base; return {v: v, f: f}; } $provide.value("$locale", { "DATETIME_FORMATS": { "AMPMS": [ "AM", "PM" ], "DAY": [ "\u0432\u043e\u0441\u043a\u0440\u0435\u0441\u0435\u043d\u044c\u0435", "\u043f\u043e\u043d\u0435\u0434\u0435\u043b\u044c\u043d\u0438\u043a", "\u0432\u0442\u043e\u0440\u043d\u0438\u043a", "\u0441\u0440\u0435\u0434\u0430", "\u0447\u0435\u0442\u0432\u0435\u0440\u0433", "\u043f\u044f\u0442\u043d\u0438\u0446\u0430", "\u0441\u0443\u0431\u0431\u043e\u0442\u0430" ], "ERANAMES": [ "\u0434\u043e \u043d. \u044d.", "\u043d. \u044d." ], "ERAS": [ "\u0434\u043e \u043d. \u044d.", "\u043d. \u044d." ], "FIRSTDAYOFWEEK": 0, "MONTH": [ "\u044f\u043d\u0432\u0430\u0440\u044f", "\u0444\u0435\u0432\u0440\u0430\u043b\u044f", "\u043c\u0430\u0440\u0442\u0430", "\u0430\u043f\u0440\u0435\u043b\u044f", "\u043c\u0430\u044f", "\u0438\u044e\u043d\u044f", "\u0438\u044e\u043b\u044f", "\u0430\u0432\u0433\u0443\u0441\u0442\u0430", "\u0441\u0435\u043d\u0442\u044f\u0431\u0440\u044f", "\u043e\u043a\u0442\u044f\u0431\u0440\u044f", "\u043d\u043e\u044f\u0431\u0440\u044f", "\u0434\u0435\u043a\u0430\u0431\u0440\u044f" ], "SHORTDAY": [ "\u0432\u0441", "\u043f\u043d", "\u0432\u0442", "\u0441\u0440", "\u0447\u0442", "\u043f\u0442", "\u0441\u0431" ], "SHORTMONTH": [ "\u044f\u043d\u0432.", "\u0444\u0435\u0432\u0440.", "\u043c\u0430\u0440\u0442\u0430", "\u0430\u043f\u0440.", "\u043c\u0430\u044f", "\u0438\u044e\u043d\u044f", "\u0438\u044e\u043b\u044f", "\u0430\u0432\u0433.", "\u0441\u0435\u043d\u0442.", "\u043e\u043a\u0442.", "\u043d\u043e\u044f\u0431.", "\u0434\u0435\u043a." ], "WEEKENDRANGE": [ 5, 6 ], "fullDate": "EEEE, d MMMM y '\u0433'.", "longDate": "d MMMM y '\u0433'.", "medium": "d MMM y '\u0433'. H:mm:ss", "mediumDate": "d MMM y '\u0433'.", "mediumTime": "H:mm:ss", "short": "dd.MM.yy H:mm", "shortDate": "dd.MM.yy", "shortTime": "H:mm" }, "NUMBER_FORMATS": { "CURRENCY_SYM": "BYR", "DECIMAL_SEP": ",", "GROUP_SEP": "\u00a0", "PATTERNS": [ { "gSize": 3, "lgSize": 3, "maxFrac": 3, "minFrac": 0, "minInt": 1, "negPre": "-", "negSuf": "", "posPre": "", "posSuf": "" }, { "gSize": 3, "lgSize": 3, "maxFrac": 2, "minFrac": 2, "minInt": 1, "negPre": "-", "negSuf": "\u00a0\u00a4", "posPre": "", "posSuf": "\u00a0\u00a4" } ] }, "id": "ru-by", "pluralCat": function(n, opt_precision) { var i = n | 0; var vf = getVF(n, opt_precision); if (vf.v == 0 && i % 10 == 1 && i % 100 != 11) { return PLURAL_CATEGORY.ONE; } if (vf.v == 0 && i % 10 >= 2 && i % 10 <= 4 && (i % 100 < 12 || i % 100 > 14)) { return PLURAL_CATEGORY.FEW; } if (vf.v == 0 && i % 10 == 0 || vf.v == 0 && i % 10 >= 5 && i % 10 <= 9 || vf.v == 0 && i % 100 >= 11 && i % 100 <= 14) { return PLURAL_CATEGORY.MANY; } return PLURAL_CATEGORY.OTHER;} }); }]);
YUI.add("intl-base",function(B){var A=/[, ]/;B.mix(B.namespace("Intl"),{lookupBestLang:function(G,H){var F,I,C,E;function D(K){var J;for(J=0;J<H.length;J+=1){if(K.toLowerCase()===H[J].toLowerCase()){return H[J];}}}if(B.Lang.isString(G)){G=G.split(A);}for(F=0;F<G.length;F+=1){I=G[F];if(!I||I==="*"){continue;}while(I.length>0){C=D(I);if(C){return C;}else{E=I.lastIndexOf("-");if(E>=0){I=I.substring(0,E);if(E>=2&&I.charAt(E-2)==="-"){I=I.substring(0,E-2);}}else{break;}}}}return"";}});},"@VERSION@",{requires:["yui-base"]});
/* * Date Format 1.2.3 * (c) 2007-2009 Steven Levithan <stevenlevithan.com> * MIT license * * Includes enhancements by Scott Trenda <scott.trenda.net> * and Kris Kowal <cixar.com/~kris.kowal/> * * Accepts a date, a mask, or a date and a mask. * Returns a formatted version of the given date. * The date defaults to the current date/time. * The mask defaults to dateFormat.masks.default. */ var dateFormat = function () { var token = /d{1,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|[LloSZW]|"[^"]*"|'[^']*'/g, timezone = /\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g, timezoneClip = /[^-+\dA-Z]/g, pad = function (val, len) { val = String(val); len = len || 2; while (val.length < len) val = "0" + val; return val; }, /** * Get the ISO 8601 week number * Based on comments from * http://techblog.procurios.nl/k/n618/news/view/33796/14863/Calculate-ISO-8601-week-and-year-in-javascript.html */ getWeek = function (date) { // Remove time components of date var targetThursday = new Date(date.getFullYear(), date.getMonth(), date.getDate()); // Change date to Thursday same week targetThursday.setDate(targetThursday.getDate() - ((targetThursday.getDay() + 6) % 7) + 3); // Take January 4th as it is always in week 1 (see ISO 8601) var firstThursday = new Date(targetThursday.getFullYear(), 0, 4); // Change date to Thursday same week firstThursday.setDate(firstThursday.getDate() - ((firstThursday.getDay() + 6) % 7) + 3); // Check if daylight-saving-time-switch occured and correct for it var ds = targetThursday.getTimezoneOffset()/firstThursday.getTimezoneOffset()-1; targetThursday.setHours(targetThursday.getHours()+ds); // Number of weeks between target Thursday and first Thursday var weekDiff = (targetThursday - firstThursday) / (86400000*7); return 1 + weekDiff; }; // Regexes and supporting functions are cached through closure return function (date, mask, utc) { var dF = dateFormat; // You can't provide utc if you skip other args (use the "UTC:" mask prefix) if (arguments.length == 1 && Object.prototype.toString.call(date) == "[object String]" && !/\d/.test(date)) { mask = date; date = undefined; } date = date || new Date; if(!(date instanceof Date)) { date = new Date(date); } if (isNaN(date)) { throw TypeError("Invalid date"); } mask = String(dF.masks[mask] || mask || dF.masks["default"]); // Allow setting the utc argument via the mask if (mask.slice(0, 4) == "UTC:") { mask = mask.slice(4); utc = true; } var _ = utc ? "getUTC" : "get", d = date[_ + "Date"](), D = date[_ + "Day"](), m = date[_ + "Month"](), y = date[_ + "FullYear"](), H = date[_ + "Hours"](), M = date[_ + "Minutes"](), s = date[_ + "Seconds"](), L = date[_ + "Milliseconds"](), o = utc ? 0 : date.getTimezoneOffset(), W = getWeek(date), flags = { d: d, dd: pad(d), ddd: dF.i18n.dayNames[D], dddd: dF.i18n.dayNames[D + 7], m: m + 1, mm: pad(m + 1), mmm: dF.i18n.monthNames[m], mmmm: dF.i18n.monthNames[m + 12], yy: String(y).slice(2), yyyy: y, h: H % 12 || 12, hh: pad(H % 12 || 12), H: H, HH: pad(H), M: M, MM: pad(M), s: s, ss: pad(s), l: pad(L, 3), L: pad(L > 99 ? Math.round(L / 10) : L), t: H < 12 ? "a" : "p", tt: H < 12 ? "am" : "pm", T: H < 12 ? "A" : "P", TT: H < 12 ? "AM" : "PM", Z: utc ? "UTC" : (String(date).match(timezone) || [""]).pop().replace(timezoneClip, ""), o: (o > 0 ? "-" : "+") + pad(Math.floor(Math.abs(o) / 60) * 100 + Math.abs(o) % 60, 4), S: ["th", "st", "nd", "rd"][d % 10 > 3 ? 0 : (d % 100 - d % 10 != 10) * d % 10], W: W }; return mask.replace(token, function ($0) { return $0 in flags ? flags[$0] : $0.slice(1, $0.length - 1); }); }; }(); // Some common format strings dateFormat.masks = { "default": "ddd mmm dd yyyy HH:MM:ss", shortDate: "m/d/yy", mediumDate: "mmm d, yyyy", longDate: "mmmm d, yyyy", fullDate: "dddd, mmmm d, yyyy", shortTime: "h:MM TT", mediumTime: "h:MM:ss TT", longTime: "h:MM:ss TT Z", isoDate: "yyyy-mm-dd", isoTime: "HH:MM:ss", isoDateTime: "yyyy-mm-dd'T'HH:MM:ss", isoUtcDateTime: "UTC:yyyy-mm-dd'T'HH:MM:ss'Z'" }; // Internationalization strings dateFormat.i18n = { dayNames: [ "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" ], monthNames: [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ] }; /* // For convenience... Date.prototype.format = function (mask, utc) { return dateFormat(this, mask, utc); }; */ if (typeof exports !== "undefined") { module.exports = dateFormat; }
/* Translators (2009 onwards): * - City-busz * - Glanthor Reviol */ /** * @requires OpenLayers/Lang.js */ /** * Namespace: OpenLayers.Lang["hu"] * Dictionary for Magyar. Keys for entries are used in calls to * <OpenLayers.Lang.translate>. Entry bodies are normal strings or * strings formatted for use with <OpenLayers.String.format> calls. */ OpenLayers.Lang["hu"] = OpenLayers.Util.applyDefaults({ 'unhandledRequest': "Nem kezelt kérés visszatérése ${statusText}", 'Permalink': "Permalink", 'Overlays': "Rávetítések", 'Base Layer': "Alapréteg", 'noFID': "Nem frissíthető olyan jellemző, amely nem rendelkezik FID-del.", 'browserNotSupported': "A böngészője nem támogatja a vektoros renderelést. A jelenleg támogatott renderelők:\n${renderers}", 'minZoomLevelError': "A minZoomLevel tulajdonságot csak a következővel való használatra szánták: FixedZoomLevels-leszármazott fóliák. Ez azt jelenti, hogy a minZoomLevel wfs fólia jelölőnégyzetei már a múlté. Mi azonban nem távolíthatjuk el annak a veszélye nélkül, hogy az esetlegesen ettől függő OL alapú alkalmazásokat tönkretennénk. Ezért ezt érvénytelenítjük -- a minZoomLevel az alul levő jelölőnégyzet a 3.0-s verzióból el lesz távolítva. Kérjük, helyette használja a min/max felbontás beállítást, amelyről az alábbi helyen talál leírást: http://trac.openlayers.org/wiki/SettingZoomLevels", 'commitSuccess': "WFS tranzakció: SIKERES ${response}", 'commitFailed': "WFS tranzakció: SIKERTELEN ${response}", 'googleWarning': "A Google fólia betöltése sikertelen.\x3cbr\x3e\x3cbr\x3eAhhoz, hogy ez az üzenet eltűnjön, válasszon egy új BaseLayer fóliát a jobb felső sarokban található fóliakapcsoló segítségével.\x3cbr\x3e\x3cbr\x3eNagy valószínűséggel ez azért van, mert a Google Maps könyvtár parancsfájlja nem található, vagy nem tartalmazza az Ön oldalához tartozó megfelelő API-kulcsot.\x3cbr\x3e\x3cbr\x3eFejlesztőknek: A helyes működtetésre vonatkozó segítség az alábbi helyen érhető el, \x3ca href=\'http://trac.openlayers.org/wiki/Google\' target=\'_blank\'\x3ekattintson ide\x3c/a\x3e", 'getLayerWarning': "A(z) ${layerType} fólia nem töltődött be helyesen.\x3cbr\x3e\x3cbr\x3eAhhoz, hogy ez az üzenet eltűnjön, válasszon egy új BaseLayer fóliát a jobb felső sarokban található fóliakapcsoló segítségével.\x3cbr\x3e\x3cbr\x3eNagy valószínűséggel ez azért van, mert a(z) ${layerLib} könyvtár parancsfájlja helytelen.\x3cbr\x3e\x3cbr\x3eFejlesztőknek: A helyes működtetésre vonatkozó segítség az alábbi helyen érhető el, \x3ca href=\'http://trac.openlayers.org/wiki/${layerLib}\' target=\'_blank\'\x3ekattintson ide\x3c/a\x3e", 'Scale = 1 : ${scaleDenom}': "Lépték = 1 : ${scaleDenom}", 'W': "Ny", 'E': "K", 'N': "É", 'S': "D", 'reprojectDeprecated': "Ön a \'reproject\' beállítást használja a(z) ${layerName} fólián. Ez a beállítás érvénytelen: használata az üzleti alaptérképek fölötti adatok megjelenítésének támogatására szolgált, de ezt a funkció ezentúl a Gömbi Mercator használatával érhető el. További információ az alábbi helyen érhető el: http://trac.openlayers.org/wiki/SphericalMercator", 'methodDeprecated': "Ez a módszer érvénytelenítve lett és a 3.0-s verzióból el lesz távolítva. Használja a(z) ${newMethod} módszert helyette." });
/* YUI 3.17.1 (build 0eb5a52) Copyright 2014 Yahoo! Inc. All rights reserved. Licensed under the BSD License. http://yuilibrary.com/license/ */ YUI.add("base-pluginhost",function(e,t){var n=e.Base,r=e.Plugin.Host;e.mix(n,r,!1,null,1),n.plug=r.plug,n.unplug=r.unplug},"3.17.1",{requires:["base-base","pluginhost"]});
"use strict"; import I from "immutable"; import IPropTypes from "react-immutable-proptypes"; import React, { Component, PropTypes } from "react"; import Preset from "./Preset"; import FilterInput from "./FilterInput"; import MultiSelect from "./MultiSelect"; import PaginationInfo from "./PaginationInfo"; import DateSelector from "../common/DateSelector"; import yyyyMMdd from "../../utils/yyyyMMdd"; export default class Filter extends Component { shouldComponentUpdate(nextProps) { return nextProps.selections !== this.props.selections || nextProps.filters !== this.props.filters || nextProps.numberOfRows !== this.props.numberOfRows; } render() { // use cx const baseClassName = "job-text-input "; const textFilterClassName = baseClassName + "filter"; const dateFilterClassName = "date"; const selects = this.props.filters.get("restrictions").map((field, restr) => { return ( this.props.selections.has(restr) ? <MultiSelect key={restr} selected={field} selections={this.props.selections.get(restr)} onSelect={this.props.restrictTo} /> : <span key={restr}/> ); }).toArray(); const presets = this.props.presetConfig.map(preset => { const key = preset.description.split(" ")[0]; return <Preset key={key} description={preset.description} onSelect={preset.onSelect} />; }); return ( <div className="table-manip"> <div className="table-manip-presets"> {presets} </div> <div className="table-manip-col table-manip-filters" > <div className="table-manip-row"> <FilterInput type="text" value={this.props.filters.get("filterBy")} setFilter={this.props.setFilter} className={textFilterClassName} placeholder="Filter all by..." /> { this.props.filters.has("startDate") ? <DateSelector value={this.props.filters.get("startDate")} onChange={this.props.setStartDate} className={dateFilterClassName} inputClass={"clearable"} label="Earliest shipping date" /> : null } { this.props.filters.has("endDate") ? <DateSelector value={this.props.filters.get("endDate")} onChange={this.props.setEndDate} className={dateFilterClassName} inputClass={"clearable"} label="Latest shipping date" /> : null } </div> <PaginationInfo numberOfRows={this.props.numberOfRows} /> </div> <div className="table-manip-col"> {selects} </div> { this.props.children ? <div className="table-manip-col table-manip-children"> {this.props.children} </div> : <span/> } </div> ); } } Filter.propTypes = { filters: IPropTypes.shape({ filterBy : PropTypes.string, startDate : PropTypes.string, endDate : PropTypes.string, restrictions: IPropTypes.mapOf(IPropTypes.shape({ key : PropTypes.string, options: IPropTypes.listOf(PropTypes.oneOfType([ PropTypes.string, PropTypes.number, PropTypes.bool ]) ) }) ) }), selections : IPropTypes.mapOf(IPropTypes.listOf(PropTypes.oneOfType([ PropTypes.string, PropTypes.number, PropTypes.bool ]) )), presetConfig : PropTypes.arrayOf(PropTypes.shape({ description: PropTypes.string, onSelect: PropTypes.arrayOf(PropTypes.func) })), setFilter : PropTypes.func, setStartDate : PropTypes.func, setEndDate : PropTypes.func, restrictTo : PropTypes.func, numberOfRows: PropTypes.number };
var ShitList = require('./shitList.js'); var shitList = new ShitList(); shitList.getAll().then(function (shitList) { if (shitList.length <= 0) { shitList = ["Your shit list is empty."]; } shitList.forEach(function (hostname) { var $item = $('<li>').text(hostname); $('.list').append($item); }); });
'use strict' const helpers = require('../apps/helpers') const log = helpers.remoteLog let logMeta = { js: 'userManager.js' } const inspect = require('util').inspect let addUserManager = (processObjects) => { log('info', 'Adding User Management Module', logMeta) return new Promise((resolve, reject) => { let redis = processObjects.redis let umRedisClient = processObjects.umRedisClient processObjects.userManager = () => { //add socket.id -> emailid mappings processObjects.userManager.addSocket = (socketID, emailID, next) => { umRedisClient.set('socketID.' + socketID, emailID, (err, reply) => { if (err) { log('error', 'processObjects.userManager.addSocket Issue with set, returned ' + err, logMeta) return next(false, err) } else { //log('debug', ' set Success, Reply ' + reply, logMeta) umRedisClient.expire('socketID.' + socketID, 1 * 10 * 60, (err, reply) => {//Set to Expire after 10 minutes if (err) { log('error', 'processObjects.userManager.addSocket Issue with expire, returned ' + err, logMeta) return next(false, err) } else { log('debug', ' Update Successful for user ' + emailID + ' SocketID:' + socketID, logMeta) processObjects.userManager.updateUser(emailID, 'SocketID', socketID, next) } }) } }) } //remove socketid->emaidid mapping processObjects.userManager.removeSocket = (socketID, next) => { umRedisClient.get('socketID.' + socketID, (err, reply) => { if (err) { log('error', 'processObjects.userManager.removeSocket Problem in get socketid. -> ' + err, logMeta) return next(false, err) } else { log('debug', ' ' + socketID + ' going to be deleted -> related user' + inspect(reply), logMeta) let userToBeDeleted = reply umRedisClient.del('socketID.' + socketID, (err, reply) => { if (err) { log('error', 'processObjects.userManager.removeSocket Problem in del -> ' + err, logMeta) return next(false, err) } else { log('debug', 'socketID.' + socketID + ' deleted with reply -> ' + inspect(reply), logMeta) if (userToBeDeleted === 'Guest') {//For now remove 'Guest' only. If logged email is removed then cache is destroyed umRedisClient.del('user.' + userToBeDeleted, (err, reply) => { if (err) { log('error', 'processObjects.userManager.removeSocket Problem in del user.socketID-> ' + err, logMeta) return next(false, err) } else { log('debug', 'user.socketID.' + userToBeDeleted + ' deleted with reply -> ' + inspect(reply), logMeta) return next(true, null) } }) } else { return next(true, null) } } }) } }) } //Get SocketID from email processObjects.userManager.getValueFromemail = (emailID, key) => { return new Promise((resolve, reject) => { umRedisClient.get('user.' + emailID, (err, reply) => { if (err) { reject('processObjects.userManager.getSocketIDFromemail->umRedisClient.get for user.' + emailID + 'resulted in error:' + err) } else { log('debug', 'Search for key:' + key + ' for ' + emailID + ' resulted in -> ' + reply, logMeta) if (reply != null) { resolve(JSON.parse(reply)[key]) } else { reject('processObjects.userManager.getSocketIDFromemail->umRedisClient.get for user.' + emailID + 'resulted in NULL response') } } }) }) } //SocketID List LAtest processObjects.userManager.getLoggedSocketID = (returnSocketIDList) => { return umRedisClient.keys('userMan.socketID.*', (err, reply) => { if (err) { log('error', 'processObjects.userManager.getLoggedSocketID resulted in error -> ' + err, logMeta) return null } else { //log('debug', ' getLoggedSocketID resulted in -> ' + reply, logMeta) let SocketIDList = reply.map((val) => { return val.slice(17) }) if (typeof returnSocketIDList === 'function') { return returnSocketIDList(SocketIDList) } else { return JSON.stringify(SocketIDList)//[TODO]Not intended to be used as of now...may need to remove } } }) } //Update Property related to user if user exists processObjects.userManager.updateUser = (emailID, key, value, next) => { //Update User Properties if (emailID === 'Guest') { let profile = { email: emailID } profile[key] = value umRedisClient.set('user.' + profile.email, JSON.stringify(profile), (err, reply) => { if (err) { log('error', ' Issue with set, returned ' + err, logMeta) return next(false, err) } else { //log('debug', ' set Success, Reply ' + reply, logMeta) umRedisClient.expire('user.' + profile.email, 1 * 10 * 60, (err, reply) => {//Set to Expire after 10 minutes if (err) { log('error', ' Issue with expire, returned ' + err, logMeta) return next(false, err) } else { //log('debug', ' Update Successful for user ' + profile.email + ' Key:' + key + ' Value:' + value, logMeta) return next(true, null) } }) } }) } else { umRedisClient.get('user.' + emailID, (err, reply) => { if (err) { log('error', ' get for ' + emailID + ' Failed with Error -> ' + err, logMeta) return next(false, err) } else { //log('debug', ' get for ' + emailID + ' Succeeded with reply -> ' + reply, logMeta) if (reply === null) { return next(false, emailID + " not found in Redis") } let profile = JSON.parse(reply) profile[key] = value umRedisClient.set('user.' + profile.email, JSON.stringify(profile), (err, reply) => { if (err) { log('error', ' Issue with set, returned ' + err, logMeta) return next(false, err) } else { //log('debug', ' set Success, Reply ' + reply, logMeta) umRedisClient.expire('user.' + profile.email, 8 * 60 * 60, (err, reply) => {//Set to Expire after 8 hours if (err) { log('error', ' Issue with expire, returned ' + err, logMeta) return next(false, err) } else { //log('debug', ' Update Successful for user ' + profile.email + ' Key:' + key + ' Value:' + value, logMeta) return next(true, null) } }) } }) } }) } } //All Below functions are for User Authentication with AzureAD // Add new User on successful Login processObjects.userManager.addUser = (profile) => { //Add new Profile to userArray umRedisClient.set('user.' + profile.email, JSON.stringify(profile), (err, reply) => { if (err) { log('error', 'processObjects.userManager.addUser Issue with set, returned ' + err, logMeta) } else { //log('debug', ' set Success, Reply ' + reply, logMeta) umRedisClient.expire('user.' + profile.email, 8 * 60 * 60, (err, reply) => {//Set to Expire after 8 hours if (err) { log('error', 'processObjects.userManager.addUser Issue with expire, returned ' + err, logMeta) } else { //log('debug', ' expire Success, Reply ' + reply, logMeta) } }) log('debug', 'User ' + profile.email + ' added to userManager', logMeta) } }) } processObjects.userManager.findUserByEmail = (email, cb) => {//Function used by Passport Deserializer to find email in userArray umRedisClient.get('user.' + email, (err, reply) => { if (err) { log('error', 'processObjects.userManager.findUserByEmail get for ' + email + ' Failed with Error -> ' + err, logMeta) return cb(null, null) } else { //log('debug',' get for ' + email + ' Succeeded with reply -> ' + reply,logMeta) return cb(null, JSON.parse(reply)) } }) } processObjects.userManager.removeUser = (email) => { umRedisClient.get('user.' + email, (err, obj) => { if (err) { log('error', 'processObjects.userManager.removeUser Problem in get -> ' + err, logMeta) } else { umRedisClient.del('user.' + email, (err, reply) => { if (err) { log('error', 'processObjects.userManager.removeUser Problem in del -> ' + err, logMeta) } else { log('debug', ' ' + email + ' deleted with reply -> ' + inspect(reply), logMeta) } }) } }) } processObjects.userManager.getLoggedUsers = () => { return new Promise((resolve, reject) => { umRedisClient.keys('userMan.user.*', (err, reply) => { if (err) { log('error', 'processObjects.userManager.getLoggedUserss resulted in error -> ' + err, logMeta) return reject('processObjects.userManager.getLoggedUserss resulted in error -> ' + err) } else { //log('debug', 'getLoggedUsers resulted in -> ' + reply, logMeta) return resolve(reply.map((val) => { return val.slice(13, -24) })) } }) }) } } processObjects.userManager() return process.nextTick(() => resolve(processObjects)) }) } module.exports = { addUserManager }