code
stringlengths
2
1.05M
/*! * Bootstrap-select v1.13.14 (https://developer.snapappointments.com/bootstrap-select) * * Copyright 2012-2020 SnapAppointments, LLC * Licensed under MIT (https://github.com/snapappointments/bootstrap-select/blob/master/LICENSE) */ !function(e,t){void 0===e&&void 0!==window&&(e=window),"function"==typeof define&&define.amd?define(["jquery"],function(e){return t(e)}):"object"==typeof module&&module.exports?module.exports=t(require("jquery")):t(e.jQuery)}(this,function(e){e.fn.selectpicker.defaults={noneSelectedText:"Aucune s\xe9lection",noneResultsText:"Aucun r\xe9sultat pour {0}",countSelectedText:function(e,t){return 1<e?"{0} \xe9l\xe9ments s\xe9lectionn\xe9s":"{0} \xe9l\xe9ment s\xe9lectionn\xe9"},maxOptionsText:function(e,t){return[1<e?"Limite atteinte ({n} \xe9l\xe9ments max)":"Limite atteinte ({n} \xe9l\xe9ment max)",1<t?"Limite du groupe atteinte ({n} \xe9l\xe9ments max)":"Limite du groupe atteinte ({n} \xe9l\xe9ment max)"]},multipleSeparator:", ",selectAllText:"Tout s\xe9lectionner",deselectAllText:"Tout d\xe9s\xe9lectionner"}});
// TODO:: banner (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(); })(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 = 7); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony export (immutable) */ __webpack_exports__["b"] = __extends; /* unused harmony export __assign */ /* unused harmony export __rest */ /* harmony export (immutable) */ __webpack_exports__["a"] = __decorate; /* unused harmony export __param */ /* unused harmony export __metadata */ /* unused harmony export __awaiter */ /* unused harmony export __generator */ /* unused harmony export __exportStar */ /* unused harmony export __values */ /* unused harmony export __read */ /* unused harmony export __spread */ /* unused harmony export __await */ /* unused harmony export __asyncGenerator */ /* unused harmony export __asyncDelegator */ /* unused harmony export __asyncValues */ /*! ***************************************************************************** Copyright (c) Microsoft Corporation. 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 THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT. See the Apache Version 2.0 License for specific language governing permissions and limitations under the License. ***************************************************************************** */ /* global Reflect, Promise */ var 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]; }; function __extends(d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); } var __assign = Object.assign || function __assign(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; } function __rest(s, e) { var t = {}; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p]; if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) if (e.indexOf(p[i]) < 0) t[p[i]] = s[p[i]]; return t; } function __decorate(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; } function __param(paramIndex, decorator) { return function (target, key) { decorator(target, key, paramIndex); } } function __metadata(metadataKey, metadataValue) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue); } function __awaiter(thisArg, _arguments, P, generator) { return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator.throw(value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); } function __generator(thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (_) try { if (f = 1, y && (t = y[op[0] & 2 ? "return" : op[0] ? "throw" : "next"]) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [0, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } } function __exportStar(m, exports) { for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p]; } function __values(o) { var m = typeof Symbol === "function" && o[Symbol.iterator], i = 0; if (m) return m.call(o); return { next: function () { if (o && i >= o.length) o = void 0; return { value: o && o[i++], done: !o }; } }; } function __read(o, n) { var m = typeof Symbol === "function" && o[Symbol.iterator]; if (!m) return o; var i = m.call(o), r, ar = [], e; try { while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); } catch (error) { e = { error: error }; } finally { try { if (r && !r.done && (m = i["return"])) m.call(i); } finally { if (e) throw e.error; } } return ar; } function __spread() { for (var ar = [], i = 0; i < arguments.length; i++) ar = ar.concat(__read(arguments[i])); return ar; } function __await(v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } function __asyncGenerator(thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); var g = generator.apply(thisArg, _arguments || []), i, q = []; return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } } function __asyncDelegator(o) { var i, p; return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; function verb(n, f) { if (o[n]) i[n] = function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; }; } } function __asyncValues(o) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); var m = o[Symbol.asyncIterator]; return m ? m.call(o) : typeof __values === "function" ? __values(o) : o[Symbol.iterator](); } /***/ }), /* 1 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return GraphQueryable; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return GraphQueryableCollection; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return GraphQueryableSearchableCollection; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return GraphQueryableInstance; }); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_tslib__ = __webpack_require__(0); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__pnp_common__ = __webpack_require__(2); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__pnp_odata__ = __webpack_require__(4); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__net_graphclient__ = __webpack_require__(6); /** * Queryable Base Class * */ var GraphQueryable = /** @class */ (function (_super) { __WEBPACK_IMPORTED_MODULE_0_tslib__["b" /* __extends */](GraphQueryable, _super); /** * Creates a new instance of the Queryable class * * @constructor * @param baseUrl A string or Queryable that should form the base part of the url * */ function GraphQueryable(baseUrl, path) { var _this = _super.call(this) || this; if (typeof baseUrl === "string") { var urlStr = baseUrl; _this._parentUrl = urlStr; _this._url = __WEBPACK_IMPORTED_MODULE_1__pnp_common__["d" /* Util */].combinePaths(urlStr, path); } else { var q = baseUrl; _this._parentUrl = q._url; _this._options = q._options; _this._url = __WEBPACK_IMPORTED_MODULE_1__pnp_common__["d" /* Util */].combinePaths(_this._parentUrl, path); } return _this; } /** * Creates a new instance of the supplied factory and extends this into that new instance * * @param factory constructor for the new queryable */ GraphQueryable.prototype.as = function (factory) { var o = new factory(this._url, null); return __WEBPACK_IMPORTED_MODULE_1__pnp_common__["d" /* Util */].extend(o, this, true); }; /** * Gets the full url with query information * */ GraphQueryable.prototype.toUrlAndQuery = function () { var _this = this; return this.toUrl() + ("?" + this._query.getKeys().map(function (key) { return key + "=" + _this._query.get(key); }).join("&")); }; /** * Gets a parent for this instance as specified * * @param factory The contructor for the class to create */ GraphQueryable.prototype.getParent = function (factory, baseUrl, path) { if (baseUrl === void 0) { baseUrl = this.parentUrl; } return new factory(baseUrl, path); }; /** * Clones this queryable into a new queryable instance of T * @param factory Constructor used to create the new instance * @param additionalPath Any additional path to include in the clone * @param includeBatch If true this instance's batch will be added to the cloned instance */ GraphQueryable.prototype.clone = function (factory, additionalPath, includeBatch) { if (includeBatch === void 0) { includeBatch = true; } // TODO:: include batching info in clone if (includeBatch) { return new factory(this, additionalPath); } return new factory(this, additionalPath); }; /** * Converts the current instance to a request context * * @param verb The request verb * @param options The set of supplied request options * @param parser The supplied ODataParser instance * @param pipeline Optional request processing pipeline */ GraphQueryable.prototype.toRequestContext = function (verb, options, parser, pipeline) { if (options === void 0) { options = {}; } if (pipeline === void 0) { pipeline = __WEBPACK_IMPORTED_MODULE_2__pnp_odata__["e" /* PipelineMethods */].default; } // TODO:: add batch support return Promise.resolve({ batch: this.batch, batchDependency: function () { return void (0); }, cachingOptions: this._cachingOptions, clientFactory: function () { return new __WEBPACK_IMPORTED_MODULE_3__net_graphclient__["a" /* GraphHttpClient */](); }, isBatched: this.hasBatch, isCached: this._useCaching, options: options, parser: parser, pipeline: pipeline, requestAbsoluteUrl: this.toUrlAndQuery(), requestId: __WEBPACK_IMPORTED_MODULE_1__pnp_common__["d" /* Util */].getGUID(), verb: verb, }); }; return GraphQueryable; }(__WEBPACK_IMPORTED_MODULE_2__pnp_odata__["d" /* ODataQueryable */])); /** * Represents a REST collection which can be filtered, paged, and selected * */ var GraphQueryableCollection = /** @class */ (function (_super) { __WEBPACK_IMPORTED_MODULE_0_tslib__["b" /* __extends */](GraphQueryableCollection, _super); function GraphQueryableCollection() { return _super !== null && _super.apply(this, arguments) || this; } /** * * @param filter The string representing the filter query */ GraphQueryableCollection.prototype.filter = function (filter) { this._query.add("$filter", filter); return this; }; /** * Choose which fields to return * * @param selects One or more fields to return */ GraphQueryableCollection.prototype.select = function () { var selects = []; for (var _i = 0; _i < arguments.length; _i++) { selects[_i] = arguments[_i]; } if (selects.length > 0) { this._query.add("$select", selects.join(",")); } return this; }; /** * Expands fields such as lookups to get additional data * * @param expands The Fields for which to expand the values */ GraphQueryableCollection.prototype.expand = function () { var expands = []; for (var _i = 0; _i < arguments.length; _i++) { expands[_i] = arguments[_i]; } if (expands.length > 0) { this._query.add("$expand", expands.join(",")); } return this; }; /** * Orders based on the supplied fields ascending * * @param orderby The name of the field to sort on * @param ascending If false DESC is appended, otherwise ASC (default) */ GraphQueryableCollection.prototype.orderBy = function (orderBy, ascending) { if (ascending === void 0) { ascending = true; } var keys = this._query.getKeys(); var query = []; var asc = ascending ? " asc" : " desc"; for (var i = 0; i < keys.length; i++) { if (keys[i] === "$orderby") { query.push(this._query.get("$orderby")); break; } } query.push("" + orderBy + asc); this._query.add("$orderby", query.join(",")); return this; }; /** * Limits the query to only return the specified number of items * * @param top The query row limit */ GraphQueryableCollection.prototype.top = function (top) { this._query.add("$top", top.toString()); return this; }; /** * Skips a set number of items in the return set * * @param num Number of items to skip */ GraphQueryableCollection.prototype.skip = function (num) { this._query.add("$top", num.toString()); return this; }; /** * To request second and subsequent pages of Graph data */ GraphQueryableCollection.prototype.skipToken = function (token) { this._query.add("$skiptoken", token); return this; }; Object.defineProperty(GraphQueryableCollection.prototype, "count", { /** * Retrieves the total count of matching resources */ get: function () { this._query.add("$count", "true"); return this; }, enumerable: true, configurable: true }); return GraphQueryableCollection; }(GraphQueryable)); var GraphQueryableSearchableCollection = /** @class */ (function (_super) { __WEBPACK_IMPORTED_MODULE_0_tslib__["b" /* __extends */](GraphQueryableSearchableCollection, _super); function GraphQueryableSearchableCollection() { return _super !== null && _super.apply(this, arguments) || this; } /** * To request second and subsequent pages of Graph data */ GraphQueryableSearchableCollection.prototype.search = function (query) { this._query.add("$search", query); return this; }; return GraphQueryableSearchableCollection; }(GraphQueryableCollection)); /** * Represents an instance that can be selected * */ var GraphQueryableInstance = /** @class */ (function (_super) { __WEBPACK_IMPORTED_MODULE_0_tslib__["b" /* __extends */](GraphQueryableInstance, _super); function GraphQueryableInstance() { return _super !== null && _super.apply(this, arguments) || this; } /** * Choose which fields to return * * @param selects One or more fields to return */ GraphQueryableInstance.prototype.select = function () { var selects = []; for (var _i = 0; _i < arguments.length; _i++) { selects[_i] = arguments[_i]; } if (selects.length > 0) { this._query.add("$select", selects.join(",")); } return this; }; /** * Expands fields such as lookups to get additional data * * @param expands The Fields for which to expand the values */ GraphQueryableInstance.prototype.expand = function () { var expands = []; for (var _i = 0; _i < arguments.length; _i++) { expands[_i] = arguments[_i]; } if (expands.length > 0) { this._query.add("$expand", expands.join(",")); } return this; }; return GraphQueryableInstance; }(GraphQueryable)); //# sourceMappingURL=graphqueryable.js.map /***/ }), /* 2 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return Util; }); /* unused harmony export readBlobAsText */ /* unused harmony export readBlobAsArrayBuffer */ /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return Dictionary; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "g", function() { return mergeOptions; }); /* unused harmony export deprecated */ /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "e", function() { return beta; }); /* unused harmony export UrlException */ /* unused harmony export CommonRuntimeConfigKeys */ /* unused harmony export RuntimeConfigImpl */ /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return RuntimeConfig; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "f", function() { return mergeHeaders; }); /* unused harmony export PnPClientStorageWrapper */ /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return PnPClientStorage; }); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__pnp_logging__ = __webpack_require__(3); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_1_tslib__ = __webpack_require__(0); /** * Reads a blob as text * * @param blob The data to read */ function readBlobAsText(blob) { return readBlobAs(blob, "string"); } /** * Reads a blob into an array buffer * * @param blob The data to read */ function readBlobAsArrayBuffer(blob) { return readBlobAs(blob, "buffer"); } /** * Generic method to read blob's content * * @param blob The data to read * @param mode The read mode */ function readBlobAs(blob, mode) { return new Promise(function (resolve, reject) { try { var reader = new FileReader(); reader.onload = function (e) { resolve(e.target.result); }; switch (mode) { case "string": reader.readAsText(blob); break; case "buffer": reader.readAsArrayBuffer(blob); break; } } catch (e) { reject(e); } }); } /** * Generic dictionary */ var Dictionary = /** @class */ (function () { /** * Creates a new instance of the Dictionary<T> class * * @constructor */ function Dictionary(keys, values) { if (keys === void 0) { keys = []; } if (values === void 0) { values = []; } this.keys = keys; this.values = values; } /** * Gets a value from the collection using the specified key * * @param key The key whose value we want to return, returns null if the key does not exist */ Dictionary.prototype.get = function (key) { var index = this.keys.indexOf(key); if (index < 0) { return null; } return this.values[index]; }; /** * Adds the supplied key and value to the dictionary * * @param key The key to add * @param o The value to add */ Dictionary.prototype.add = function (key, o) { var index = this.keys.indexOf(key); if (index > -1) { if (o === null) { this.remove(key); } else { this.values[index] = o; } } else { if (o !== null) { this.keys.push(key); this.values.push(o); } } }; /** * Merges the supplied typed hash into this dictionary instance. Existing values are updated and new ones are created as appropriate. */ Dictionary.prototype.merge = function (source) { var _this = this; if ("getKeys" in source) { var sourceAsDictionary_1 = source; sourceAsDictionary_1.getKeys().map(function (key) { _this.add(key, sourceAsDictionary_1.get(key)); }); } else { var sourceAsHash = source; for (var key in sourceAsHash) { if (sourceAsHash.hasOwnProperty(key)) { this.add(key, sourceAsHash[key]); } } } }; /** * Removes a value from the dictionary * * @param key The key of the key/value pair to remove. Returns null if the key was not found. */ Dictionary.prototype.remove = function (key) { var index = this.keys.indexOf(key); if (index < 0) { return null; } var val = this.values[index]; this.keys.splice(index, 1); this.values.splice(index, 1); return val; }; /** * Returns all the keys currently in the dictionary as an array */ Dictionary.prototype.getKeys = function () { return this.keys; }; /** * Returns all the values currently in the dictionary as an array */ Dictionary.prototype.getValues = function () { return this.values; }; /** * Clears the current dictionary */ Dictionary.prototype.clear = function () { this.keys = []; this.values = []; }; /** * Gets a count of the items currently in the dictionary */ Dictionary.prototype.count = function () { return this.keys.length; }; return Dictionary; }()); var Util = /** @class */ (function () { function Util() { } /** * Gets a callback function which will maintain context across async calls. * Allows for the calling pattern getCtxCallback(thisobj, method, methodarg1, methodarg2, ...) * * @param context The object that will be the 'this' value in the callback * @param method The method to which we will apply the context and parameters * @param params Optional, additional arguments to supply to the wrapped method when it is invoked */ Util.getCtxCallback = function (context, method) { var params = []; for (var _i = 2; _i < arguments.length; _i++) { params[_i - 2] = arguments[_i]; } return function () { method.apply(context, params); }; }; /** * Tests if a url param exists * * @param name The name of the url paramter to check */ Util.urlParamExists = function (name) { name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]"); var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"); return regex.test(location.search); }; /** * Gets a url param value by name * * @param name The name of the paramter for which we want the value */ Util.getUrlParamByName = function (name) { name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]"); var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"); var results = regex.exec(location.search); return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " ")); }; /** * Gets a url param by name and attempts to parse a bool value * * @param name The name of the paramter for which we want the boolean value */ Util.getUrlParamBoolByName = function (name) { var p = this.getUrlParamByName(name); var isFalse = (p === "" || /false|0/i.test(p)); return !isFalse; }; /** * Inserts the string s into the string target as the index specified by index * * @param target The string into which we will insert s * @param index The location in target to insert s (zero based) * @param s The string to insert into target at position index */ Util.stringInsert = function (target, index, s) { if (index > 0) { return target.substring(0, index) + s + target.substring(index, target.length); } return s + target; }; /** * Adds a value to a date * * @param date The date to which we will add units, done in local time * @param interval The name of the interval to add, one of: ['year', 'quarter', 'month', 'week', 'day', 'hour', 'minute', 'second'] * @param units The amount to add to date of the given interval * * http://stackoverflow.com/questions/1197928/how-to-add-30-minutes-to-a-javascript-date-object */ Util.dateAdd = function (date, interval, units) { var ret = new Date(date); // don't change original date switch (interval.toLowerCase()) { case "year": ret.setFullYear(ret.getFullYear() + units); break; case "quarter": ret.setMonth(ret.getMonth() + 3 * units); break; case "month": ret.setMonth(ret.getMonth() + units); break; case "week": ret.setDate(ret.getDate() + 7 * units); break; case "day": ret.setDate(ret.getDate() + units); break; case "hour": ret.setTime(ret.getTime() + units * 3600000); break; case "minute": ret.setTime(ret.getTime() + units * 60000); break; case "second": ret.setTime(ret.getTime() + units * 1000); break; default: ret = undefined; break; } return ret; }; /** * Loads a stylesheet into the current page * * @param path The url to the stylesheet * @param avoidCache If true a value will be appended as a query string to avoid browser caching issues */ Util.loadStylesheet = function (path, avoidCache) { if (avoidCache) { path += "?" + encodeURIComponent((new Date()).getTime().toString()); } var head = document.getElementsByTagName("head"); if (head.length > 0) { var e = document.createElement("link"); head[0].appendChild(e); e.setAttribute("type", "text/css"); e.setAttribute("rel", "stylesheet"); e.setAttribute("href", path); } }; /** * Combines an arbitrary set of paths ensuring that the slashes are normalized * * @param paths 0 to n path parts to combine */ Util.combinePaths = function () { var paths = []; for (var _i = 0; _i < arguments.length; _i++) { paths[_i] = arguments[_i]; } return paths .filter(function (path) { return !Util.stringIsNullOrEmpty(path); }) .map(function (path) { return path.replace(/^[\\|\/]/, "").replace(/[\\|\/]$/, ""); }) .join("/") .replace(/\\/g, "/"); }; /** * Gets a random string of chars length * * @param chars The length of the random string to generate */ Util.getRandomString = function (chars) { var text = new Array(chars); var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; for (var i = 0; i < chars; i++) { text[i] = possible.charAt(Math.floor(Math.random() * possible.length)); } return text.join(""); }; /** * Gets a random GUID value * * http://stackoverflow.com/questions/105034/create-guid-uuid-in-javascript */ /* tslint:disable no-bitwise */ Util.getGUID = function () { var d = new Date().getTime(); var guid = "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function (c) { var r = (d + Math.random() * 16) % 16 | 0; d = Math.floor(d / 16); return (c === "x" ? r : (r & 0x3 | 0x8)).toString(16); }); return guid; }; /* tslint:enable */ /** * Determines if a given value is a function * * @param candidateFunction The thing to test for being a function */ Util.isFunction = function (candidateFunction) { return typeof candidateFunction === "function"; }; /** * Determines if an object is both defined and not null * @param obj Object to test */ Util.objectDefinedNotNull = function (obj) { return typeof obj !== "undefined" && obj !== null; }; /** * @returns whether the provided parameter is a JavaScript Array or not. */ Util.isArray = function (array) { if (Array.isArray) { return Array.isArray(array); } return array && typeof array.length === "number" && array.constructor === Array; }; /** * Determines if a string is null or empty or undefined * * @param s The string to test */ Util.stringIsNullOrEmpty = function (s) { return typeof s === "undefined" || s === null || s.length < 1; }; /** * Provides functionality to extend the given object by doing a shallow copy * * @param target The object to which properties will be copied * @param source The source object from which properties will be copied * @param noOverwrite If true existing properties on the target are not overwritten from the source * */ Util.extend = function (target, source, noOverwrite) { if (noOverwrite === void 0) { noOverwrite = false; } if (!Util.objectDefinedNotNull(source)) { return target; } // ensure we don't overwrite things we don't want overwritten var check = noOverwrite ? function (o, i) { return !(i in o); } : function () { return true; }; return Object.getOwnPropertyNames(source) .filter(function (v) { return check(target, v); }) .reduce(function (t, v) { t[v] = source[v]; return t; }, target); }; /** * Determines if a given url is absolute * * @param url The url to check to see if it is absolute */ Util.isUrlAbsolute = function (url) { return /^https?:\/\/|^\/\//i.test(url); }; return Util; }()); function mergeOptions(target, source) { if (Util.objectDefinedNotNull(source)) { var headers = Util.extend(target.headers || {}, source.headers); target = Util.extend(target, source); target.headers = headers; } } function deprecated(deprecationVersion, message) { return function (target, propertyKey, descriptor) { var method = descriptor.value; descriptor.value = function () { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } __WEBPACK_IMPORTED_MODULE_0__pnp_logging__["a" /* Logger */].log({ data: { descriptor: descriptor, propertyKey: propertyKey, target: target, }, level: 2 /* Warning */, message: "(" + deprecationVersion + ") " + message, }); return method.apply(this, args); }; }; } function beta(message) { if (message === void 0) { message = "This feature is flagged as beta and is subject to change."; } return function (target, propertyKey, descriptor) { var method = descriptor.value; descriptor.value = function () { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } __WEBPACK_IMPORTED_MODULE_0__pnp_logging__["a" /* Logger */].log({ data: { descriptor: descriptor, propertyKey: propertyKey, target: target, }, level: 2 /* Warning */, message: message, }); return method.apply(this, args); }; }; } var UrlException = /** @class */ (function (_super) { Object(__WEBPACK_IMPORTED_MODULE_1_tslib__["b" /* __extends */])(UrlException, _super); function UrlException(msg) { var _this = _super.call(this, msg) || this; _this.name = "UrlException"; __WEBPACK_IMPORTED_MODULE_0__pnp_logging__["a" /* Logger */].log({ data: {}, level: 3 /* Error */, message: "[" + _this.name + "]::" + _this.message }); return _this; } return UrlException; }(Error)); var CommonRuntimeConfigKeys = /** @class */ (function () { function CommonRuntimeConfigKeys() { } CommonRuntimeConfigKeys.defaultCachingStore = "defaultCachingStore"; CommonRuntimeConfigKeys.defaultCachingTimeoutSeconds = "defaultCachingTimeoutSeconds"; CommonRuntimeConfigKeys.globalCacheDisable = "globalCacheDisable"; CommonRuntimeConfigKeys.enableCacheExpiration = "enableCacheExpiration"; CommonRuntimeConfigKeys.cacheExpirationIntervalMilliseconds = "cacheExpirationIntervalMilliseconds"; CommonRuntimeConfigKeys.spfxContext = "spfxContext"; return CommonRuntimeConfigKeys; }()); var RuntimeConfigImpl = /** @class */ (function () { function RuntimeConfigImpl() { this._v = new Dictionary(); // setup defaults this._v.add(CommonRuntimeConfigKeys.defaultCachingStore, "session"); this._v.add(CommonRuntimeConfigKeys.defaultCachingTimeoutSeconds, 60); this._v.add(CommonRuntimeConfigKeys.globalCacheDisable, false); this._v.add(CommonRuntimeConfigKeys.enableCacheExpiration, false); this._v.add(CommonRuntimeConfigKeys.cacheExpirationIntervalMilliseconds, 750); this._v.add(CommonRuntimeConfigKeys.spfxContext, null); } /** * * @param config The set of properties to add to the globa configuration instance */ RuntimeConfigImpl.prototype.extend = function (config) { var _this = this; Object.keys(config).forEach(function (key) { _this._v.add(key, config[key]); }); }; RuntimeConfigImpl.prototype.get = function (key) { return this._v.get(key); }; Object.defineProperty(RuntimeConfigImpl.prototype, "defaultCachingStore", { get: function () { return this.get(CommonRuntimeConfigKeys.defaultCachingStore); }, enumerable: true, configurable: true }); Object.defineProperty(RuntimeConfigImpl.prototype, "defaultCachingTimeoutSeconds", { get: function () { return this.get(CommonRuntimeConfigKeys.defaultCachingTimeoutSeconds); }, enumerable: true, configurable: true }); Object.defineProperty(RuntimeConfigImpl.prototype, "globalCacheDisable", { get: function () { return this.get(CommonRuntimeConfigKeys.globalCacheDisable); }, enumerable: true, configurable: true }); Object.defineProperty(RuntimeConfigImpl.prototype, "enableCacheExpiration", { get: function () { return this.get(CommonRuntimeConfigKeys.enableCacheExpiration); }, enumerable: true, configurable: true }); Object.defineProperty(RuntimeConfigImpl.prototype, "cacheExpirationIntervalMilliseconds", { get: function () { return this.get(CommonRuntimeConfigKeys.cacheExpirationIntervalMilliseconds); }, enumerable: true, configurable: true }); Object.defineProperty(RuntimeConfigImpl.prototype, "spfxContext", { get: function () { return this.get(CommonRuntimeConfigKeys.spfxContext); }, enumerable: true, configurable: true }); return RuntimeConfigImpl; }()); var _runtimeConfig = new RuntimeConfigImpl(); var RuntimeConfig = _runtimeConfig; function mergeHeaders(target, source) { if (typeof source !== "undefined" && source !== null) { var temp = new Request("", { headers: source }); temp.headers.forEach(function (value, name) { target.append(name, value); }); } } /** * A wrapper class to provide a consistent interface to browser based storage * */ var PnPClientStorageWrapper = /** @class */ (function () { /** * Creates a new instance of the PnPClientStorageWrapper class * * @constructor */ function PnPClientStorageWrapper(store, defaultTimeoutMinutes) { if (defaultTimeoutMinutes === void 0) { defaultTimeoutMinutes = -1; } this.store = store; this.defaultTimeoutMinutes = defaultTimeoutMinutes; this.enabled = this.test(); // if the cache timeout is enabled call the handler // this will clear any expired items and set the timeout function if (RuntimeConfig.enableCacheExpiration) { __WEBPACK_IMPORTED_MODULE_0__pnp_logging__["a" /* Logger */].write("Enabling cache expiration.", 1 /* Info */); this.cacheExpirationHandler(); } } /** * Get a value from storage, or null if that value does not exist * * @param key The key whose value we want to retrieve */ PnPClientStorageWrapper.prototype.get = function (key) { if (!this.enabled) { return null; } var o = this.store.getItem(key); if (o == null) { return null; } var persistable = JSON.parse(o); if (new Date(persistable.expiration) <= new Date()) { __WEBPACK_IMPORTED_MODULE_0__pnp_logging__["a" /* Logger */].write("Removing item with key '" + key + "' from cache due to expiration.", 1 /* Info */); this.delete(key); return null; } else { return persistable.value; } }; /** * Adds a value to the underlying storage * * @param key The key to use when storing the provided value * @param o The value to store * @param expire Optional, if provided the expiration of the item, otherwise the default is used */ PnPClientStorageWrapper.prototype.put = function (key, o, expire) { if (this.enabled) { this.store.setItem(key, this.createPersistable(o, expire)); } }; /** * Deletes a value from the underlying storage * * @param key The key of the pair we want to remove from storage */ PnPClientStorageWrapper.prototype.delete = function (key) { if (this.enabled) { this.store.removeItem(key); } }; /** * Gets an item from the underlying storage, or adds it if it does not exist using the supplied getter function * * @param key The key to use when storing the provided value * @param getter A function which will upon execution provide the desired value * @param expire Optional, if provided the expiration of the item, otherwise the default is used */ PnPClientStorageWrapper.prototype.getOrPut = function (key, getter, expire) { var _this = this; if (!this.enabled) { return getter(); } return new Promise(function (resolve) { var o = _this.get(key); if (o == null) { getter().then(function (d) { _this.put(key, d, expire); resolve(d); }); } else { resolve(o); } }); }; /** * Deletes any expired items placed in the store by the pnp library, leaves other items untouched */ PnPClientStorageWrapper.prototype.deleteExpired = function () { var _this = this; return new Promise(function (resolve, reject) { if (!_this.enabled) { resolve(); } try { for (var i = 0; i < _this.store.length; i++) { var key = _this.store.key(i); if (key !== null) { // test the stored item to see if we stored it if (/["|']?pnp["|']? ?: ?1/i.test(_this.store.getItem(key))) { // get those items as get will delete from cache if they are expired _this.get(key); } } } resolve(); } catch (e) { reject(e); } }); }; /** * Used to determine if the wrapped storage is available currently */ PnPClientStorageWrapper.prototype.test = function () { var str = "test"; try { this.store.setItem(str, str); this.store.removeItem(str); return true; } catch (e) { return false; } }; /** * Creates the persistable to store */ PnPClientStorageWrapper.prototype.createPersistable = function (o, expire) { if (typeof expire === "undefined") { // ensure we are by default inline with the global library setting var defaultTimeout = RuntimeConfig.defaultCachingTimeoutSeconds; if (this.defaultTimeoutMinutes > 0) { defaultTimeout = this.defaultTimeoutMinutes * 60; } expire = Util.dateAdd(new Date(), "second", defaultTimeout); } return JSON.stringify({ pnp: 1, expiration: expire, value: o }); }; /** * Deletes expired items added by this library in this.store and sets a timeout to call itself */ PnPClientStorageWrapper.prototype.cacheExpirationHandler = function () { var _this = this; __WEBPACK_IMPORTED_MODULE_0__pnp_logging__["a" /* Logger */].write("Called cache expiration handler.", 0 /* Verbose */); this.deleteExpired().then(function (_) { // call ourself in the future setTimeout(Util.getCtxCallback(_this, _this.cacheExpirationHandler), RuntimeConfig.cacheExpirationIntervalMilliseconds); }).catch(function (e) { // we've got some error - so just stop the loop and report the error __WEBPACK_IMPORTED_MODULE_0__pnp_logging__["a" /* Logger */].log({ data: e, level: 3 /* Error */, message: "Error deleting expired cache entries, see data for details. Timeout not reset.", }); }); }; return PnPClientStorageWrapper; }()); /** * A thin implementation of in-memory storage for use in nodejs */ var MemoryStorage = /** @class */ (function () { function MemoryStorage(_store) { if (_store === void 0) { _store = new Dictionary(); } this._store = _store; } Object.defineProperty(MemoryStorage.prototype, "length", { get: function () { return this._store.count(); }, enumerable: true, configurable: true }); MemoryStorage.prototype.clear = function () { this._store.clear(); }; MemoryStorage.prototype.getItem = function (key) { return this._store.get(key); }; MemoryStorage.prototype.key = function (index) { return this._store.getKeys()[index]; }; MemoryStorage.prototype.removeItem = function (key) { this._store.remove(key); }; MemoryStorage.prototype.setItem = function (key, data) { this._store.add(key, data); }; return MemoryStorage; }()); /** * A class that will establish wrappers for both local and session storage */ var PnPClientStorage = /** @class */ (function () { /** * Creates a new instance of the PnPClientStorage class * * @constructor */ function PnPClientStorage(_local, _session) { if (_local === void 0) { _local = null; } if (_session === void 0) { _session = null; } this._local = _local; this._session = _session; } Object.defineProperty(PnPClientStorage.prototype, "local", { /** * Provides access to the local storage of the browser */ get: function () { if (this._local === null) { this._local = typeof localStorage !== "undefined" ? new PnPClientStorageWrapper(localStorage) : new PnPClientStorageWrapper(new MemoryStorage()); } return this._local; }, enumerable: true, configurable: true }); Object.defineProperty(PnPClientStorage.prototype, "session", { /** * Provides access to the session storage of the browser */ get: function () { if (this._session === null) { this._session = typeof sessionStorage !== "undefined" ? new PnPClientStorageWrapper(sessionStorage) : new PnPClientStorageWrapper(new MemoryStorage()); } return this._session; }, enumerable: true, configurable: true }); return PnPClientStorage; }()); //# sourceMappingURL=common.es5.js.map /***/ }), /* 3 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return Logger; }); /* unused harmony export ConsoleListener */ /* unused harmony export FunctionListener */ /** * 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); }; 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; }()); /** * 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=logging.es5.js.map /***/ }), /* 4 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* unused harmony export CachingOptions */ /* unused harmony export CachingParserWrapper */ /* unused harmony export ProcessHttpClientResponseException */ /* unused harmony export ODataParserBase */ /* unused harmony export ODataDefaultParser */ /* unused harmony export ODataValue */ /* unused harmony export ODataRawParserImpl */ /* unused harmony export ODataRaw */ /* unused harmony export TextFileParser */ /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return BlobFileParser; }); /* unused harmony export JSONFileParser */ /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return BufferFileParser; }); /* unused harmony export setResult */ /* unused harmony export pipe */ /* unused harmony export requestPipelineMethod */ /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "e", function() { return PipelineMethods; }); /* unused harmony export AlreadyInBatchException */ /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return ODataQueryable; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return ODataBatch; }); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__pnp_common__ = __webpack_require__(2); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_1_tslib__ = __webpack_require__(0); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__pnp_logging__ = __webpack_require__(3); var CachingOptions = /** @class */ (function () { function CachingOptions(key) { this.key = key; this.expiration = __WEBPACK_IMPORTED_MODULE_0__pnp_common__["d" /* Util */].dateAdd(new Date(), "second", __WEBPACK_IMPORTED_MODULE_0__pnp_common__["c" /* RuntimeConfig */].defaultCachingTimeoutSeconds); this.storeName = __WEBPACK_IMPORTED_MODULE_0__pnp_common__["c" /* RuntimeConfig */].defaultCachingStore; } Object.defineProperty(CachingOptions.prototype, "store", { get: function () { if (this.storeName === "local") { return CachingOptions.storage.local; } else { return CachingOptions.storage.session; } }, enumerable: true, configurable: true }); CachingOptions.storage = new __WEBPACK_IMPORTED_MODULE_0__pnp_common__["b" /* PnPClientStorage */](); return CachingOptions; }()); var CachingParserWrapper = /** @class */ (function () { function CachingParserWrapper(_parser, _cacheOptions) { this._parser = _parser; this._cacheOptions = _cacheOptions; } CachingParserWrapper.prototype.parse = function (response) { var _this = this; // add this to the cache based on the options return this._parser.parse(response).then(function (data) { if (_this._cacheOptions.store !== null) { _this._cacheOptions.store.put(_this._cacheOptions.key, data, _this._cacheOptions.expiration); } return data; }); }; return CachingParserWrapper; }()); /** * Represents an exception with an HttpClient request * */ var ProcessHttpClientResponseException = /** @class */ (function (_super) { Object(__WEBPACK_IMPORTED_MODULE_1_tslib__["b" /* __extends */])(ProcessHttpClientResponseException, _super); function ProcessHttpClientResponseException(status, statusText, data) { var _this = _super.call(this, "Error making HttpClient request in queryable: [" + status + "] " + statusText) || this; _this.status = status; _this.statusText = statusText; _this.data = data; _this.name = "ProcessHttpClientResponseException"; __WEBPACK_IMPORTED_MODULE_2__pnp_logging__["a" /* Logger */].log({ data: _this.data, level: 3 /* Error */, message: _this.message }); return _this; } return ProcessHttpClientResponseException; }(Error)); var ODataParserBase = /** @class */ (function () { function ODataParserBase() { } ODataParserBase.prototype.parse = function (r) { var _this = this; return new Promise(function (resolve, reject) { if (_this.handleError(r, reject)) { if ((r.headers.has("Content-Length") && parseFloat(r.headers.get("Content-Length") || "-1") === 0) || r.status === 204) { resolve({}); } else { // patch to handle cases of 200 response with no or whitespace only bodies (#487 & #545) r.text() .then(function (txt) { return txt.replace(/\s/ig, "").length > 0 ? JSON.parse(txt) : {}; }) .then(function (json) { return resolve(_this.parseODataJSON(json)); }) .catch(function (e) { return reject(e); }); } } }); }; ODataParserBase.prototype.handleError = function (r, reject) { if (!r.ok) { r.json().then(function (json) { // include the headers as they contain diagnostic information var data = { responseBody: json, responseHeaders: r.headers, }; reject(new ProcessHttpClientResponseException(r.status, r.statusText, data)); }).catch(function (e) { // we failed to read the body - possibly it is empty. Let's report the original status that caused // the request to fail and log the error without parsing the body if anyone needs it for debugging __WEBPACK_IMPORTED_MODULE_2__pnp_logging__["a" /* Logger */].log({ data: e, level: 2 /* Warning */, message: "There was an error parsing the error response body. See data for details.", }); // include the headers as they contain diagnostic information var data = { responseBody: "[[body not available]]", responseHeaders: r.headers, }; reject(new ProcessHttpClientResponseException(r.status, r.statusText, data)); }); } return r.ok; }; ODataParserBase.prototype.parseODataJSON = function (json) { var result = json; if (json.hasOwnProperty("d")) { if (json.d.hasOwnProperty("results")) { result = json.d.results; } else { result = json.d; } } else if (json.hasOwnProperty("value")) { result = json.value; } return result; }; return ODataParserBase; }()); var ODataDefaultParser = /** @class */ (function (_super) { Object(__WEBPACK_IMPORTED_MODULE_1_tslib__["b" /* __extends */])(ODataDefaultParser, _super); function ODataDefaultParser() { return _super !== null && _super.apply(this, arguments) || this; } return ODataDefaultParser; }(ODataParserBase)); var ODataValueParserImpl = /** @class */ (function (_super) { Object(__WEBPACK_IMPORTED_MODULE_1_tslib__["b" /* __extends */])(ODataValueParserImpl, _super); function ODataValueParserImpl() { return _super !== null && _super.apply(this, arguments) || this; } ODataValueParserImpl.prototype.parse = function (r) { return _super.prototype.parse.call(this, r).then(function (d) { return d; }); }; return ODataValueParserImpl; }(ODataParserBase)); function ODataValue() { return new ODataValueParserImpl(); } var ODataRawParserImpl = /** @class */ (function () { function ODataRawParserImpl() { } ODataRawParserImpl.prototype.parse = function (r) { return r.json(); }; return ODataRawParserImpl; }()); var ODataRaw = new ODataRawParserImpl(); var TextFileParser = /** @class */ (function () { function TextFileParser() { } TextFileParser.prototype.parse = function (r) { return r.text(); }; return TextFileParser; }()); var BlobFileParser = /** @class */ (function () { function BlobFileParser() { } BlobFileParser.prototype.parse = function (r) { return r.blob(); }; return BlobFileParser; }()); var JSONFileParser = /** @class */ (function () { function JSONFileParser() { } JSONFileParser.prototype.parse = function (r) { return r.json(); }; return JSONFileParser; }()); var BufferFileParser = /** @class */ (function () { function BufferFileParser() { } BufferFileParser.prototype.parse = function (r) { if (__WEBPACK_IMPORTED_MODULE_0__pnp_common__["d" /* Util */].isFunction(r.arrayBuffer)) { return r.arrayBuffer(); } return r.buffer(); }; return BufferFileParser; }()); /** * Resolves the context's result value * * @param context The current context */ function returnResult(context) { __WEBPACK_IMPORTED_MODULE_2__pnp_logging__["a" /* Logger */].log({ data: context.result, level: 0 /* Verbose */, message: "[" + context.requestId + "] (" + (new Date()).getTime() + ") Returning result, see data property for value.", }); return Promise.resolve(context.result || null); } /** * Sets the result on the context */ function setResult(context, value) { return new Promise(function (resolve) { context.result = value; context.hasResult = true; resolve(context); }); } /** * Invokes the next method in the provided context's pipeline * * @param c The current request context */ function next(c) { var _next = c.pipeline.shift(); if (typeof _next !== "undefined") { return _next(c); } else { return Promise.resolve(c); } } /** * Executes the current request context's pipeline * * @param context Current context */ function pipe(context) { return next(context) .then(function (ctx) { return returnResult(ctx); }) .catch(function (e) { __WEBPACK_IMPORTED_MODULE_2__pnp_logging__["a" /* Logger */].log({ data: e, level: 3 /* Error */, message: "Error in request pipeline: " + e.message, }); throw e; }); } /** * decorator factory applied to methods in the pipeline to control behavior */ function requestPipelineMethod(alwaysRun) { if (alwaysRun === void 0) { alwaysRun = false; } return function (target, propertyKey, descriptor) { var method = descriptor.value; descriptor.value = function () { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } // if we have a result already in the pipeline, pass it along and don't call the tagged method if (!alwaysRun && args.length > 0 && args[0].hasOwnProperty("hasResult") && args[0].hasResult) { __WEBPACK_IMPORTED_MODULE_2__pnp_logging__["a" /* Logger */].write("[" + args[0].requestId + "] (" + (new Date()).getTime() + ") Skipping request pipeline method " + propertyKey + ", existing result in pipeline.", 0 /* Verbose */); return Promise.resolve(args[0]); } // apply the tagged method __WEBPACK_IMPORTED_MODULE_2__pnp_logging__["a" /* Logger */].write("[" + args[0].requestId + "] (" + (new Date()).getTime() + ") Calling request pipeline method " + propertyKey + ".", 0 /* Verbose */); // then chain the next method in the context's pipeline - allows for dynamic pipeline return method.apply(target, args).then(function (ctx) { return next(ctx); }); }; }; } /** * Contains the methods used within the request pipeline */ var PipelineMethods = /** @class */ (function () { function PipelineMethods() { } /** * Logs the start of the request */ PipelineMethods.logStart = function (context) { return new Promise(function (resolve) { __WEBPACK_IMPORTED_MODULE_2__pnp_logging__["a" /* Logger */].log({ data: __WEBPACK_IMPORTED_MODULE_2__pnp_logging__["a" /* Logger */].activeLogLevel === 1 /* Info */ ? {} : context, level: 1 /* Info */, message: "[" + context.requestId + "] (" + (new Date()).getTime() + ") Beginning " + context.verb + " request (" + context.requestAbsoluteUrl + ")", }); resolve(context); }); }; /** * Handles caching of the request */ PipelineMethods.caching = function (context) { return new Promise(function (resolve) { // handle caching, if applicable if (context.verb === "GET" && context.isCached) { __WEBPACK_IMPORTED_MODULE_2__pnp_logging__["a" /* Logger */].write("[" + context.requestId + "] (" + (new Date()).getTime() + ") Caching is enabled for request, checking cache...", 1 /* Info */); var cacheOptions = new CachingOptions(context.requestAbsoluteUrl.toLowerCase()); if (typeof context.cachingOptions !== "undefined") { cacheOptions = __WEBPACK_IMPORTED_MODULE_0__pnp_common__["d" /* Util */].extend(cacheOptions, context.cachingOptions); } // we may not have a valid store if (cacheOptions.store !== null) { // check if we have the data in cache and if so resolve the promise and return var data = cacheOptions.store.get(cacheOptions.key); if (data !== null) { // ensure we clear any help batch dependency we are resolving from the cache __WEBPACK_IMPORTED_MODULE_2__pnp_logging__["a" /* Logger */].log({ data: __WEBPACK_IMPORTED_MODULE_2__pnp_logging__["a" /* Logger */].activeLogLevel === 1 /* Info */ ? {} : data, level: 1 /* Info */, message: "[" + context.requestId + "] (" + (new Date()).getTime() + ") Value returned from cache.", }); context.batchDependency(); // handle the case where a parser needs to take special actions with a cached result (such as getAs) if (context.parser.hasOwnProperty("hydrate")) { data = context.parser.hydrate(data); } return setResult(context, data).then(function (ctx) { return resolve(ctx); }); } } __WEBPACK_IMPORTED_MODULE_2__pnp_logging__["a" /* Logger */].write("[" + context.requestId + "] (" + (new Date()).getTime() + ") Value not found in cache.", 1 /* Info */); // if we don't then wrap the supplied parser in the caching parser wrapper // and send things on their way context.parser = new CachingParserWrapper(context.parser, cacheOptions); } return resolve(context); }); }; /** * Sends the request */ PipelineMethods.send = function (context) { return new Promise(function (resolve, reject) { // send or batch the request if (context.isBatched) { // we are in a batch, so add to batch, remove dependency, and resolve with the batch's promise var p = context.batch.add(context.requestAbsoluteUrl, context.verb, context.options, context.parser); // we release the dependency here to ensure the batch does not execute until the request is added to the batch context.batchDependency(); __WEBPACK_IMPORTED_MODULE_2__pnp_logging__["a" /* Logger */].write("[" + context.requestId + "] (" + (new Date()).getTime() + ") Batching request in batch " + context.batch.batchId + ".", 1 /* Info */); // we set the result as the promise which will be resolved by the batch's execution resolve(setResult(context, p)); } else { __WEBPACK_IMPORTED_MODULE_2__pnp_logging__["a" /* Logger */].write("[" + context.requestId + "] (" + (new Date()).getTime() + ") Sending request.", 1 /* Info */); // we are not part of a batch, so proceed as normal var client = context.clientFactory(); var opts = __WEBPACK_IMPORTED_MODULE_0__pnp_common__["d" /* Util */].extend(context.options || {}, { method: context.verb }); client.fetch(context.requestAbsoluteUrl, opts) .then(function (response) { return context.parser.parse(response); }) .then(function (result) { return setResult(context, result); }) .then(function (ctx) { return resolve(ctx); }) .catch(function (e) { return reject(e); }); } }); }; /** * Logs the end of the request */ PipelineMethods.logEnd = function (context) { return new Promise(function (resolve) { if (context.isBatched) { __WEBPACK_IMPORTED_MODULE_2__pnp_logging__["a" /* Logger */].log({ data: __WEBPACK_IMPORTED_MODULE_2__pnp_logging__["a" /* Logger */].activeLogLevel === 1 /* Info */ ? {} : context, level: 1 /* Info */, message: "[" + context.requestId + "] (" + (new Date()).getTime() + ") " + context.verb + " request will complete in batch " + context.batch.batchId + ".", }); } else { __WEBPACK_IMPORTED_MODULE_2__pnp_logging__["a" /* Logger */].log({ data: __WEBPACK_IMPORTED_MODULE_2__pnp_logging__["a" /* Logger */].activeLogLevel === 1 /* Info */ ? {} : context, level: 1 /* Info */, message: "[" + context.requestId + "] (" + (new Date()).getTime() + ") Completing " + context.verb + " request.", }); } resolve(context); }); }; Object.defineProperty(PipelineMethods, "default", { get: function () { return [ PipelineMethods.logStart, PipelineMethods.caching, PipelineMethods.send, PipelineMethods.logEnd, ]; }, enumerable: true, configurable: true }); Object(__WEBPACK_IMPORTED_MODULE_1_tslib__["a" /* __decorate */])([ requestPipelineMethod(true) ], PipelineMethods, "logStart", null); Object(__WEBPACK_IMPORTED_MODULE_1_tslib__["a" /* __decorate */])([ requestPipelineMethod() ], PipelineMethods, "caching", null); Object(__WEBPACK_IMPORTED_MODULE_1_tslib__["a" /* __decorate */])([ requestPipelineMethod() ], PipelineMethods, "send", null); Object(__WEBPACK_IMPORTED_MODULE_1_tslib__["a" /* __decorate */])([ requestPipelineMethod(true) ], PipelineMethods, "logEnd", null); return PipelineMethods; }()); var AlreadyInBatchException = /** @class */ (function (_super) { Object(__WEBPACK_IMPORTED_MODULE_1_tslib__["b" /* __extends */])(AlreadyInBatchException, _super); function AlreadyInBatchException(msg) { if (msg === void 0) { msg = "This query is already part of a batch."; } var _this = _super.call(this, msg) || this; _this.name = "AlreadyInBatchException"; __WEBPACK_IMPORTED_MODULE_2__pnp_logging__["a" /* Logger */].log({ data: {}, level: 3 /* Error */, message: "[" + _this.name + "]::" + _this.message }); return _this; } return AlreadyInBatchException; }(Error)); var ODataQueryable = /** @class */ (function () { function ODataQueryable() { this._batch = null; this._query = new __WEBPACK_IMPORTED_MODULE_0__pnp_common__["a" /* Dictionary */](); this._options = {}; this._url = ""; this._parentUrl = ""; this._useCaching = false; this._cachingOptions = null; } /** * Directly concatonates the supplied string to the current url, not normalizing "/" chars * * @param pathPart The string to concatonate to the url */ ODataQueryable.prototype.concat = function (pathPart) { this._url += pathPart; return this; }; Object.defineProperty(ODataQueryable.prototype, "query", { /** * Provides access to the query builder for this url * */ get: function () { return this._query; }, enumerable: true, configurable: true }); /** * Sets custom options for current object and all derived objects accessible via chaining * * @param options custom options */ ODataQueryable.prototype.configure = function (options) { Object(__WEBPACK_IMPORTED_MODULE_0__pnp_common__["g" /* mergeOptions */])(this._options, options); return this; }; /** * Enables caching for this request * * @param options Defines the options used when caching this request */ ODataQueryable.prototype.usingCaching = function (options) { if (!__WEBPACK_IMPORTED_MODULE_0__pnp_common__["c" /* RuntimeConfig */].globalCacheDisable) { this._useCaching = true; if (typeof options !== "undefined") { this._cachingOptions = options; } } return this; }; /** * Adds this query to the supplied batch * * @example * ``` * * let b = pnp.sp.createBatch(); * pnp.sp.web.inBatch(b).get().then(...); * b.execute().then(...) * ``` */ ODataQueryable.prototype.inBatch = function (batch) { if (this.batch !== null) { throw new AlreadyInBatchException(); } this._batch = batch; return this; }; /** * Gets the currentl url, made absolute based on the availability of the _spPageContextInfo object * */ ODataQueryable.prototype.toUrl = function () { return this._url; }; /** * Executes the currently built request * * @param parser Allows you to specify a parser to handle the result * @param getOptions The options used for this request */ ODataQueryable.prototype.get = function (parser, options) { if (parser === void 0) { parser = new ODataDefaultParser(); } if (options === void 0) { options = {}; } return this.toRequestContext("GET", options, parser, PipelineMethods.default).then(function (context) { return pipe(context); }); }; ODataQueryable.prototype.getAs = function (parser, options) { if (parser === void 0) { parser = new ODataDefaultParser(); } if (options === void 0) { options = {}; } return this.toRequestContext("GET", options, parser, PipelineMethods.default).then(function (context) { return pipe(context); }); }; ODataQueryable.prototype.postCore = function (options, parser) { if (options === void 0) { options = {}; } if (parser === void 0) { parser = new ODataDefaultParser(); } return this.toRequestContext("POST", options, parser, PipelineMethods.default).then(function (context) { return pipe(context); }); }; ODataQueryable.prototype.postAsCore = function (options, parser) { if (options === void 0) { options = {}; } if (parser === void 0) { parser = new ODataDefaultParser(); } return this.toRequestContext("POST", options, parser, PipelineMethods.default).then(function (context) { return pipe(context); }); }; ODataQueryable.prototype.patchCore = function (options, parser) { if (options === void 0) { options = {}; } if (parser === void 0) { parser = new ODataDefaultParser(); } return this.toRequestContext("PATCH", options, parser, PipelineMethods.default).then(function (context) { return pipe(context); }); }; ODataQueryable.prototype.deleteCore = function (options, parser) { if (options === void 0) { options = {}; } if (parser === void 0) { parser = new ODataDefaultParser(); } return this.toRequestContext("DELETE", options, parser, PipelineMethods.default).then(function (context) { return pipe(context); }); }; /** * Blocks a batch call from occuring, MUST be cleared by calling the returned function */ ODataQueryable.prototype.addBatchDependency = function () { if (this._batch !== null) { return this._batch.addDependency(); } return function () { return null; }; }; Object.defineProperty(ODataQueryable.prototype, "hasBatch", { /** * Indicates if the current query has a batch associated * */ get: function () { return __WEBPACK_IMPORTED_MODULE_0__pnp_common__["d" /* Util */].objectDefinedNotNull(this._batch); }, enumerable: true, configurable: true }); Object.defineProperty(ODataQueryable.prototype, "batch", { /** * The batch currently associated with this query or null * */ get: function () { return this.hasBatch ? this._batch : null; }, enumerable: true, configurable: true }); /** * Appends the given string and normalizes "/" chars * * @param pathPart The string to append */ ODataQueryable.prototype.append = function (pathPart) { this._url = __WEBPACK_IMPORTED_MODULE_0__pnp_common__["d" /* Util */].combinePaths(this._url, pathPart); }; Object.defineProperty(ODataQueryable.prototype, "parentUrl", { /** * Gets the parent url used when creating this instance * */ get: function () { return this._parentUrl; }, enumerable: true, configurable: true }); return ODataQueryable; }()); var ODataBatch = /** @class */ (function () { function ODataBatch(_batchId) { if (_batchId === void 0) { _batchId = __WEBPACK_IMPORTED_MODULE_0__pnp_common__["d" /* Util */].getGUID(); } this._batchId = _batchId; this._requests = []; this._dependencies = []; } Object.defineProperty(ODataBatch.prototype, "batchId", { get: function () { return this._batchId; }, enumerable: true, configurable: true }); Object.defineProperty(ODataBatch.prototype, "requests", { /** * The requests contained in this batch */ get: function () { return this._requests; }, enumerable: true, configurable: true }); /** * * @param url Request url * @param method Request method (GET, POST, etc) * @param options Any request options * @param parser The parser used to handle the eventual return from the query */ ODataBatch.prototype.add = function (url, method, options, parser) { var info = { method: method.toUpperCase(), options: options, parser: parser, reject: null, resolve: null, url: url, }; var p = new Promise(function (resolve, reject) { info.resolve = resolve; info.reject = reject; }); this._requests.push(info); return p; }; /** * Adds a dependency insuring that some set of actions will occur before a batch is processed. * MUST be cleared using the returned resolve delegate to allow batches to run */ ODataBatch.prototype.addDependency = function () { var resolver = function () { return void (0); }; var promise = new Promise(function (resolve) { resolver = resolve; }); this._dependencies.push(promise); return resolver; }; /** * Execute the current batch and resolve the associated promises * * @returns A promise which will be resolved once all of the batch's child promises have resolved */ ODataBatch.prototype.execute = function () { var _this = this; // we need to check the dependencies twice due to how different engines handle things. // We can get a second set of promises added after the first set resolve return Promise.all(this._dependencies).then(function () { return Promise.all(_this._dependencies); }).then(function () { return _this.executeImpl(); }); }; return ODataBatch; }()); //# sourceMappingURL=odata.es5.js.map /***/ }), /* 5 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony export (immutable) */ __webpack_exports__["b"] = setup; /* unused harmony export NoGraphClientAvailableException */ /* unused harmony export GraphRuntimeConfigImpl */ /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return GraphRuntimeConfig; }); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_tslib__ = __webpack_require__(0); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__pnp_common__ = __webpack_require__(2); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__pnp_logging__ = __webpack_require__(3); function setup(config) { __WEBPACK_IMPORTED_MODULE_1__pnp_common__["c" /* RuntimeConfig */].extend(config); } var NoGraphClientAvailableException = /** @class */ (function (_super) { __WEBPACK_IMPORTED_MODULE_0_tslib__["b" /* __extends */](NoGraphClientAvailableException, _super); function NoGraphClientAvailableException(msg) { if (msg === void 0) { msg = "There is no Graph Client available, either set one using configuraiton or provide a valid SPFx Context using setup."; } var _this = _super.call(this, msg) || this; _this.name = "NoGraphClientAvailableException"; __WEBPACK_IMPORTED_MODULE_2__pnp_logging__["a" /* Logger */].log({ data: null, level: 3 /* Error */, message: _this.message }); return _this; } return NoGraphClientAvailableException; }(Error)); var GraphRuntimeConfigImpl = /** @class */ (function () { function GraphRuntimeConfigImpl() { } Object.defineProperty(GraphRuntimeConfigImpl.prototype, "headers", { get: function () { var graphPart = __WEBPACK_IMPORTED_MODULE_1__pnp_common__["c" /* RuntimeConfig */].get("graph"); if (typeof graphPart !== "undefined" && typeof graphPart.headers !== "undefined") { return graphPart.headers; } return {}; }, enumerable: true, configurable: true }); Object.defineProperty(GraphRuntimeConfigImpl.prototype, "fetchClientFactory", { get: function () { var graphPart = __WEBPACK_IMPORTED_MODULE_1__pnp_common__["c" /* RuntimeConfig */].get("graph"); // use a configured factory firt if (typeof graphPart !== "undefined" && typeof graphPart.fetchClientFactory !== "undefined") { return graphPart.fetchClientFactory; } // then try and use spfx context if available if (typeof __WEBPACK_IMPORTED_MODULE_1__pnp_common__["c" /* RuntimeConfig */].spfxContext !== "undefined") { return function () { return __WEBPACK_IMPORTED_MODULE_1__pnp_common__["c" /* RuntimeConfig */].spfxContext.graphHttpClient; }; } throw new NoGraphClientAvailableException(); }, enumerable: true, configurable: true }); return GraphRuntimeConfigImpl; }()); var GraphRuntimeConfig = new GraphRuntimeConfigImpl(); //# sourceMappingURL=graphlibconfig.js.map /***/ }), /* 6 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return GraphHttpClient; }); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__pnp_common__ = __webpack_require__(2); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__config_graphlibconfig__ = __webpack_require__(5); // import { APIUrlException } from "../utils/exceptions"; var GraphHttpClient = /** @class */ (function () { function GraphHttpClient() { this._impl = __WEBPACK_IMPORTED_MODULE_1__config_graphlibconfig__["a" /* GraphRuntimeConfig */].fetchClientFactory(); } GraphHttpClient.prototype.fetch = function (url, options) { if (options === void 0) { options = {}; } var headers = new Headers(); // first we add the global headers so they can be overwritten by any passed in locally to this call Object(__WEBPACK_IMPORTED_MODULE_0__pnp_common__["f" /* mergeHeaders */])(headers, __WEBPACK_IMPORTED_MODULE_1__config_graphlibconfig__["a" /* GraphRuntimeConfig */].headers); // second we add the local options so we can overwrite the globals Object(__WEBPACK_IMPORTED_MODULE_0__pnp_common__["f" /* mergeHeaders */])(headers, options.headers); var opts = __WEBPACK_IMPORTED_MODULE_0__pnp_common__["d" /* Util */].extend(options, { headers: headers }); return this.fetchRaw(url, opts); }; GraphHttpClient.prototype.fetchRaw = function (url, options) { var _this = this; if (options === void 0) { options = {}; } // here we need to normalize the headers var rawHeaders = new Headers(); Object(__WEBPACK_IMPORTED_MODULE_0__pnp_common__["f" /* mergeHeaders */])(rawHeaders, options.headers); options = __WEBPACK_IMPORTED_MODULE_0__pnp_common__["d" /* Util */].extend(options, { headers: rawHeaders }); var retry = function (ctx) { _this._impl.fetch(url, {}, options).then(function (response) { return ctx.resolve(response); }).catch(function (response) { // Check if request was throttled - http status code 429 // Check if request failed due to server unavailable - http status code 503 if (response.status !== 429 && response.status !== 503) { ctx.reject(response); } // grab our current delay var delay = ctx.delay; // Increment our counters. ctx.delay *= 2; ctx.attempts++; // If we have exceeded the retry count, reject. if (ctx.retryCount <= ctx.attempts) { ctx.reject(response); } // Set our retry timeout for {delay} milliseconds. setTimeout(__WEBPACK_IMPORTED_MODULE_0__pnp_common__["d" /* Util */].getCtxCallback(_this, retry, ctx), delay); }); }; return new Promise(function (resolve, reject) { var retryContext = { attempts: 0, delay: 100, reject: reject, resolve: resolve, retryCount: 7, }; retry.call(_this, retryContext); }); }; GraphHttpClient.prototype.get = function (url, options) { if (options === void 0) { options = {}; } var opts = __WEBPACK_IMPORTED_MODULE_0__pnp_common__["d" /* Util */].extend(options, { method: "GET" }); return this.fetch(url, opts); }; GraphHttpClient.prototype.post = function (url, options) { if (options === void 0) { options = {}; } var opts = __WEBPACK_IMPORTED_MODULE_0__pnp_common__["d" /* Util */].extend(options, { method: "POST" }); return this.fetch(url, opts); }; GraphHttpClient.prototype.patch = function (url, options) { if (options === void 0) { options = {}; } var opts = __WEBPACK_IMPORTED_MODULE_0__pnp_common__["d" /* Util */].extend(options, { method: "PATCH" }); return this.fetch(url, opts); }; GraphHttpClient.prototype.delete = function (url, options) { if (options === void 0) { options = {}; } var opts = __WEBPACK_IMPORTED_MODULE_0__pnp_common__["d" /* Util */].extend(options, { method: "DELETE" }); return this.fetch(url, opts); }; return GraphHttpClient; }()); //# sourceMappingURL=graphclient.js.map /***/ }), /* 7 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; Object.defineProperty(__webpack_exports__, "__esModule", { value: true }); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__src_graph__ = __webpack_require__(8); /* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "graph", function() { return __WEBPACK_IMPORTED_MODULE_0__src_graph__["g"]; }); /* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "GraphRest", function() { return __WEBPACK_IMPORTED_MODULE_0__src_graph__["f"]; }); /* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "GraphBatch", function() { return __WEBPACK_IMPORTED_MODULE_0__src_graph__["a"]; }); /* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "GraphQueryable", function() { return __WEBPACK_IMPORTED_MODULE_0__src_graph__["b"]; }); /* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "GraphQueryableCollection", function() { return __WEBPACK_IMPORTED_MODULE_0__src_graph__["c"]; }); /* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "GraphQueryableInstance", function() { return __WEBPACK_IMPORTED_MODULE_0__src_graph__["d"]; }); /* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "GraphQueryableSearchableCollection", function() { return __WEBPACK_IMPORTED_MODULE_0__src_graph__["e"]; }); //# sourceMappingURL=index.js.map /***/ }), /* 8 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__rest__ = __webpack_require__(9); /* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "g", function() { return __WEBPACK_IMPORTED_MODULE_0__rest__["b"]; }); /* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "f", function() { return __WEBPACK_IMPORTED_MODULE_0__rest__["a"]; }); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__batch__ = __webpack_require__(18); /* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return __WEBPACK_IMPORTED_MODULE_1__batch__["a"]; }); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__graphqueryable__ = __webpack_require__(1); /* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return __WEBPACK_IMPORTED_MODULE_2__graphqueryable__["a"]; }); /* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return __WEBPACK_IMPORTED_MODULE_2__graphqueryable__["b"]; }); /* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return __WEBPACK_IMPORTED_MODULE_2__graphqueryable__["c"]; }); /* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "e", function() { return __WEBPACK_IMPORTED_MODULE_2__graphqueryable__["d"]; }); //# sourceMappingURL=graph.js.map /***/ }), /* 9 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return GraphRest; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return graph; }); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__v1__ = __webpack_require__(10); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__config_graphlibconfig__ = __webpack_require__(5); var GraphRest = /** @class */ (function () { function GraphRest() { } Object.defineProperty(GraphRest.prototype, "v1", { get: function () { return new __WEBPACK_IMPORTED_MODULE_0__v1__["a" /* V1 */](""); }, enumerable: true, configurable: true }); GraphRest.prototype.setup = function (config) { Object(__WEBPACK_IMPORTED_MODULE_1__config_graphlibconfig__["b" /* setup */])(config); }; return GraphRest; }()); var graph = new GraphRest(); //# sourceMappingURL=rest.js.map /***/ }), /* 10 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return V1; }); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_tslib__ = __webpack_require__(0); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__graphqueryable__ = __webpack_require__(1); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__groups__ = __webpack_require__(11); // import { Me } from "./me"; /** * Root object wrapping v1 functionality for MS Graph * */ var V1 = /** @class */ (function (_super) { __WEBPACK_IMPORTED_MODULE_0_tslib__["b" /* __extends */](V1, _super); /** * Creates a new instance of the V1 class * * @param baseUrl The url or Queryable which forms the parent of this fields collection * @param path Optional additional path */ function V1(baseUrl, path) { if (path === void 0) { path = "v1.0"; } return _super.call(this, baseUrl, path) || this; } Object.defineProperty(V1.prototype, "groups", { get: function () { return new __WEBPACK_IMPORTED_MODULE_2__groups__["a" /* Groups */](this); }, enumerable: true, configurable: true }); return V1; }(__WEBPACK_IMPORTED_MODULE_1__graphqueryable__["a" /* GraphQueryable */])); //# sourceMappingURL=v1.js.map /***/ }), /* 11 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* unused harmony export GroupType */ /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return Groups; }); /* unused harmony export Group */ /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_tslib__ = __webpack_require__(0); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__graphqueryable__ = __webpack_require__(1); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__members__ = __webpack_require__(12); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__pnp_common__ = __webpack_require__(2); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__calendars__ = __webpack_require__(13); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_5__conversations__ = __webpack_require__(14); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_6__plans__ = __webpack_require__(16); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_7__photos__ = __webpack_require__(17); var GroupType; (function (GroupType) { /** * Office 365 (aka unified group) */ GroupType[GroupType["Office365"] = 0] = "Office365"; /** * Dynamic membership */ GroupType[GroupType["Dynamic"] = 1] = "Dynamic"; /** * Security */ GroupType[GroupType["Security"] = 2] = "Security"; })(GroupType || (GroupType = {})); /** * Describes a collection of Field objects * */ var Groups = /** @class */ (function (_super) { __WEBPACK_IMPORTED_MODULE_0_tslib__["b" /* __extends */](Groups, _super); function Groups(baseUrl, path) { if (path === void 0) { path = "groups"; } return _super.call(this, baseUrl, path) || this; } /** * Gets a group from the collection using the specified id * * @param id Id of the group to get from this collection */ Groups.prototype.getById = function (id) { return new Group(this, id); }; /** * Create a new group as specified in the request body. * * @param name Name to display in the address book for the group * @param mailNickname Mail alias for the group * @param groupType Type of group being created * @param additionalProperties A plain object collection of additional properties you want to set on the new group */ Groups.prototype.add = function (name, mailNickname, groupType, additionalProperties) { var _this = this; if (additionalProperties === void 0) { additionalProperties = {}; } var postBody = __WEBPACK_IMPORTED_MODULE_3__pnp_common__["d" /* Util */].extend({ displayName: name, mailEnabled: groupType === GroupType.Office365, mailNickname: mailNickname, securityEnabled: groupType !== GroupType.Office365, }, additionalProperties); // include a group type if required if (groupType !== GroupType.Security) { postBody = __WEBPACK_IMPORTED_MODULE_3__pnp_common__["d" /* Util */].extend(postBody, { groupTypes: [groupType === GroupType.Office365 ? "Unified" : "DynamicMembership"], }); } return this.postCore({ body: JSON.stringify(postBody), }).then(function (r) { return { data: r, group: _this.getById(r.id), }; }); }; return Groups; }(__WEBPACK_IMPORTED_MODULE_1__graphqueryable__["b" /* GraphQueryableCollection */])); /** * Represents a group entity */ var Group = /** @class */ (function (_super) { __WEBPACK_IMPORTED_MODULE_0_tslib__["b" /* __extends */](Group, _super); function Group() { return _super !== null && _super.apply(this, arguments) || this; } Object.defineProperty(Group.prototype, "caldendar", { /** * The calendar associated with this group */ get: function () { return new __WEBPACK_IMPORTED_MODULE_4__calendars__["a" /* Calendar */](this, "calendar"); }, enumerable: true, configurable: true }); Object.defineProperty(Group.prototype, "events", { /** * Retrieve a list of event objects */ get: function () { return new __WEBPACK_IMPORTED_MODULE_4__calendars__["b" /* Events */](this); }, enumerable: true, configurable: true }); Object.defineProperty(Group.prototype, "owners", { /** * Gets the collection of owners for this group */ get: function () { return new __WEBPACK_IMPORTED_MODULE_2__members__["b" /* Owners */](this); }, enumerable: true, configurable: true }); Object.defineProperty(Group.prototype, "plans", { /** * The collection of plans for this group */ get: function () { return new __WEBPACK_IMPORTED_MODULE_6__plans__["a" /* Plans */](this); }, enumerable: true, configurable: true }); Object.defineProperty(Group.prototype, "members", { /** * Gets the collection of members for this group */ get: function () { return new __WEBPACK_IMPORTED_MODULE_2__members__["a" /* Members */](this); }, enumerable: true, configurable: true }); Object.defineProperty(Group.prototype, "conversations", { /** * Gets the conversations collection for this group */ get: function () { return new __WEBPACK_IMPORTED_MODULE_5__conversations__["a" /* Conversations */](this); }, enumerable: true, configurable: true }); Object.defineProperty(Group.prototype, "acceptedSenders", { /** * Gets the collection of accepted senders for this group */ get: function () { return new __WEBPACK_IMPORTED_MODULE_5__conversations__["b" /* Senders */](this, "acceptedsenders"); }, enumerable: true, configurable: true }); Object.defineProperty(Group.prototype, "rejectedSenders", { /** * Gets the collection of rejected senders for this group */ get: function () { return new __WEBPACK_IMPORTED_MODULE_5__conversations__["b" /* Senders */](this, "rejectedsenders"); }, enumerable: true, configurable: true }); Object.defineProperty(Group.prototype, "photo", { /** * The photo associated with the group */ get: function () { return new __WEBPACK_IMPORTED_MODULE_7__photos__["a" /* Photo */](this); }, enumerable: true, configurable: true }); /** * Add the group to the list of the current user's favorite groups. Supported for only Office 365 groups */ Group.prototype.addFavorite = function () { return this.clone(Group, "addFavorite").postCore(); }; /** * Return all the groups that the specified group is a member of. The check is transitive * * @param securityEnabledOnly */ Group.prototype.getMemberGroups = function (securityEnabledOnly) { if (securityEnabledOnly === void 0) { securityEnabledOnly = false; } return this.clone(Group, "getMemberGroups").postCore({ body: JSON.stringify({ securityEnabledOnly: securityEnabledOnly, }), }); }; /** * Deletes this group */ Group.prototype.delete = function () { return this.deleteCore(); }; /** * Update the properties of a group object * * @param properties Set of properties of this group to update */ Group.prototype.update = function (properties) { return this.patchCore({ body: JSON.stringify(properties), }); }; /** * Remove the group from the list of the current user's favorite groups. Supported for only Office 365 groups */ Group.prototype.removeFavorite = function () { return this.clone(Group, "removeFavorite").postCore(); }; /** * Reset the unseenCount of all the posts that the current user has not seen since their last visit */ Group.prototype.resetUnseenCount = function () { return this.clone(Group, "resetUnseenCount").postCore(); }; /** * Calling this method will enable the current user to receive email notifications for this group, * about new posts, events, and files in that group. Supported for only Office 365 groups */ Group.prototype.subscribeByMail = function () { return this.clone(Group, "subscribeByMail").postCore(); }; /** * Calling this method will prevent the current user from receiving email notifications for this group * about new posts, events, and files in that group. Supported for only Office 365 groups */ Group.prototype.unsubscribeByMail = function () { return this.clone(Group, "unsubscribeByMail").postCore(); }; /** * Get the occurrences, exceptions, and single instances of events in a calendar view defined by a time range, from the default calendar of a group * * @param start Start date and time of the time range * @param end End date and time of the time range */ Group.prototype.getCalendarView = function (start, end) { var view = this.clone(Group, "calendarView"); view.query.add("startDateTime", start.toISOString()); view.query.add("endDateTime", end.toISOString()); return view.get(); }; return Group; }(__WEBPACK_IMPORTED_MODULE_1__graphqueryable__["c" /* GraphQueryableInstance */])); //# sourceMappingURL=groups.js.map /***/ }), /* 12 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return Members; }); /* unused harmony export Member */ /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return Owners; }); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_tslib__ = __webpack_require__(0); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__graphqueryable__ = __webpack_require__(1); var Members = /** @class */ (function (_super) { __WEBPACK_IMPORTED_MODULE_0_tslib__["b" /* __extends */](Members, _super); function Members(baseUrl, path) { if (path === void 0) { path = "members"; } return _super.call(this, baseUrl, path) || this; } /** * Use this API to add a member to an Office 365 group, a security group or a mail-enabled security group through * the members navigation property. You can add users or other groups. * Important: You can add only users to Office 365 groups. * * @param id Full @odata.id of the directoryObject, user, or group object you want to add (ex: https://graph.microsoft.com/v1.0/directoryObjects/${id}) */ Members.prototype.add = function (id) { return this.clone(Members, "$ref").postCore({ body: JSON.stringify({ "@odata.id": id, }), }); }; /** * Gets a member of the group by id * * @param id Group member's id */ Members.prototype.getById = function (id) { return new Member(this, id); }; return Members; }(__WEBPACK_IMPORTED_MODULE_1__graphqueryable__["b" /* GraphQueryableCollection */])); var Member = /** @class */ (function (_super) { __WEBPACK_IMPORTED_MODULE_0_tslib__["b" /* __extends */](Member, _super); function Member() { return _super !== null && _super.apply(this, arguments) || this; } return Member; }(__WEBPACK_IMPORTED_MODULE_1__graphqueryable__["c" /* GraphQueryableInstance */])); var Owners = /** @class */ (function (_super) { __WEBPACK_IMPORTED_MODULE_0_tslib__["b" /* __extends */](Owners, _super); function Owners(baseUrl, path) { if (path === void 0) { path = "owners"; } return _super.call(this, baseUrl, path) || this; } return Owners; }(Members)); //# sourceMappingURL=members.js.map /***/ }), /* 13 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* unused harmony export Calendars */ /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return Calendar; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return Events; }); /* unused harmony export Event */ /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_tslib__ = __webpack_require__(0); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__graphqueryable__ = __webpack_require__(1); // import { Attachments } from "./attachments"; var Calendars = /** @class */ (function (_super) { __WEBPACK_IMPORTED_MODULE_0_tslib__["b" /* __extends */](Calendars, _super); function Calendars(baseUrl, path) { if (path === void 0) { path = "calendars"; } return _super.call(this, baseUrl, path) || this; } return Calendars; }(__WEBPACK_IMPORTED_MODULE_1__graphqueryable__["b" /* GraphQueryableCollection */])); var Calendar = /** @class */ (function (_super) { __WEBPACK_IMPORTED_MODULE_0_tslib__["b" /* __extends */](Calendar, _super); function Calendar() { return _super !== null && _super.apply(this, arguments) || this; } Object.defineProperty(Calendar.prototype, "events", { get: function () { return new Events(this); }, enumerable: true, configurable: true }); return Calendar; }(__WEBPACK_IMPORTED_MODULE_1__graphqueryable__["c" /* GraphQueryableInstance */])); var Events = /** @class */ (function (_super) { __WEBPACK_IMPORTED_MODULE_0_tslib__["b" /* __extends */](Events, _super); function Events(baseUrl, path) { if (path === void 0) { path = "events"; } return _super.call(this, baseUrl, path) || this; } Events.prototype.getById = function (id) { return new Event(this, id); }; /** * Adds a new event to the collection * * @param properties The set of properties used to create the event */ Events.prototype.add = function (properties) { var _this = this; return this.postCore({ body: JSON.stringify(properties), }).then(function (r) { return { data: r, event: _this.getById(r.id), }; }); }; return Events; }(__WEBPACK_IMPORTED_MODULE_1__graphqueryable__["b" /* GraphQueryableCollection */])); var Event = /** @class */ (function (_super) { __WEBPACK_IMPORTED_MODULE_0_tslib__["b" /* __extends */](Event, _super); function Event() { return _super !== null && _super.apply(this, arguments) || this; } // TODO:: when supported // /** // * Gets the collection of attachments for this event // */ // public get attachments(): Attachments { // return new Attachments(this); // } /** * Update the properties of an event object * * @param properties Set of properties of this event to update */ Event.prototype.update = function (properties) { return this.patchCore({ body: JSON.stringify(properties), }); }; /** * Deletes this event */ Event.prototype.delete = function () { return this.deleteCore(); }; return Event; }(__WEBPACK_IMPORTED_MODULE_1__graphqueryable__["c" /* GraphQueryableInstance */])); //# sourceMappingURL=calendars.js.map /***/ }), /* 14 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return Conversations; }); /* unused harmony export Threads */ /* unused harmony export Posts */ /* unused harmony export Conversation */ /* unused harmony export Thread */ /* unused harmony export Post */ /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return Senders; }); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_tslib__ = __webpack_require__(0); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__graphqueryable__ = __webpack_require__(1); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__attachments__ = __webpack_require__(15); var Conversations = /** @class */ (function (_super) { __WEBPACK_IMPORTED_MODULE_0_tslib__["b" /* __extends */](Conversations, _super); function Conversations(baseUrl, path) { if (path === void 0) { path = "conversations"; } return _super.call(this, baseUrl, path) || this; } /** * Create a new conversation by including a thread and a post. * * @param properties Properties used to create the new conversation */ Conversations.prototype.add = function (properties) { return this.postCore({ body: JSON.stringify(properties), }); }; /** * Gets a conversation from this collection by id * * @param id Group member's id */ Conversations.prototype.getById = function (id) { return new Conversation(this, id); }; return Conversations; }(__WEBPACK_IMPORTED_MODULE_1__graphqueryable__["b" /* GraphQueryableCollection */])); var Threads = /** @class */ (function (_super) { __WEBPACK_IMPORTED_MODULE_0_tslib__["b" /* __extends */](Threads, _super); function Threads(baseUrl, path) { if (path === void 0) { path = "threads"; } return _super.call(this, baseUrl, path) || this; } /** * Gets a thread from this collection by id * * @param id Group member's id */ Threads.prototype.getById = function (id) { return new Thread(this, id); }; /** * Adds a new thread to this collection * * @param properties properties used to create the new thread * @returns Id of the new thread */ Threads.prototype.add = function (properties) { return this.postCore({ body: JSON.stringify(properties), }); }; return Threads; }(__WEBPACK_IMPORTED_MODULE_1__graphqueryable__["b" /* GraphQueryableCollection */])); var Posts = /** @class */ (function (_super) { __WEBPACK_IMPORTED_MODULE_0_tslib__["b" /* __extends */](Posts, _super); function Posts(baseUrl, path) { if (path === void 0) { path = "posts"; } return _super.call(this, baseUrl, path) || this; } /** * Gets a thread from this collection by id * * @param id Group member's id */ Posts.prototype.getById = function (id) { return new Post(this, id); }; /** * Adds a new thread to this collection * * @param properties properties used to create the new thread * @returns Id of the new thread */ Posts.prototype.add = function (properties) { return this.postCore({ body: JSON.stringify(properties), }); }; return Posts; }(__WEBPACK_IMPORTED_MODULE_1__graphqueryable__["b" /* GraphQueryableCollection */])); var Conversation = /** @class */ (function (_super) { __WEBPACK_IMPORTED_MODULE_0_tslib__["b" /* __extends */](Conversation, _super); function Conversation() { return _super !== null && _super.apply(this, arguments) || this; } Object.defineProperty(Conversation.prototype, "threads", { /** * Get all the threads in a group conversation. */ get: function () { return new Threads(this); }, enumerable: true, configurable: true }); /** * Updates this conversation */ Conversation.prototype.update = function (properties) { return this.patchCore({ body: JSON.stringify(properties), }); }; /** * Deletes this member from the group */ Conversation.prototype.delete = function () { return this.deleteCore(); }; return Conversation; }(__WEBPACK_IMPORTED_MODULE_1__graphqueryable__["c" /* GraphQueryableInstance */])); var Thread = /** @class */ (function (_super) { __WEBPACK_IMPORTED_MODULE_0_tslib__["b" /* __extends */](Thread, _super); function Thread() { return _super !== null && _super.apply(this, arguments) || this; } Object.defineProperty(Thread.prototype, "posts", { /** * Get all the threads in a group conversation. */ get: function () { return new Posts(this); }, enumerable: true, configurable: true }); /** * Reply to a thread in a group conversation and add a new post to it * * @param post Contents of the post */ Thread.prototype.reply = function (post) { return this.clone(Thread, "reply").postCore({ body: JSON.stringify({ post: post, }), }); }; /** * Deletes this member from the group */ Thread.prototype.delete = function () { return this.deleteCore(); }; return Thread; }(__WEBPACK_IMPORTED_MODULE_1__graphqueryable__["c" /* GraphQueryableInstance */])); var Post = /** @class */ (function (_super) { __WEBPACK_IMPORTED_MODULE_0_tslib__["b" /* __extends */](Post, _super); function Post() { return _super !== null && _super.apply(this, arguments) || this; } Object.defineProperty(Post.prototype, "attachments", { get: function () { return new __WEBPACK_IMPORTED_MODULE_2__attachments__["a" /* Attachments */](this); }, enumerable: true, configurable: true }); /** * Deletes this post */ Post.prototype.delete = function () { return this.deleteCore(); }; /** * Forward a post to a recipient */ Post.prototype.forward = function (info) { return this.clone(Post, "forward").postCore({ body: JSON.stringify(info), }); }; /** * Reply to a thread in a group conversation and add a new post to it * * @param post Contents of the post */ Post.prototype.reply = function (post) { return this.clone(Post, "reply").postCore({ body: JSON.stringify({ post: post, }), }); }; return Post; }(__WEBPACK_IMPORTED_MODULE_1__graphqueryable__["c" /* GraphQueryableInstance */])); var Senders = /** @class */ (function (_super) { __WEBPACK_IMPORTED_MODULE_0_tslib__["b" /* __extends */](Senders, _super); function Senders(baseUrl, path) { return _super.call(this, baseUrl, path) || this; } /** * Add a new user or group to this senders collection * @param id The full @odata.id value to add (ex: https://graph.microsoft.com/v1.0/users/user@contoso.com) */ Senders.prototype.add = function (id) { return this.clone(Senders, "$ref").postCore({ body: JSON.stringify({ "@odata.id": id, }), }); }; /** * Removes the entity from the collection * * @param id The full @odata.id value to remove (ex: https://graph.microsoft.com/v1.0/users/user@contoso.com) */ Senders.prototype.remove = function (id) { var remover = this.clone(Senders, "$ref"); remover.query.add("$id", id); return remover.deleteCore(); }; return Senders; }(__WEBPACK_IMPORTED_MODULE_1__graphqueryable__["b" /* GraphQueryableCollection */])); //# sourceMappingURL=conversations.js.map /***/ }), /* 15 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return Attachments; }); /* unused harmony export Attachment */ /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_tslib__ = __webpack_require__(0); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__graphqueryable__ = __webpack_require__(1); var Attachments = /** @class */ (function (_super) { __WEBPACK_IMPORTED_MODULE_0_tslib__["b" /* __extends */](Attachments, _super); function Attachments(baseUrl, path) { if (path === void 0) { path = "attachments"; } return _super.call(this, baseUrl, path) || this; } /** * Gets a member of the group by id * * @param id Attachment id */ Attachments.prototype.getById = function (id) { return new Attachment(this, id); }; /** * Add attachment to this collection * * @param name Name given to the attachment file * @param bytes File content */ Attachments.prototype.addFile = function (name, bytes) { return this.postCore({ body: JSON.stringify({ "@odata.type": "#microsoft.graph.fileAttachment", contentBytes: bytes, name: name, }), }); }; return Attachments; }(__WEBPACK_IMPORTED_MODULE_1__graphqueryable__["b" /* GraphQueryableCollection */])); var Attachment = /** @class */ (function (_super) { __WEBPACK_IMPORTED_MODULE_0_tslib__["b" /* __extends */](Attachment, _super); function Attachment() { return _super !== null && _super.apply(this, arguments) || this; } return Attachment; }(__WEBPACK_IMPORTED_MODULE_1__graphqueryable__["c" /* GraphQueryableInstance */])); //# sourceMappingURL=attachments.js.map /***/ }), /* 16 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return Plans; }); /* unused harmony export Plan */ /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_tslib__ = __webpack_require__(0); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__graphqueryable__ = __webpack_require__(1); var Plans = /** @class */ (function (_super) { __WEBPACK_IMPORTED_MODULE_0_tslib__["b" /* __extends */](Plans, _super); function Plans(baseUrl, path) { if (path === void 0) { path = "planner/plans"; } return _super.call(this, baseUrl, path) || this; } /** * Gets a plan from this collection by id * * @param id Plan's id */ Plans.prototype.getById = function (id) { return new Plan(this, id); }; return Plans; }(__WEBPACK_IMPORTED_MODULE_1__graphqueryable__["b" /* GraphQueryableCollection */])); var Plan = /** @class */ (function (_super) { __WEBPACK_IMPORTED_MODULE_0_tslib__["b" /* __extends */](Plan, _super); function Plan() { return _super !== null && _super.apply(this, arguments) || this; } return Plan; }(__WEBPACK_IMPORTED_MODULE_1__graphqueryable__["c" /* GraphQueryableInstance */])); //# sourceMappingURL=plans.js.map /***/ }), /* 17 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return Photo; }); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_tslib__ = __webpack_require__(0); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__graphqueryable__ = __webpack_require__(1); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__pnp_odata__ = __webpack_require__(4); var Photo = /** @class */ (function (_super) { __WEBPACK_IMPORTED_MODULE_0_tslib__["b" /* __extends */](Photo, _super); function Photo(baseUrl, path) { if (path === void 0) { path = "photo"; } return _super.call(this, baseUrl, path) || this; } /** * Gets the image bytes as a blob (browser) */ Photo.prototype.getBlob = function () { return this.clone(Photo, "$value", false).get(new __WEBPACK_IMPORTED_MODULE_2__pnp_odata__["a" /* BlobFileParser */]()); }; /** * Gets the image file byets as a Buffer (node.js) */ Photo.prototype.getBuffer = function () { return this.clone(Photo, "$value", false).get(new __WEBPACK_IMPORTED_MODULE_2__pnp_odata__["b" /* BufferFileParser */]()); }; /** * Sets the file bytes * * @param content Image file contents, max 4 MB */ Photo.prototype.setContent = function (content) { return this.clone(Photo, "$value", false).patchCore({ body: content, }); }; return Photo; }(__WEBPACK_IMPORTED_MODULE_1__graphqueryable__["c" /* GraphQueryableInstance */])); //# sourceMappingURL=photos.js.map /***/ }), /* 18 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* unused harmony export GraphBatchParseException */ /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return GraphBatch; }); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_tslib__ = __webpack_require__(0); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__pnp_odata__ = __webpack_require__(4); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__pnp_logging__ = __webpack_require__(3); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__pnp_common__ = __webpack_require__(2); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__config_graphlibconfig__ = __webpack_require__(5); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_5__net_graphclient__ = __webpack_require__(6); var GraphBatchParseException = /** @class */ (function (_super) { __WEBPACK_IMPORTED_MODULE_0_tslib__["b" /* __extends */](GraphBatchParseException, _super); function GraphBatchParseException(msg) { var _this = _super.call(this, msg) || this; _this.name = "GraphBatchParseException"; __WEBPACK_IMPORTED_MODULE_2__pnp_logging__["a" /* Logger */].log({ data: {}, level: 3 /* Error */, message: "[" + _this.name + "]::" + _this.message }); return _this; } return GraphBatchParseException; }(Error)); var GraphBatch = /** @class */ (function (_super) { __WEBPACK_IMPORTED_MODULE_0_tslib__["b" /* __extends */](GraphBatch, _super); function GraphBatch(batchUrl) { if (batchUrl === void 0) { batchUrl = "https://graph.microsoft.com/beta/$batch"; } var _this = _super.call(this) || this; _this.batchUrl = batchUrl; return _this; } GraphBatch.prototype.executeImpl = function () { var _this = this; __WEBPACK_IMPORTED_MODULE_2__pnp_logging__["a" /* Logger */].write("[" + this.batchId + "] (" + (new Date()).getTime() + ") Executing batch with " + this.requests.length + " requests.", 1 /* Info */); var client = new __WEBPACK_IMPORTED_MODULE_5__net_graphclient__["a" /* GraphHttpClient */](); var batchRequest = { requests: this.formatRequests(), }; var batchOptions = { "body": JSON.stringify(batchRequest), "headers": { "Accept": "application/json", "Content-Type": "application/json", }, "method": "POST", }; __WEBPACK_IMPORTED_MODULE_2__pnp_logging__["a" /* Logger */].write("[" + this.batchId + "] (" + (new Date()).getTime() + ") Sending batch request.", 1 /* Info */); var nextLinkFlag = false; return client.fetch(this.batchUrl, batchOptions) .then(function (r) { return r.json(); }) .then(this._parseResponse) .then(function (parsedResponse) { __WEBPACK_IMPORTED_MODULE_2__pnp_logging__["a" /* Logger */].write("[" + _this.batchId + "] (" + (new Date()).getTime() + ") Resolving batched requests.", 1 /* Info */); return parsedResponse.responses.reduce(function (chain, response, index) { var request = _this.requests[index]; if (__WEBPACK_IMPORTED_MODULE_3__pnp_common__["d" /* Util */].objectDefinedNotNull(request)) { __WEBPACK_IMPORTED_MODULE_2__pnp_logging__["a" /* Logger */].write("[" + _this.batchId + "] (" + (new Date()).getTime() + ") Resolving batched request " + request.method + " " + request.url + ".", 0 /* Verbose */); return chain.then(function (_) { return request.parser.parse(response).then(request.resolve).catch(request.reject); }); } else { // do we have a next url? if no this is an error if (!__WEBPACK_IMPORTED_MODULE_3__pnp_common__["d" /* Util */].stringIsNullOrEmpty(parsedResponse.nextLink)) { throw new GraphBatchParseException("Could not properly parse responses to match requests in batch."); } nextLinkFlag = true; // keep the chain moving, but don't add anything for this request yet // here we need to process the next link - so what do we do? // need to append a .then() // TODO:: return chain; } }, Promise.resolve()); }); }; GraphBatch.prototype.formatRequests = function () { return this.requests.map(function (reqInfo, index) { var requestFragment = { id: "" + ++index, method: reqInfo.method, url: reqInfo.url, }; var headers = {}; // merge global config headers if (typeof __WEBPACK_IMPORTED_MODULE_4__config_graphlibconfig__["a" /* GraphRuntimeConfig */].headers !== "undefined" && __WEBPACK_IMPORTED_MODULE_4__config_graphlibconfig__["a" /* GraphRuntimeConfig */].headers !== null) { headers = __WEBPACK_IMPORTED_MODULE_3__pnp_common__["d" /* Util */].extend(headers, __WEBPACK_IMPORTED_MODULE_4__config_graphlibconfig__["a" /* GraphRuntimeConfig */].headers); } if (typeof reqInfo.options !== "undefined") { // merge per request headers if (typeof reqInfo.options.headers !== "undefined" && reqInfo.options.headers !== null) { headers = __WEBPACK_IMPORTED_MODULE_3__pnp_common__["d" /* Util */].extend(headers, reqInfo.options.headers); } // add a request body if (typeof reqInfo.options.body !== "undefined" && reqInfo.options.body !== null) { requestFragment = __WEBPACK_IMPORTED_MODULE_3__pnp_common__["d" /* Util */].extend(requestFragment, { body: reqInfo.options.body, }); } } requestFragment = __WEBPACK_IMPORTED_MODULE_3__pnp_common__["d" /* Util */].extend(requestFragment, { headers: headers, }); return requestFragment; }); }; GraphBatch.prototype._parseResponse = function (graphResponse) { var _this = this; return new Promise(function (resolve) { var parsedResponses = new Array(_this.requests.length).fill(null); for (var i = 0; i < graphResponse.responses.length; ++i) { var response = graphResponse.responses[i]; // we create the request id by adding 1 to the index, so we place the response by subtracting one to match // the array of requests and make it easier to map them by index var responseId = parseInt(response.id, 10) - 1; if (response.status === 204) { parsedResponses[responseId] = new Response(); } else { parsedResponses[responseId] = new Response(null, { headers: response.headers, status: response.status, }); } } resolve({ nextLink: graphResponse.nextLink, responses: parsedResponses, }); }); }; __WEBPACK_IMPORTED_MODULE_0_tslib__["a" /* __decorate */]([ Object(__WEBPACK_IMPORTED_MODULE_3__pnp_common__["e" /* beta */])("Graph batching functionality is in beta.") ], GraphBatch.prototype, "executeImpl", null); return GraphBatch; }(__WEBPACK_IMPORTED_MODULE_1__pnp_odata__["c" /* ODataBatch */])); //# sourceMappingURL=batch.js.map /***/ }) /******/ ]); }); //# sourceMappingURL=graph.es5.umd.bundle.js.map
var ORM = require('../../'); var helper = require('../support/spec_helper'); var should = require('should'); var async = require('async'); var common = require('../common'); var _ = require('lodash'); describe("hasOne", function () { var db = null; var Person = null; var Pet = null; var setup = function () { return function (done) { Person = db.define('person', { name: String }); Pet = db.define('pet', { name: String }); Person.hasOne('pet', Pet, { reverse: 'owners', field: 'pet_id' }); return helper.dropSync([Person, Pet], function () { // Running in series because in-memory sqlite encounters problems async.series([ Person.create.bind(Person, { name: "John Doe" }), Person.create.bind(Person, { name: "Jane Doe" }), Pet.create.bind(Pet, { name: "Deco" }), Pet.create.bind(Pet, { name: "Fido" }) ], done); }); }; }; before(function (done) { helper.connect(function (connection) { db = connection; done(); }); }); describe("reverse", function () { removeHookRun = false; before(setup({ hooks: { beforeRemove: function () { removeHookRun = true; } } })); it("should create methods in both models", function (done) { var person = Person(1); var pet = Pet(1); person.getPet.should.be.a("function"); person.setPet.should.be.a("function"); person.removePet.should.be.a("function"); person.hasPet.should.be.a("function"); pet.getOwners.should.be.a("function"); pet.setOwners.should.be.a("function"); pet.hasOwners.should.be.a("function"); return done(); }); describe(".getAccessor()", function () { it("should work", function (done) { Person.find({ name: "John Doe" }).first(function (err, John) { Pet.find({ name: "Deco" }).first(function (err, Deco) { Deco.hasOwners(function (err, has_owner) { should.not.exist(err); has_owner.should.be.false; Deco.setOwners(John, function (err) { should.not.exist(err); Deco.getOwners(function (err, JohnCopy) { should.not.exist(err); should(Array.isArray(JohnCopy)); John.should.eql(JohnCopy[0]); return done(); }); }); }); }); }); }); describe("Chain", function () { before(function (done) { var petParams = [ { name: "Hippo" }, { name: "Finch", owners: [{ name: "Harold" }, { name: "Hagar" }] }, { name: "Fox", owners: [{ name: "Nelly" }, { name: "Narnia" }] } ]; Pet.create(petParams, function (err, pets) { should.not.exist(err); should.equal(pets.length, 3); Person.find({ name: ["Harold", "Hagar", "Nelly", "Narnia"] }, function (err, people) { should.not.exist(err); should.exist(people); should.equal(people.length, 4); done(); }); }); }); it("should be returned if no callback is passed", function (done) { Pet.one(function (err, pet) { should.not.exist(err); should.exist(pet); var chain = pet.getOwners(); should.equal(typeof chain, 'object'); should.equal(typeof chain.run, 'function'); done() }); }); it(".remove() should not call hooks", function (done) { Pet.one({ name: "Finch" }, function (err, pet) { should.not.exist(err); should.exist(pet); should.equal(removeHookRun, false); pet.getOwners().remove(function (err) { should.not.exist(err); should.equal(removeHookRun, false); Person.find({ name: "Harold" }, function (err, items) { should.not.exist(err); should.equal(items.length, 0); done(); }); }); }); }); }); }); it("should be able to set an array of people as the owner", function (done) { Person.find({ name: ["John Doe", "Jane Doe"] }, function (err, owners) { Pet.find({ name: "Fido" }).first(function (err, Fido) { Fido.hasOwners(function (err, has_owner) { should.not.exist(err); has_owner.should.be.false; Fido.setOwners(owners, function (err) { should.not.exist(err); Fido.getOwners(function (err, ownersCopy) { should.not.exist(err); should(Array.isArray(owners)); owners.length.should.equal(2); if (owners[0] == ownersCopy[0]) { owners[0].should.eql(ownersCopy[0]); owners[1].should.eql(ownersCopy[1]); } else { owners[0].should.eql(ownersCopy[1]); owners[1].should.eql(ownersCopy[0]); } return done(); }); }); }); }); }); }); // broken in mongo if (common.protocol() != "mongodb") { describe("findBy()", function () { before(setup()); before(function (done) { Person.one({ name: "Jane Doe" }, function (err, jane) { Pet.one({ name: "Deco" }, function (err, deco) { deco.setOwners(jane, function (err) { should.not.exist(err); done(); }); }); }); }); it("should throw if no conditions passed", function (done) { (function () { Pet.findByOwners(function () {}); }).should.throw(); return done(); }); it("should lookup reverse Model based on associated model properties", function (done) { Pet.findByOwners({ name: "Jane Doe" }, function (err, pets) { should.not.exist(err); should.equal(Array.isArray(pets), true); // This often fails for sqlite on travis if (common.isTravis() && common.protocol() != 'sqlite') { should.equal(pets.length, 1); should.equal(pets[0].name, 'Deco'); } return done(); }); }); it("should return a ChainFind if no callback passed", function (done) { var ChainFind = Pet.findByOwners({ name: "John Doe" }); ChainFind.run.should.be.a("function"); return done(); }); }); } }); describe("reverse find", function () { it("should be able to find given an association id", function (done) { common.retry(setup(), function (done) { Person.find({ name: "John Doe" }).first(function (err, John) { should.not.exist(err); should.exist(John); Pet.find({ name: "Deco" }).first(function (err, Deco) { should.not.exist(err); should.exist(Deco); Deco.hasOwners(function (err, has_owner) { should.not.exist(err); has_owner.should.be.false; Deco.setOwners(John, function (err) { should.not.exist(err); Person.find({ pet_id: Deco[Pet.id[0]] }).first(function (err, owner) { should.not.exist(err); should.exist(owner); should.equal(owner.name, John.name); done(); }); }); }); }); }); }, 3, done); }); it("should be able to find given an association instance", function (done) { common.retry(setup(), function (done) { Person.find({ name: "John Doe" }).first(function (err, John) { should.not.exist(err); should.exist(John); Pet.find({ name: "Deco" }).first(function (err, Deco) { should.not.exist(err); should.exist(Deco); Deco.hasOwners(function (err, has_owner) { should.not.exist(err); has_owner.should.be.false; Deco.setOwners(John, function (err) { should.not.exist(err); Person.find({ pet: Deco }).first(function (err, owner) { should.not.exist(err); should.exist(owner); should.equal(owner.name, John.name); done(); }); }); }); }); }); }, 3, done); }); it("should be able to find given a number of association instances with a single primary key", function (done) { common.retry(setup(), function (done) { Person.find({ name: "John Doe" }).first(function (err, John) { should.not.exist(err); should.exist(John); Pet.all(function (err, pets) { should.not.exist(err); should.exist(pets); should.equal(pets.length, 2); pets[0].hasOwners(function (err, has_owner) { should.not.exist(err); has_owner.should.be.false; pets[0].setOwners(John, function (err) { should.not.exist(err); Person.find({ pet: pets }, function (err, owners) { should.not.exist(err); should.exist(owners); owners.length.should.equal(1); should.equal(owners[0].name, John.name); done(); }); }); }); }); }); }, 3, done); }); }); });
/** * Client showdown integration tests * * Ensures that the final output from showdown + client extensions is as expected */ /*globals describe, it */ /*jshint expr:true*/ var should = require('should'), // Stuff we are testing Showdown = require('showdown'), ghostgfm = require('../../shared/lib/showdown/extensions/ghostgfm'), ghostimagepreview = require('../../shared/lib/showdown/extensions/ghostimagepreview'), converter = new Showdown.converter({extensions: [ghostimagepreview, ghostgfm]}); // To stop jshint complaining should.equal(true, true); describe('Showdown client side converter', function () { /*jslint regexp: true */ it('should replace showdown strike through with html', function () { var testPhrase = {input: '~~foo_bar~~', output: /^<p><del>foo_bar<\/del><\/p>$/}, processedMarkup = converter.makeHtml(testPhrase.input); // The image is the entire markup, so the image box should be too processedMarkup.should.match(testPhrase.output); }); it('should honour escaped tildes', function () { var testPhrase = {input: '\\~\\~foo_bar\\~\\~', output: /^<p>~~foo_bar~~<\/p>$/}, processedMarkup = converter.makeHtml(testPhrase.input); // The image is the entire markup, so the image box should be too processedMarkup.should.match(testPhrase.output); }); it('should not touch single underscores inside words', function () { var testPhrase = {input: 'foo_bar', output: /^<p>foo_bar<\/p>$/}, processedMarkup = converter.makeHtml(testPhrase.input); processedMarkup.should.match(testPhrase.output); }); // Currently failing - fixing this causes other issues // it('should not create italic words between lines', function () { // var testPhrase = {input: 'foo_bar\nbar_foo', output: /^<p>foo_bar <br \/>\nbar_foo<\/p>$/}, // processedMarkup = converter.makeHtml(testPhrase.input); // // processedMarkup.should.match(testPhrase.output); // }); it('should not touch underscores in code blocks', function () { var testPhrase = {input: ' foo_bar_baz', output: /^<pre><code>foo_bar_baz\n<\/code><\/pre>$/}, processedMarkup = converter.makeHtml(testPhrase.input); processedMarkup.should.match(testPhrase.output); }); it('should not touch underscores in pre blocks', function () { var testPhrases = [ {input: '<pre>\nfoo_bar_baz\n</pre>', output: /^<pre>\nfoo_bar_baz\n<\/pre>$/}, {input: '<pre>foo_bar_baz</pre>', output: /^<pre>foo_bar_baz<\/pre>$/} ], processedMarkup; testPhrases.forEach(function (testPhrase) { processedMarkup = converter.makeHtml(testPhrase.input); processedMarkup.should.match(testPhrase.output); }); }); it('should not escape double underscores at the beginning of a line', function () { var testPhrases = [ {input: '\n__test__\n', output: /^<p><strong>test<\/strong><\/p>$/} ], processedMarkup; testPhrases.forEach(function (testPhrase) { processedMarkup = converter.makeHtml(testPhrase.input); processedMarkup.should.match(testPhrase.output); }); }); it('should not treat pre blocks with pre-text differently', function () { var testPhrases = [ { input: '<pre>\nthis is `a\\_test` and this\\_too and finally_this_is\n</pre>', output: /^<pre>\nthis is `a\\_test` and this\\_too and finally_this_is\n<\/pre>$/ }, { input: 'hmm<pre>\nthis is `a\\_test` and this\\_too and finally_this_is\n</pre>', output: /^<p>hmm<\/p>\n\n<pre>\nthis is `a\\_test` and this\\_too and finally_this_is\n<\/pre>$/ } ], processedMarkup; testPhrases.forEach(function (testPhrase) { processedMarkup = converter.makeHtml(testPhrase.input); processedMarkup.should.match(testPhrase.output); }); }); it('should escape two or more underscores inside words', function () { var testPhrases = [ {input: 'foo_bar_baz', output: /^<p>foo_bar_baz<\/p>$/}, {input: 'foo_bar_baz_bat', output: /^<p>foo_bar_baz_bat<\/p>$/}, {input: 'foo_bar_baz_bat_boo', output: /^<p>foo_bar_baz_bat_boo<\/p>$/}, {input: 'FOO_BAR', output: /^<p>FOO_BAR<\/p>$/}, {input: 'FOO_BAR_BAZ', output: /^<p>FOO_BAR_BAZ<\/p>$/}, {input: 'FOO_bar_BAZ_bat', output: /^<p>FOO_bar_BAZ_bat<\/p>$/}, {input: 'FOO_bar_BAZ_bat_BOO', output: /^<p>FOO_bar_BAZ_bat_BOO<\/p>$/}, {input: 'foo_BAR_baz_BAT_boo', output: /^<p>foo_BAR_baz_BAT_boo<\/p>$/} ], processedMarkup; testPhrases.forEach(function (testPhrase) { processedMarkup = converter.makeHtml(testPhrase.input); processedMarkup.should.match(testPhrase.output); }); }); it('should turn newlines into br tags in simple cases', function () { var testPhrases = [ {input: 'fizz\nbuzz', output: /^<p>fizz <br \/>\nbuzz<\/p>$/}, {input: 'Hello world\nIt is a fine day', output: /^<p>Hello world <br \/>\nIt is a fine day<\/p>$/}, {input: '\'first\nsecond', output: /^<p>\'first <br \/>\nsecond<\/p>$/}, {input: '\'first\nsecond', output: /^<p>\'first <br \/>\nsecond<\/p>$/} ], processedMarkup; testPhrases.forEach(function (testPhrase) { processedMarkup = converter.makeHtml(testPhrase.input); processedMarkup.should.match(testPhrase.output); }); }); it('should convert newlines in all groups', function () { var testPhrases = [ { input: 'ruby\npython\nerlang', output: /^<p>ruby <br \/>\npython <br \/>\nerlang<\/p>$/ }, { input: 'Hello world\nIt is a fine day\nout', output: /^<p>Hello world <br \/>\nIt is a fine day <br \/>\nout<\/p>$/ } ], processedMarkup; testPhrases.forEach(function (testPhrase) { processedMarkup = converter.makeHtml(testPhrase.input); processedMarkup.should.match(testPhrase.output); }); }); it('should convert newlines in even long groups', function () { var testPhrases = [ { input: 'ruby\npython\nerlang\ngo', output: /^<p>ruby <br \/>\npython <br \/>\nerlang <br \/>\ngo<\/p>$/ }, { input: 'Hello world\nIt is a fine day\noutside\nthe window', output: /^<p>Hello world <br \/>\nIt is a fine day <br \/>\noutside <br \/>\nthe window<\/p>$/ } ], processedMarkup; testPhrases.forEach(function (testPhrase) { processedMarkup = converter.makeHtml(testPhrase.input); processedMarkup.should.match(testPhrase.output); }); }); it('should not convert newlines in lists', function () { var testPhrases = [ { input: '#fizz\n# buzz\n### baz', output: /^<h1 id="fizz">fizz<\/h1>\n\n<h1 id="buzz">buzz<\/h1>\n\n<h3 id="baz">baz<\/h3>$/ }, { input: '* foo\n* bar', output: /^<ul>\n<li>foo<\/li>\n<li>bar<\/li>\n<\/ul>$/ } ], processedMarkup; testPhrases.forEach(function (testPhrase) { processedMarkup = converter.makeHtml(testPhrase.input); processedMarkup.should.match(testPhrase.output); }); }); it('should auto-link URL in text with markdown syntax', function () { var testPhrases = [ { input: 'http://google.co.uk', output: /^<p><a href=\'http:\/\/google.co.uk\'>http:\/\/google.co.uk<\/a><\/p>$/ }, { input: 'https://atest.com/fizz/buzz?baz=fizzbuzz', output: /^<p><a href=\'https:\/\/atest.com\/fizz\/buzz\?baz=fizzbuzz\'>https:\/\/atest.com\/fizz\/buzz\?baz=fizzbuzz<\/a><\/p>$/ }, { input: 'Some [ text (http://www.google.co.uk) some other text', output: /^<p>Some \[ text \(<a href=\'http:\/\/www.google.co.uk\'>http:\/\/www.google.co.uk<\/a>\) some other text<\/p>$/ }, { input: '>http://google.co.uk', output: /^<blockquote>\n <p><a href=\'http:\/\/google.co.uk\'>http:\/\/google.co.uk<\/a><\/p>\n<\/blockquote>$/ }, { input: '> http://google.co.uk', output: /^<blockquote>\n <p><a href=\'http:\/\/google.co.uk\'>http:\/\/google.co.uk<\/a><\/p>\n<\/blockquote>$/ }, { input: '<>>> http://google.co.uk', output: /^<p>&lt;>>> <a href=\'http:\/\/google.co.uk\'>http:\/\/google.co.uk<\/a><\/p>$/ }, { input: '<strong>http://google.co.uk', output: /^<p><strong><a href=\'http:\/\/google.co.uk\'>http:\/\/google.co.uk<\/a><\/p>$/ }, { input: '# http://google.co.uk', output: /^<h1 id="httpgooglecouk"><a href=\'http:\/\/google.co.uk\'>http:\/\/google.co.uk<\/a><\/h1>$/ }, { input: '* http://google.co.uk', output: /^<ul>\n<li><a href=\'http:\/\/google.co.uk\'>http:\/\/google.co.uk<\/a><\/li>\n<\/ul>$/ } ], processedMarkup; testPhrases.forEach(function (testPhrase) { processedMarkup = converter.makeHtml(testPhrase.input); processedMarkup.should.match(testPhrase.output); }); }); it('should convert reference format URL', function () { var testPhrases = [ { input: '[Google][1]\n\n[1]: http://google.co.uk', output: /^<p><a href="http:\/\/google.co.uk">Google<\/a><\/p>$/ }, { input: '[Google][1]\n\n[1]: http://google.co.uk \"some text\"', output: /^<p><a href="http:\/\/google.co.uk" title="some text">Google<\/a><\/p>$/ }, { input: '[http://google.co.uk]: http://google.co.uk\n\n[Hello][http://google.co.uk]', output: /^<p><a href="http:\/\/google.co.uk">Hello<\/a><\/p>$/ } ], processedMarkup; testPhrases.forEach(function (testPhrase) { processedMarkup = converter.makeHtml(testPhrase.input); processedMarkup.should.match(testPhrase.output); }); }); /* No ref-style for now it('should convert reference format image', function () { var testPhrases = [ { input: '![Google][1]\n\n[1]: http://dsurl.stuff/something.jpg', output: /^<section.*?<img.*?src="http:\/\/dsurl.stuff\/something.jpg"\/>.*?<\/section>$/, }, { input: '![Google][1]\n\n[1]: http://dsurl.stuff/something.jpg \"some text\"', output: /^<section.*?<img.*?src="http:\/\/dsurl.stuff\/something.jpg"\/>.*?<\/section>$/ }, { input: '[http://www.google.co.uk]: http://www.google.co.uk\n\n![Hello][http://www.google.co.uk]', output: /^<section.*?<img.*?src="http:\/\/www.google.co.uk"\/>.*?<\/section>$/ } ], processedMarkup; testPhrases.forEach(function (testPhrase) { processedMarkup = converter.makeHtml(testPhrase.input); processedMarkup.should.match(testPhrase.output); }); }); */ it('should NOT auto-link URL in HTML', function () { var testPhrases = [ { input: '<img src="http://placekitten.com/50">', output: /^<p><img src=\"http:\/\/placekitten.com\/50\"><\/p>$/ }, { input: '<img src="http://placekitten.com/50" />', output: /^<p><img src=\"http:\/\/placekitten.com\/50\" \/><\/p>$/ }, { input: '<script type="text/javascript" src="http://google.co.uk"></script>', output: /^<script type=\"text\/javascript\" src=\"http:\/\/google.co.uk\"><\/script>$/ }, { input: '<a href="http://facebook.com">http://google.co.uk</a>', output: /^<p><a href=\"http:\/\/facebook.com\">http:\/\/google.co.uk<\/a><\/p>$/ }, { input: '<a href="http://facebook.com">test</a> http://google.co.uk', output: /^<p><a href=\"http:\/\/facebook.com\">test<\/a> <a href=\'http:\/\/google.co.uk\'>http:\/\/google.co.uk<\/a><\/p>$/ } ], processedMarkup; testPhrases.forEach(function (testPhrase) { processedMarkup = converter.makeHtml(testPhrase.input); processedMarkup.should.match(testPhrase.output); }); }); it('should NOT escape underscore inside of code/pre blocks', function () { var testPhrase = { input: '```\n_____\n```', output: /^<pre><code>_____ \n<\/code><\/pre>$/ }, processedMarkup; processedMarkup = converter.makeHtml(testPhrase.input); processedMarkup.should.match(testPhrase.output); }); it('should NOT auto-link URLS inside of code/pre blocks', function () { var testPhrases = [ { input: '```\nurl: http://google.co.uk\n```', output: /^<pre><code>url: http:\/\/google.co.uk \n<\/code><\/pre>$/ }, { input: '`url: http://google.co.uk`', output: /^<p><code>url: http:\/\/google.co.uk<\/code><\/p>$/ }, { input: 'Hello type some `url: http://google.co.uk` stuff', output: /^<p>Hello type some <code>url: http:\/\/google.co.uk<\/code> stuff<\/p>$/ } ], processedMarkup; testPhrases.forEach(function (testPhrase) { processedMarkup = converter.makeHtml(testPhrase.input); processedMarkup.should.match(testPhrase.output); }); }); it('should not display anything for reference URL', function () { var testPhrases = [ { input: '[1]: http://www.google.co.uk', output: /^$/ }, { input: '[http://www.google.co.uk]: http://www.google.co.uk', output: /^$/ }, { input: '[1]: http://dsurl.stuff/something.jpg', output: /^$/ }, { input: '[1]:http://www.google.co.uk', output: /^$/ }, { input: ' [1]:http://www.google.co.uk', output: /^$/ }, { input: '', output: /^$/ } ], processedMarkup; testPhrases.forEach(function (testPhrase) { processedMarkup = converter.makeHtml(testPhrase.input); processedMarkup.should.match(testPhrase.output); }); }); it('should show placeholder for image markdown', function () { var testPhrases = [ {input: '![image and another,/ image](http://dsurl stuff)', output: /^<section.*?section>\n*$/}, {input: '![image and another,/ image]', output: /^<section.*?section>\n*$/}, {input: '![]()', output: /^<section.*?section>\n*$/}, {input: '![]', output: /^<section.*?section>\n*$/} ], processedMarkup; testPhrases.forEach(function (testPhrase) { processedMarkup = converter.makeHtml(testPhrase.input); processedMarkup.should.match(testPhrase.output); }); }); it('should have placeholder with image ONLY if image URL is present and valid', function () { var testPhrases = [ { input: '![image stuff](http://dsurl.stuff/something.jpg)', output: /^<section.*?<img class="js-upload-target.*?<\/section>$/ }, {input: '![]', output: /<img class="js-upload-target"/, not: true}, {input: '![]', output: /^<section.*?<\/section>$/}, {input: '![]()', output: /<img class="js-upload-target"/, not: true}, {input: '![]()', output: /^<section.*?<\/section>$/}, {input: '![]', output: /<img class="js-upload-target"/, not: true}, {input: '![]', output: /^<section.*?<\/section>$/} ], processedMarkup; testPhrases.forEach(function (testPhrase) { processedMarkup = converter.makeHtml(testPhrase.input); if (testPhrase.not) { processedMarkup.should.not.match(testPhrase.output); } else { processedMarkup.should.match(testPhrase.output); } }); }); /* No ref-style for now it('should have placeholder with image if image reference is present', function () { var testPhrases = [ { input: '![alt][id]\n\n[id]: http://dsurl.stuff/something.jpg', output: /^<section.*?<img class="js-upload-target.*?<\/section>$/ }, {input: '![][]', output: /^<section.*?<\/section>$/}, {input: '![][]', output: /<img class="js-upload-target"/, not: true}, {input: '![][id]', output: /^<section.*?<\/section>$/}, {input: '![][id]', output: /<img class="js-upload-target"/, not: true} ], processedMarkup; testPhrases.forEach(function (testPhrase) { processedMarkup = converter.makeHtml(testPhrase.input); if (testPhrase.not) { processedMarkup.should.not.match(testPhrase.output); } else { processedMarkup.should.match(testPhrase.output); } }); }); */ it('should correctly output link and image markdown without autolinks', function () { var testPhrases = [ { input: '[1](http://google.co.uk)', output: /^<p><a href="http:\/\/google.co.uk">1<\/a><\/p>$/ }, { input: ' [1](http://google.co.uk)', output: /^<p><a href="http:\/\/google.co.uk">1<\/a><\/p>$/ }, { input: '[http://google.co.uk](http://google.co.uk)', output: /^<p><a href="http:\/\/google.co.uk">http:\/\/google.co.uk<\/a><\/p>$/ }, { input: '[http://google.co.uk][id]\n\n[id]: http://google.co.uk', output: /^<p><a href="http:\/\/google.co.uk">http:\/\/google.co.uk<\/a><\/p>$/ }, { input: '![http://google.co.uk/kitten.jpg](http://google.co.uk/kitten.jpg)', output: /^<section.*?((?!<a href=\'http:\/\/google.co.uk\/kitten.jpg\').)*<\/section>$/ }, { input: '![image stuff](http://dsurl.stuff/something)', output: /^<section.*?((?!<a href=\'http:\/\/dsurl.stuff\/something\').)*<\/section>$/ } ], processedMarkup; testPhrases.forEach(function (testPhrase) { processedMarkup = converter.makeHtml(testPhrase.input); processedMarkup.should.match(testPhrase.output); }); }); it('should output block HTML untouched', function () { var testPhrases = [ { input: '<table class=\"test\">\n <tr>\n <td>Foo</td>\n </tr>\n <tr>\n <td>Bar</td>\n </tr>\n</table>', output: /^<table class=\"test\"> \n <tr>\n <td>Foo<\/td>\n <\/tr>\n <tr>\n <td>Bar<\/td>\n <\/tr>\n<\/table>$/ }, { input: '<hr />', output: /^<hr \/>$/ }, { // audio isn't counted as a block tag by showdown so gets wrapped in <p></p> input: '<audio class=\"podcastplayer\" controls>\n <source src=\"foobar.mp3\" type=\"audio/mp3\" preload=\"none\"></source>\n <source src=\"foobar.off\" type=\"audio/ogg\" preload=\"none\"></source>\n</audio>', output: /^<audio class=\"podcastplayer\" controls> \n <source src=\"foobar.mp3\" type=\"audio\/mp3\" preload=\"none\"><\/source>\n <source src=\"foobar.off\" type=\"audio\/ogg\" preload=\"none\"><\/source>\n<\/audio>$/ } ]; testPhrases.forEach(function (testPhrase) { var processedMarkup = converter.makeHtml(testPhrase.input); processedMarkup.should.match(testPhrase.output); }); }); // Waiting for showdown typography to be updated // it('should correctly convert quotes to curly quotes', function () { // var testPhrases = [ // { // input: 'Hello world\nIt's a fine day\nout', // output: /^<p>Hello world <br \/>\nIt’s a fine day <br \/>\nout<\/p>$/} // ]; // // testPhrases.forEach(function (testPhrase) { // processedMarkup = converter.makeHtml(testPhrase.input); // processedMarkup.should.match(testPhrase.output); // }); // }) });
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.useDragLayer = useDragLayer; var _react = require("react"); var _useDragDropManager = require("./useDragDropManager"); var _useCollector3 = require("./useCollector"); function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); } function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } function _iterableToArrayLimit(arr, i) { if (typeof Symbol === "undefined" || !(Symbol.iterator in Object(arr))) return; var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _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"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } /** * useDragLayer Hook * @param collector The property collector */ function useDragLayer(collect) { var dragDropManager = (0, _useDragDropManager.useDragDropManager)(); var monitor = dragDropManager.getMonitor(); var _useCollector = (0, _useCollector3.useCollector)(monitor, collect), _useCollector2 = _slicedToArray(_useCollector, 2), collected = _useCollector2[0], updateCollected = _useCollector2[1]; (0, _react.useEffect)(function () { return monitor.subscribeToOffsetChange(updateCollected); }); (0, _react.useEffect)(function () { return monitor.subscribeToStateChange(updateCollected); }); return collected; }
CKEDITOR.plugins.setLang("easyimage","it",{commands:{fullImage:"Immagine a dimensione intera",sideImage:"Immagine laterale",altText:"Cambia testo alternativo dell'immagine",upload:"Carica immagine"},uploadFailed:"L'immagine non può essere caricata a causa di un errore di rete."});
var underscore = require('./underscore.js'); // Start chaining a wrapped Underscore object. function chain(obj) { var instance = underscore(obj); instance._chain = true; return instance; } module.exports = chain;
(function($) { Craft.TableFieldSettings = Garnish.Base.extend( { columnsTableName: null, defaultsTableName: null, columnsTableId: null, defaultsTableId: null, columnsTableInputPath: null, defaultsTableInputPath: null, defaults: null, columnSettings: null, columnsTable: null, defaultsTable: null, init: function(columnsTableName, defaultsTableName, columns, defaults, columnSettings) { this.columnsTableName = columnsTableName; this.defaultsTableName = defaultsTableName; this.columnsTableId = Craft.formatInputId(this.columnsTableName); this.defaultsTableId = Craft.formatInputId(this.defaultsTableName); this.columnsTableInputPath = this.columnsTableId.split('-'); this.defaultsTableInputPath = this.defaultsTableId.split('-'); this.defaults = defaults; this.columnSettings = columnSettings; this.initColumnsTable(); this.initDefaultsTable(columns); }, initColumnsTable: function() { this.columnsTable = new Craft.EditableTable(this.columnsTableId, this.columnsTableName, this.columnSettings, { rowIdPrefix: 'col', onAddRow: $.proxy(this, 'onAddColumn'), onDeleteRow: $.proxy(this, 'reconstructDefaultsTable') }); this.initColumnSettingInputs(this.columnsTable.$tbody); this.columnsTable.sorter.settings.onSortChange = $.proxy(this, 'reconstructDefaultsTable'); }, initDefaultsTable: function(columns) { this.defaultsTable = new Craft.EditableTable(this.defaultsTableId, this.defaultsTableName, columns, { rowIdPrefix: 'row' }); }, onAddColumn: function($tr) { this.reconstructDefaultsTable(); this.initColumnSettingInputs($tr); }, initColumnSettingInputs: function($container) { var $textareas = $container.find('td:first-child textarea, td:nth-child(3) textarea'), $typeSelect = $container.find('td:nth-child(4) select'); this.addListener($textareas, 'textchange', 'reconstructDefaultsTable'); this.addListener($typeSelect, 'change', 'reconstructDefaultsTable'); }, reconstructDefaultsTable: function() { var columnsTableData = Craft.expandPostArray(Garnish.getPostData(this.columnsTable.$tbody)), defaultsTableData = Craft.expandPostArray(Garnish.getPostData(this.defaultsTable.$tbody)), columns = columnsTableData, defaults = defaultsTableData; for (var i = 0; i < this.columnsTableInputPath.length; i++) { var key = this.columnsTableInputPath[i]; columns = columns[key]; } for (var i = 0; i < this.defaultsTableInputPath.length; i++) { var key = this.defaultsTableInputPath[i]; defaults = defaults[key]; } var tableHtml = '<table id="'+this.defaultsTableId+'" class="editable shadow-box">' + '<thead>' + '<tr>'; for (var colId in columns) { tableHtml += '<th scope="col" class="header">'+(columns[colId].heading ? columns[colId].heading : '&nbsp;')+'</th>'; } tableHtml += '<th class="header" colspan="2"></th>' + '</tr>' + '</thead>' + '<tbody>'; for (var rowId in defaults) { tableHtml += Craft.EditableTable.getRowHtml(rowId, columns, this.defaultsTableName, defaults[rowId]); } tableHtml += '</tbody>' + '</table>'; this.defaultsTable.$table.replaceWith(tableHtml); this.defaultsTable.destroy(); delete this.defaultsTable; this.initDefaultsTable(columns); } }); })(jQuery);
//>>built define("dojox/mobile/Switch",["dojo/_base/array","dojo/_base/connect","dojo/_base/declare","dojo/_base/event","dojo/_base/window","dojo/dom-class","dojo/dom-construct","dojo/dom-style","dojo/dom-attr","dojo/touch","dijit/_Contained","dijit/_WidgetBase","./sniff","./_maskUtils","./common","dojo/has!dojo-bidi?dojox/mobile/bidi/Switch"],function(_1,_2,_3,_4,_5,_6,_7,_8,_9,_a,_b,_c,_d,_e,dm,_f){ var _10=_3(_d("dojo-bidi")?"dojox.mobile.NonBidiSwitch":"dojox.mobile.Switch",[_c,_b],{value:"on",name:"",leftLabel:"ON",rightLabel:"OFF",shape:"mblSwDefaultShape",tabIndex:"0",_setTabIndexAttr:"",baseClass:"mblSwitch",role:"",buildRendering:function(){ if(!this.templateString){ this.domNode=(this.srcNodeRef&&this.srcNodeRef.tagName==="SPAN")?this.srcNodeRef:_7.create("span"); } if(typeof this.domNode.style.msTouchAction!="undefined"){ this.domNode.style.msTouchAction="none"; } this.inherited(arguments); if(!this.templateString){ var c=(this.srcNodeRef&&this.srcNodeRef.className)||this.className||this["class"]; if((c=c.match(/mblSw.*Shape\d*/))){ this.shape=c; } _6.add(this.domNode,this.shape); var _11=this.name?" name=\""+this.name+"\"":""; this.domNode.innerHTML="<div class=\"mblSwitchInner\">"+"<div class=\"mblSwitchBg mblSwitchBgLeft\">"+"<div class=\"mblSwitchText mblSwitchTextLeft\"></div>"+"</div>"+"<div class=\"mblSwitchBg mblSwitchBgRight\">"+"<div class=\"mblSwitchText mblSwitchTextRight\"></div>"+"</div>"+"<div class=\"mblSwitchKnob\"></div>"+"<input type=\"hidden\""+_11+"></div>"+"</div>"; var n=this.inner=this.domNode.firstChild; this.left=n.childNodes[0]; this.right=n.childNodes[1]; this.knob=n.childNodes[2]; this.input=n.childNodes[3]; } _9.set(this.domNode,"role","checkbox"); _9.set(this.domNode,"aria-checked",(this.value==="on")?"true":"false"); this.switchNode=this.domNode; if(_d("windows-theme")){ var _12=_7.create("div",{className:"mblSwitchContainer"}); this.labelNode=_7.create("label",{"class":"mblSwitchLabel","for":this.id},_12); _12.appendChild(this.domNode.cloneNode(true)); this.domNode=_12; this.focusNode=_12.childNodes[1]; this.labelNode.innerHTML=(this.value=="off")?this.rightLabel:this.leftLabel; this.switchNode=this.domNode.childNodes[1]; var _13=this.inner=this.domNode.childNodes[1].firstChild; this.left=_13.childNodes[0]; this.right=_13.childNodes[1]; this.knob=_13.childNodes[2]; this.input=_13.childNodes[3]; } },postCreate:function(){ this.connect(this.switchNode,"onclick","_onClick"); this.connect(this.switchNode,"onkeydown","_onClick"); this._startHandle=this.connect(this.switchNode,_a.press,"onTouchStart"); this._initialValue=this.value; },startup:function(){ if(!this._started){ this.resize(); } },resize:function(){ if(_d("windows-theme")){ _8.set(this.domNode,"width","100%"); }else{ var _14=_8.get(this.domNode,"width"); var _15=_14+"px"; var _16=(_14-_8.get(this.knob,"width"))+"px"; _8.set(this.left,"width",_15); _8.set(this.right,this.isLeftToRight()?{width:_15,left:_16}:{width:_15}); _8.set(this.left.firstChild,"width",_16); _8.set(this.right.firstChild,"width",_16); _8.set(this.knob,"left",_16); if(this.value=="off"){ _8.set(this.inner,"left",this.isLeftToRight()?("-"+_16):0); } this._hasMaskImage=false; this._createMaskImage(); } },_changeState:function(_17,_18){ var on=(_17==="on"); this.left.style.display=""; this.right.style.display=""; this.inner.style.left=""; if(_18){ _6.add(this.switchNode,"mblSwitchAnimation"); } _6.remove(this.switchNode,on?"mblSwitchOff":"mblSwitchOn"); _6.add(this.switchNode,on?"mblSwitchOn":"mblSwitchOff"); _9.set(this.switchNode,"aria-checked",on?"true":"false"); if(!on&&!_d("windows-theme")){ this.inner.style.left=(this.isLeftToRight()?(-(_8.get(this.domNode,"width")-_8.get(this.knob,"width"))):0)+"px"; } var _19=this; _19.defer(function(){ _19.left.style.display=on?"":"none"; _19.right.style.display=!on?"":"none"; _6.remove(_19.switchNode,"mblSwitchAnimation"); },_18?300:0); },_createMaskImage:function(){ if(this._timer){ this._timer.remove(); delete this._timer; } if(this._hasMaskImage){ return; } var w=_8.get(this.domNode,"width"),h=_8.get(this.domNode,"height"); this._width=(w-_8.get(this.knob,"width")); this._hasMaskImage=true; if(!(_d("mask-image"))){ return; } var _1a=_8.get(this.left,"borderTopLeftRadius"); if(_1a=="0px"){ return; } var _1b=_1a.split(" "); var rx=parseFloat(_1b[0]),ry=(_1b.length==1)?rx:parseFloat(_1b[1]); var id=(this.shape+"Mask"+w+h+rx+ry).replace(/\./,"_"); _e.createRoundMask(this.switchNode,0,0,0,0,w,h,rx,ry,1); },_onClick:function(e){ if(e&&e.type==="keydown"&&e.keyCode!==13){ return; } if(this.onClick(e)===false){ return; } if(this._moved){ return; } this._set("value",this.input.value=(this.value=="on")?"off":"on"); this._changeState(this.value,true); this.onStateChanged(this.value); },onClick:function(){ },onTouchStart:function(e){ this._moved=false; this.innerStartX=this.inner.offsetLeft; if(!this._conn){ this._conn=[this.connect(this.inner,_a.move,"onTouchMove"),this.connect(_5.doc,_a.release,"onTouchEnd")]; if(_d("windows-theme")){ this._conn.push(this.connect(_5.doc,"MSPointerCancel","onTouchEnd")); } } this.touchStartX=e.touches?e.touches[0].pageX:e.clientX; this.left.style.display=""; this.right.style.display=""; _4.stop(e); this._createMaskImage(); },onTouchMove:function(e){ e.preventDefault(); var dx; if(e.targetTouches){ if(e.targetTouches.length!=1){ return; } dx=e.targetTouches[0].clientX-this.touchStartX; }else{ dx=e.clientX-this.touchStartX; } var pos=this.innerStartX+dx; var d=10; if(pos<=-(this._width-d)){ pos=-this._width; } if(pos>=-d){ pos=0; } this.inner.style.left=pos+"px"; if(Math.abs(dx)>d){ this._moved=true; } },onTouchEnd:function(e){ _1.forEach(this._conn,_2.disconnect); this._conn=null; if(this.innerStartX==this.inner.offsetLeft){ if(_d("touch")&&_d("clicks-prevented")){ dm._sendClick(this.inner,e); } return; } var _1c=(this.inner.offsetLeft<-(this._width/2))?"off":"on"; _1c=this._newState(_1c); this._changeState(_1c,true); if(_1c!=this.value){ this._set("value",this.input.value=_1c); this.onStateChanged(_1c); } },_newState:function(_1d){ return _1d; },onStateChanged:function(_1e){ if(this.labelNode){ this.labelNode.innerHTML=_1e=="off"?this.rightLabel:this.leftLabel; } },_setValueAttr:function(_1f){ this._changeState(_1f,false); if(this.value!=_1f){ this._set("value",this.input.value=_1f); this.onStateChanged(_1f); } },_setLeftLabelAttr:function(_20){ this.leftLabel=_20; this.left.firstChild.innerHTML=this._cv?this._cv(_20):_20; },_setRightLabelAttr:function(_21){ this.rightLabel=_21; this.right.firstChild.innerHTML=this._cv?this._cv(_21):_21; },reset:function(){ this.set("value",this._initialValue); }}); return _d("dojo-bidi")?_3("dojox.mobile.Switch",[_10,_f]):_10; });
var should = require("should"); it("should be able to load JSON files without loader", function() { var someJson = require("./some.json"); someJson.should.have.property("it", "works"); someJson.should.have.property("number", 42); }); it("should also work when the json extension is omitted", function() { var someJson = require("./some"); someJson.should.have.property("it", "works"); someJson.should.have.property("number", 42); }); it("should still be possible to manually apply the json-loader for compatibility reasons", function() { var someJson = require("json-loader!./some.json"); someJson.should.have.property("it", "works"); someJson.should.have.property("number", 42); }); it("should still be possible to use a custom loader", function() { var someJson = JSON.parse(require("raw-loader!./some.json")); someJson.should.have.property("it", "works"); someJson.should.have.property("number", 42); });
module.exports = DTMF; var C = { MIN_DURATION: 70, MAX_DURATION: 6000, DEFAULT_DURATION: 100, MIN_INTER_TONE_GAP: 50, DEFAULT_INTER_TONE_GAP: 500 }; /** * Expose C object. */ DTMF.C = C; /** * Dependencies. */ var debug = require('debug')('JsSIP:RTCSession:DTMF'); var debugerror = require('debug')('JsSIP:ERROR:RTCSession:DTMF'); debugerror.log = console.warn.bind(console); var JsSIP_C = require('../Constants'); var Exceptions = require('../Exceptions'); var RTCSession = require('../RTCSession'); function DTMF(session) { this.owner = session; this.direction = null; this.tone = null; this.duration = null; } DTMF.prototype.send = function(tone, options) { var extraHeaders, body; if (tone === undefined) { throw new TypeError('Not enough arguments'); } this.direction = 'outgoing'; // Check RTCSession Status if (this.owner.status !== RTCSession.C.STATUS_CONFIRMED && this.owner.status !== RTCSession.C.STATUS_WAITING_FOR_ACK) { throw new Exceptions.InvalidStateError(this.owner.status); } // Get DTMF options options = options || {}; extraHeaders = options.extraHeaders ? options.extraHeaders.slice() : []; this.eventHandlers = options.eventHandlers || {}; // Check tone type if (typeof tone === 'string' ) { tone = tone.toUpperCase(); } else if (typeof tone === 'number') { tone = tone.toString(); } else { throw new TypeError('Invalid tone: '+ tone); } // Check tone value if (!tone.match(/^[0-9A-D#*]$/)) { throw new TypeError('Invalid tone: '+ tone); } else { this.tone = tone; } // Duration is checked/corrected in RTCSession this.duration = options.duration; extraHeaders.push('Content-Type: application/dtmf-relay'); body = 'Signal=' + this.tone + '\r\n'; body += 'Duration=' + this.duration; this.owner.newDTMF({ originator: 'local', dtmf: this, request: this.request }); this.owner.dialog.sendRequest(this, JsSIP_C.INFO, { extraHeaders: extraHeaders, body: body }); }; DTMF.prototype.receiveResponse = function(response) { switch(true) { case /^1[0-9]{2}$/.test(response.status_code): // Ignore provisional responses. break; case /^2[0-9]{2}$/.test(response.status_code): debug('onSuccessResponse'); if (this.eventHandlers.onSuccessResponse) { this.eventHandlers.onSuccessResponse(response); } break; default: if (this.eventHandlers.onErrorResponse) { this.eventHandlers.onErrorResponse(response); } break; } }; DTMF.prototype.onRequestTimeout = function() { debugerror('onRequestTimeout'); if (this.eventHandlers.onRequestTimeout) { this.eventHandlers.onRequestTimeout(); } }; DTMF.prototype.onTransportError = function() { debugerror('onTransportError'); if (this.eventHandlers.onTransportError) { this.eventHandlers.onTransportError(); } }; DTMF.prototype.onDialogError = function() { debugerror('onDialogError'); if (this.eventHandlers.onDialogError) { this.eventHandlers.onDialogError(); } }; DTMF.prototype.init_incoming = function(request) { var body, reg_tone = /^(Signal\s*?=\s*?)([0-9A-D#*]{1})(\s)?.*/, reg_duration = /^(Duration\s?=\s?)([0-9]{1,4})(\s)?.*/; this.direction = 'incoming'; this.request = request; request.reply(200); if (request.body) { body = request.body.split('\n'); if (body.length >= 1) { if (reg_tone.test(body[0])) { this.tone = body[0].replace(reg_tone,'$2'); } } if (body.length >=2) { if (reg_duration.test(body[1])) { this.duration = parseInt(body[1].replace(reg_duration,'$2'), 10); } } } if (!this.duration) { this.duration = C.DEFAULT_DURATION; } if (!this.tone) { debug('invalid INFO DTMF received, discarded'); } else { this.owner.newDTMF({ originator: 'remote', dtmf: this, request: request }); } };
import React, { Component, PropTypes } from 'react' import { connect } from 'react-redux' import { loadRepo, loadStargazers } from '../actions' import Repo from '../components/Repo' import User from '../components/User' import List from '../components/List' function loadData(props) { const { fullName } = props props.loadRepo(fullName, [ 'description' ]) props.loadStargazers(fullName) } class RepoPage extends Component { constructor(props) { super(props) this.renderUser = this.renderUser.bind(this) this.handleLoadMoreClick = this.handleLoadMoreClick.bind(this) } componentWillMount() { loadData(this.props) } componentWillReceiveProps(nextProps) { if (nextProps.fullName !== this.props.fullName) { loadData(nextProps) } } handleLoadMoreClick() { this.props.loadStargazers(this.props.fullName, true) } renderUser(user) { return ( <User user={user} key={user.login} /> ) } render() { const { repo, owner, name } = this.props if (!repo || !owner) { return <h1><i>Loading {name} details...</i></h1> } const { stargazers, stargazersPagination } = this.props return ( <div> <Repo repo={repo} owner={owner} /> <hr /> <List renderItem={this.renderUser} items={stargazers} onLoadMoreClick={this.handleLoadMoreClick} loadingLabel={`Loading stargazers of ${name}...`} {...stargazersPagination} /> </div> ) } } RepoPage.propTypes = { repo: PropTypes.object, fullName: PropTypes.string.isRequired, name: PropTypes.string.isRequired, owner: PropTypes.object, stargazers: PropTypes.array.isRequired, stargazersPagination: PropTypes.object, loadRepo: PropTypes.func.isRequired, loadStargazers: PropTypes.func.isRequired } function mapStateToProps(state, ownProps) { const { login, name } = ownProps.params const { pagination: { stargazersByRepo }, entities: { users, repos } } = state const fullName = `${login}/${name}` const stargazersPagination = stargazersByRepo[fullName] || { ids: [] } const stargazers = stargazersPagination.ids.map(id => users[id]) return { fullName, name, stargazers, stargazersPagination, repo: repos[fullName], owner: users[login] } } export default connect(mapStateToProps, { loadRepo, loadStargazers })(RepoPage)
'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; }; }(); var _three = require('three'); var THREE = _interopRequireWildcard(_three); var _ShapeAction2 = require('./ShapeAction'); var _ShapeAction3 = _interopRequireDefault(_ShapeAction2); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } 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 _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(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; } function _inherits(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 BezierCurveToAction = function (_ShapeAction) { _inherits(BezierCurveToAction, _ShapeAction); function BezierCurveToAction(cp1X, cp1Y, cp2X, cp2Y, aX, aY) { _classCallCheck(this, BezierCurveToAction); var _this = _possibleConstructorReturn(this, (BezierCurveToAction.__proto__ || Object.getPrototypeOf(BezierCurveToAction)).call(this)); _this.cp1X = cp1X; _this.cp1Y = cp1Y; _this.cp2X = cp2X; _this.cp2Y = cp2Y; _this.aX = aX; _this.aY = aY; return _this; } _createClass(BezierCurveToAction, [{ key: 'performAction', value: function performAction(shape) { shape.bezierCurveTo(this.cp1X, this.cp1Y, this.cp2X, this.cp2Y, this.aX, this.aY); } }]); return BezierCurveToAction; }(_ShapeAction3.default); module.exports = BezierCurveToAction;
'use strict'; // Oracle Formatter // ------ module.exports = function(client) { var Formatter = require('../../formatter'); var inherits = require('inherits'); // The "formatter" is used to ensure all output is properly // escaped & parameterized. function Formatter_Oracle() { this.client = client; Formatter.apply(this, arguments); } inherits(Formatter_Oracle, Formatter); Formatter_Oracle.prototype.operators = [ '=', '<', '>', '<=', '>=', '<>', '!=', 'like', 'not like', 'between', 'ilike', '&', '|', '^', '<<', '>>', 'rlike', 'regexp', 'not regexp' ]; // Wraps a value (column, tableName) with the correct ticks. Formatter_Oracle.prototype.wrapValue = function(value) { return (value !== '*' ? '"' + value + '"' : '*'); }; // Coerce to string to prevent strange errors when it's not a string. Formatter_Oracle.prototype._wrapString = function(value) { var segments, asIndex = value.toLowerCase().indexOf(' as '); if (asIndex !== -1) { var first = value.slice(0, asIndex); var second = value.slice(asIndex + 4); return this.wrap(first) + ' ' + this.wrap(second); } var wrapped = []; segments = value.split('.'); for (var i = 0, l = segments.length; i < l; i = ++i) { value = segments[i]; if (i === 0 && segments.length > 1) { wrapped.push(this.wrap((value || '').trim())); } else { wrapped.push(this.wrapValue((value || '').trim())); } } return wrapped.join('.'); }; // Memoize the calls to "wrap" for a little extra perf. var wrapperMemo = (function(){ var memo = Object.create(null); return function(key) { if (memo[key] === void 0) { memo[key] = this._wrapString(key); } return memo[key]; }; }()); Formatter_Oracle.prototype._wrap = wrapperMemo; // Ensures the query is aliased if necessary. Formatter_Oracle.prototype.outputQuery = function(compiled, alwaysWrapped) { var sql = compiled.sql || ''; if (sql) { if (compiled.method === 'select' && alwaysWrapped || compiled.as) { sql = '(' + sql + ')'; if (compiled.as) sql += ' ' + this.wrap(compiled.as); } } return sql; }; // Assign the formatter to the the client. client.Formatter = Formatter_Oracle; };
var should = require('should'), sinon = require('sinon'), Promise = require('bluebird'), _ = require('lodash'), authStrategies = require('../../../server/auth/auth-strategies'), Models = require('../../../server/models'), errors = require('../../../server/errors'), globalUtils = require('../../../server/utils'), sandbox = sinon.sandbox.create(), fakeClient = { slug: 'ghost-admin', secret: 'not_available', status: 'enabled' }, fakeValidToken = { user_id: 3, token: 'valid-token', client_id: 1, expires: Date.now() + globalUtils.ONE_DAY_MS }, fakeInvalidToken = { user_id: 3, token: 'expired-token', client_id: 1, expires: Date.now() - globalUtils.ONE_DAY_MS }; describe('Auth Strategies', function () { var next; before(function () { // Loads all the models Models.init(); }); beforeEach(function () { next = sandbox.spy(); }); afterEach(function () { sandbox.restore(); }); describe('Client Password Strategy', function () { var clientStub; beforeEach(function () { clientStub = sandbox.stub(Models.Client, 'findOne'); clientStub.returns(new Promise.resolve()); clientStub.withArgs({slug: fakeClient.slug}).returns(new Promise.resolve({ toJSON: function () { return fakeClient; } })); }); it('should find client', function (done) { var clientId = 'ghost-admin', clientSecret = 'not_available'; authStrategies.clientPasswordStrategy(clientId, clientSecret, next).then(function () { clientStub.calledOnce.should.be.true(); clientStub.calledWith({slug: clientId}).should.be.true(); next.called.should.be.true(); next.firstCall.args.length.should.eql(2); should.equal(next.firstCall.args[0], null); next.firstCall.args[1].slug.should.eql(clientId); done(); }).catch(done); }); it('shouldn\'t find client with invalid id', function (done) { var clientId = 'invalid_id', clientSecret = 'not_available'; authStrategies.clientPasswordStrategy(clientId, clientSecret, next).then(function () { clientStub.calledOnce.should.be.true(); clientStub.calledWith({slug: clientId}).should.be.true(); next.called.should.be.true(); next.calledWith(null, false).should.be.true(); done(); }).catch(done); }); it('shouldn\'t find client with invalid secret', function (done) { var clientId = 'ghost-admin', clientSecret = 'invalid_secret'; authStrategies.clientPasswordStrategy(clientId, clientSecret, next).then(function () { clientStub.calledOnce.should.be.true(); clientStub.calledWith({slug: clientId}).should.be.true(); next.called.should.be.true(); next.calledWith(null, false).should.be.true(); done(); }).catch(done); }); it('shouldn\'t auth client that is disabled', function (done) { var clientId = 'ghost-admin', clientSecret = 'not_available'; fakeClient.status = 'disabled'; authStrategies.clientPasswordStrategy(clientId, clientSecret, next).then(function () { clientStub.calledOnce.should.be.true(); clientStub.calledWith({slug: clientId}).should.be.true(); next.called.should.be.true(); next.calledWith(null, false).should.be.true(); done(); }).catch(done); }); }); describe('Bearer Strategy', function () { var tokenStub, userStub, userIsActive; beforeEach(function () { tokenStub = sandbox.stub(Models.Accesstoken, 'findOne'); tokenStub.returns(new Promise.resolve()); tokenStub.withArgs({token: fakeValidToken.token}).returns(new Promise.resolve({ toJSON: function () { return fakeValidToken; } })); tokenStub.withArgs({token: fakeInvalidToken.token}).returns(new Promise.resolve({ toJSON: function () { return fakeInvalidToken; } })); userStub = sandbox.stub(Models.User, 'findOne'); userStub.returns(new Promise.resolve()); userStub.withArgs({id: 3}).returns(new Promise.resolve({ toJSON: function () { return {id: 3}; }, isActive: function () { return userIsActive; } })); }); it('should find user with valid token', function (done) { var accessToken = 'valid-token', userId = 3; userIsActive = true; authStrategies.bearerStrategy(accessToken, next).then(function () { tokenStub.calledOnce.should.be.true(); tokenStub.calledWith({token: accessToken}).should.be.true(); userStub.calledOnce.should.be.true(); userStub.calledWith({id: userId}).should.be.true(); next.calledOnce.should.be.true(); next.firstCall.args.length.should.eql(3); next.calledWith(null, {id: userId}, {scope: '*'}).should.be.true(); done(); }).catch(done); }); it('should find user with valid token, but user is suspended', function (done) { var accessToken = 'valid-token', userId = 3; userIsActive = false; authStrategies.bearerStrategy(accessToken, next).then(function () { tokenStub.calledOnce.should.be.true(); tokenStub.calledWith({token: accessToken}).should.be.true(); userStub.calledOnce.should.be.true(); userStub.calledWith({id: userId}).should.be.true(); next.calledOnce.should.be.true(); next.firstCall.args.length.should.eql(1); (next.firstCall.args[0] instanceof errors.NoPermissionError).should.eql(true); next.firstCall.args[0].message.should.eql('Your account was suspended.'); done(); }).catch(done); }); it('shouldn\'t find user with invalid token', function (done) { var accessToken = 'invalid_token'; authStrategies.bearerStrategy(accessToken, next).then(function () { tokenStub.calledOnce.should.be.true(); tokenStub.calledWith({token: accessToken}).should.be.true(); userStub.called.should.be.false(); next.called.should.be.true(); next.calledWith(null, false).should.be.true(); done(); }).catch(done); }); it('should find user that doesn\'t exist', function (done) { var accessToken = 'valid-token', userId = 2; // override user fakeValidToken.user_id = userId; authStrategies.bearerStrategy(accessToken, next).then(function () { tokenStub.calledOnce.should.be.true(); tokenStub.calledWith({token: accessToken}).should.be.true(); userStub.calledOnce.should.be.true(); userStub.calledWith({id: userId}).should.be.true(); next.called.should.be.true(); next.calledWith(null, false).should.be.true(); done(); }).catch(done); }); it('should find user with expired token', function (done) { var accessToken = 'expired-token'; authStrategies.bearerStrategy(accessToken, next).then(function () { tokenStub.calledOnce.should.be.true(); tokenStub.calledWith({token: accessToken}).should.be.true(); userStub.calledOnce.should.be.false(); next.called.should.be.true(); next.calledWith(null, false).should.be.true(); done(); }).catch(done); }); }); describe('Ghost Strategy', function () { var inviteFindOneStub, userAddStub, userEditStub, userFindOneStub; beforeEach(function () { userFindOneStub = sandbox.stub(Models.User, 'findOne'); userAddStub = sandbox.stub(Models.User, 'add'); userEditStub = sandbox.stub(Models.User, 'edit'); inviteFindOneStub = sandbox.stub(Models.Invite, 'findOne'); }); it('with invite, but with wrong invite token', function (done) { var ghostAuthAccessToken = '12345', req = {body: {inviteToken: 'wrong'}}, profile = {email: 'test@example.com', id: '1234'}; userFindOneStub.returns(Promise.resolve(null)); inviteFindOneStub.returns(Promise.reject(new errors.NotFoundError())); authStrategies.ghostStrategy(req, ghostAuthAccessToken, null, profile, function (err) { should.exist(err); (err instanceof errors.NotFoundError).should.eql(true); userFindOneStub.calledOnce.should.be.false(); inviteFindOneStub.calledOnce.should.be.true(); done(); }); }); it('with correct invite token, but expired', function (done) { var ghostAuthAccessToken = '12345', req = {body: {inviteToken: 'token'}}, profile = {email: 'test@example.com', id: '1234'}; userFindOneStub.returns(Promise.resolve(null)); inviteFindOneStub.returns(Promise.resolve(Models.Invite.forge({ id: 1, token: 'token', expires: Date.now() - 1000 }))); authStrategies.ghostStrategy(req, ghostAuthAccessToken, null, profile, function (err) { should.exist(err); (err instanceof errors.NotFoundError).should.eql(true); userFindOneStub.calledOnce.should.be.false(); inviteFindOneStub.calledOnce.should.be.true(); done(); }); }); it('with correct invite token', function (done) { var ghostAuthAccessToken = '12345', req = {body: {inviteToken: 'token'}}, invitedProfile = {email: 'test@example.com', name: 'Wolfram Alpha', id: '1234'}, invitedUser = {id: 2}, inviteModel = Models.Invite.forge({ id: 1, token: 'token', expires: Date.now() + 2000, role_id: '2' }); sandbox.stub(globalUtils, 'uid').returns('12345678'); userFindOneStub.returns(Promise.resolve(null)); userAddStub.withArgs({ email: invitedProfile.email, name: invitedProfile.name, password: '12345678', roles: [inviteModel.get('role_id')], ghost_auth_id: invitedProfile.id, ghost_auth_access_token: ghostAuthAccessToken }, { context: {internal: true} }).returns(Promise.resolve(invitedUser)); userEditStub.returns(Promise.resolve(invitedUser)); inviteFindOneStub.returns(Promise.resolve(inviteModel)); sandbox.stub(inviteModel, 'destroy').returns(Promise.resolve()); authStrategies.ghostStrategy(req, ghostAuthAccessToken, null, invitedProfile, function (err, user, profile) { should.not.exist(err); should.exist(user); should.exist(profile); user.should.eql(invitedUser); profile.should.eql(invitedProfile); userAddStub.calledOnce.should.be.true(); userFindOneStub.calledOnce.should.be.false(); inviteFindOneStub.calledOnce.should.be.true(); done(); }); }); it('setup', function (done) { var ghostAuthAccessToken = '12345', req = {body: {}}, ownerProfile = {email: 'test@example.com', name: 'Wolfram Alpha', id: '1234'}, owner = {id: 2}; userFindOneStub.withArgs({ghost_auth_id: ownerProfile.id}) .returns(Promise.resolve(null)); userFindOneStub.withArgs({slug: 'ghost-owner', status: 'inactive'}) .returns(Promise.resolve(_.merge({}, {status: 'inactive'}, owner))); userEditStub.withArgs({ email: ownerProfile.email, name: ownerProfile.name, slug: null, status: 'active', ghost_auth_id: ownerProfile.id, ghost_auth_access_token: ghostAuthAccessToken }, { context: {internal: true}, id: owner.id }).returns(Promise.resolve(owner)); authStrategies.ghostStrategy(req, ghostAuthAccessToken, null, ownerProfile, function (err, user, profile) { should.not.exist(err); userFindOneStub.calledTwice.should.be.true(); inviteFindOneStub.calledOnce.should.be.false(); userEditStub.calledOnce.should.be.true(); should.exist(user); should.exist(profile); user.should.eql(owner); profile.should.eql(ownerProfile); done(); }); }); it('sign in', function (done) { var ghostAuthAccessToken = '12345', req = {body: {}}, ownerProfile = {email: 'test@example.com', name: 'Wolfram Alpha', id: '12345'}, owner = { id: 2, isActive: function () { return true; } }; userFindOneStub.returns(Promise.resolve(owner)); userEditStub.withArgs({ email: ownerProfile.email, name: ownerProfile.name, ghost_auth_access_token: ghostAuthAccessToken, ghost_auth_id: ownerProfile.id }, { context: {internal: true}, id: owner.id }).returns(Promise.resolve(owner)); authStrategies.ghostStrategy(req, ghostAuthAccessToken, null, ownerProfile, function (err, user, profile) { should.not.exist(err); userFindOneStub.calledOnce.should.be.true(); userEditStub.calledOnce.should.be.true(); inviteFindOneStub.calledOnce.should.be.false(); should.exist(user); should.exist(profile); user.should.eql(owner); profile.should.eql(ownerProfile); done(); }); }); it('sign in, but user is suspended', function (done) { var ghostAuthAccessToken = '12345', req = {body: {}}, ownerProfile = {email: 'test@example.com', id: '12345'}, owner = { id: 2, isActive: function () { return false; } }; userFindOneStub.returns(Promise.resolve(owner)); userEditStub.withArgs({ ghost_auth_access_token: ghostAuthAccessToken, ghost_auth_id: ownerProfile.id, email: ownerProfile.email }, { context: {internal: true}, id: owner.id }).returns(Promise.resolve(owner)); authStrategies.ghostStrategy(req, ghostAuthAccessToken, null, ownerProfile, function (err, user, profile) { should.exist(err); err.message.should.eql('Your account was suspended.'); userFindOneStub.calledOnce.should.be.true(); userEditStub.calledOnce.should.be.false(); inviteFindOneStub.calledOnce.should.be.false(); should.not.exist(user); should.not.exist(profile); done(); }); }); }); });
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); }; import { Injectable } from 'angular2/src/core/di'; import { CssAnimationBuilder } from './css_animation_builder'; import { BrowserDetails } from './browser_details'; export let AnimationBuilder = class AnimationBuilder { /** * Used for DI * @param browserDetails */ constructor(browserDetails) { this.browserDetails = browserDetails; } /** * Creates a new CSS Animation * @returns {CssAnimationBuilder} */ css() { return new CssAnimationBuilder(this.browserDetails); } }; AnimationBuilder = __decorate([ Injectable(), __metadata('design:paramtypes', [BrowserDetails]) ], AnimationBuilder);
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports["default"] = void 0; // persion shortened var strings = { prefixAgo: null, prefixFromNow: null, suffixAgo: '', suffixFromNow: '', seconds: '1دقیقه', minute: '1دقیقه', minutes: '%dدقیقه', hour: '1ساعت', hours: '%dساعت', day: '1روز', days: '%dروز', month: '1ماه', months: '%dماه', year: '1سال', years: '%dسال', wordSeparator: ' ' }; var _default = strings; exports["default"] = _default;
/** * @fileoverview Abstraction of JavaScript source code. * @author Nicholas C. Zakas */ "use strict"; //------------------------------------------------------------------------------ // Requirements //------------------------------------------------------------------------------ const TokenStore = require("../token-store"), Traverser = require("./traverser"), astUtils = require("../ast-utils"), lodash = require("lodash"); //------------------------------------------------------------------------------ // Private //------------------------------------------------------------------------------ /** * Validates that the given AST has the required information. * @param {ASTNode} ast The Program node of the AST to check. * @throws {Error} If the AST doesn't contain the correct information. * @returns {void} * @private */ function validate(ast) { if (!ast.tokens) { throw new Error("AST is missing the tokens array."); } if (!ast.comments) { throw new Error("AST is missing the comments array."); } if (!ast.loc) { throw new Error("AST is missing location information."); } if (!ast.range) { throw new Error("AST is missing range information"); } } /** * Check to see if its a ES6 export declaration. * @param {ASTNode} astNode An AST node. * @returns {boolean} whether the given node represents an export declaration. * @private */ function looksLikeExport(astNode) { return astNode.type === "ExportDefaultDeclaration" || astNode.type === "ExportNamedDeclaration" || astNode.type === "ExportAllDeclaration" || astNode.type === "ExportSpecifier"; } /** * Merges two sorted lists into a larger sorted list in O(n) time. * @param {Token[]} tokens The list of tokens. * @param {Token[]} comments The list of comments. * @returns {Token[]} A sorted list of tokens and comments. * @private */ function sortedMerge(tokens, comments) { const result = []; let tokenIndex = 0; let commentIndex = 0; while (tokenIndex < tokens.length || commentIndex < comments.length) { if (commentIndex >= comments.length || tokenIndex < tokens.length && tokens[tokenIndex].range[0] < comments[commentIndex].range[0]) { result.push(tokens[tokenIndex++]); } else { result.push(comments[commentIndex++]); } } return result; } //------------------------------------------------------------------------------ // Public Interface //------------------------------------------------------------------------------ class SourceCode extends TokenStore { /** * Represents parsed source code. * @param {string|Object} textOrConfig - The source code text or config object. * @param {string} textOrConfig.text - The source code text. * @param {ASTNode} textOrConfig.ast - The Program node of the AST representing the code. This AST should be created from the text that BOM was stripped. * @param {Object|null} textOrConfig.parserServices - The parser srevices. * @param {ScopeManager|null} textOrConfig.scopeManager - The scope of this source code. * @param {Object|null} textOrConfig.visitorKeys - The visitor keys to traverse AST. * @param {ASTNode} [astIfNoConfig] - The Program node of the AST representing the code. This AST should be created from the text that BOM was stripped. * @constructor */ constructor(textOrConfig, astIfNoConfig) { let text, ast, parserServices, scopeManager, visitorKeys; // Process overloading. if (typeof textOrConfig === "string") { text = textOrConfig; ast = astIfNoConfig; } else if (typeof textOrConfig === "object" && textOrConfig !== null) { text = textOrConfig.text; ast = textOrConfig.ast; parserServices = textOrConfig.parserServices; scopeManager = textOrConfig.scopeManager; visitorKeys = textOrConfig.visitorKeys; } validate(ast); super(ast.tokens, ast.comments); /** * The flag to indicate that the source code has Unicode BOM. * @type boolean */ this.hasBOM = (text.charCodeAt(0) === 0xFEFF); /** * The original text source code. * BOM was stripped from this text. * @type string */ this.text = (this.hasBOM ? text.slice(1) : text); /** * The parsed AST for the source code. * @type ASTNode */ this.ast = ast; /** * The parser services of this source code. * @type {Object} */ this.parserServices = parserServices || {}; /** * The scope of this source code. * @type {ScopeManager|null} */ this.scopeManager = scopeManager || null; /** * The visitor keys to traverse AST. * @type {Object} */ this.visitorKeys = visitorKeys || Traverser.DEFAULT_VISITOR_KEYS; // Check the source text for the presence of a shebang since it is parsed as a standard line comment. const shebangMatched = this.text.match(astUtils.SHEBANG_MATCHER); const hasShebang = shebangMatched && ast.comments.length && ast.comments[0].value === shebangMatched[1]; if (hasShebang) { ast.comments[0].type = "Shebang"; } this.tokensAndComments = sortedMerge(ast.tokens, ast.comments); /** * The source code split into lines according to ECMA-262 specification. * This is done to avoid each rule needing to do so separately. * @type string[] */ this.lines = []; this.lineStartIndices = [0]; const lineEndingPattern = astUtils.createGlobalLinebreakMatcher(); let match; /* * Previously, this was implemented using a regex that * matched a sequence of non-linebreak characters followed by a * linebreak, then adding the lengths of the matches. However, * this caused a catastrophic backtracking issue when the end * of a file contained a large number of non-newline characters. * To avoid this, the current implementation just matches newlines * and uses match.index to get the correct line start indices. */ while ((match = lineEndingPattern.exec(this.text))) { this.lines.push(this.text.slice(this.lineStartIndices[this.lineStartIndices.length - 1], match.index)); this.lineStartIndices.push(match.index + match[0].length); } this.lines.push(this.text.slice(this.lineStartIndices[this.lineStartIndices.length - 1])); // Cache for comments found using getComments(). this._commentCache = new WeakMap(); // don't allow modification of this object Object.freeze(this); Object.freeze(this.lines); } /** * Split the source code into multiple lines based on the line delimiters. * @param {string} text Source code as a string. * @returns {string[]} Array of source code lines. * @public */ static splitLines(text) { return text.split(astUtils.createGlobalLinebreakMatcher()); } /** * Gets the source code for the given node. * @param {ASTNode=} node The AST node to get the text for. * @param {int=} beforeCount The number of characters before the node to retrieve. * @param {int=} afterCount The number of characters after the node to retrieve. * @returns {string} The text representing the AST node. * @public */ getText(node, beforeCount, afterCount) { if (node) { return this.text.slice(Math.max(node.range[0] - (beforeCount || 0), 0), node.range[1] + (afterCount || 0)); } return this.text; } /** * Gets the entire source text split into an array of lines. * @returns {Array} The source text as an array of lines. * @public */ getLines() { return this.lines; } /** * Retrieves an array containing all comments in the source code. * @returns {ASTNode[]} An array of comment nodes. * @public */ getAllComments() { return this.ast.comments; } /** * Gets all comments for the given node. * @param {ASTNode} node The AST node to get the comments for. * @returns {Object} An object containing a leading and trailing array * of comments indexed by their position. * @public */ getComments(node) { if (this._commentCache.has(node)) { return this._commentCache.get(node); } const comments = { leading: [], trailing: [] }; /* * Return all comments as leading comments of the Program node when * there is no executable code. */ if (node.type === "Program") { if (node.body.length === 0) { comments.leading = node.comments; } } else { /* * Return comments as trailing comments of nodes that only contain * comments (to mimic the comment attachment behavior present in Espree). */ if ((node.type === "BlockStatement" || node.type === "ClassBody") && node.body.length === 0 || node.type === "ObjectExpression" && node.properties.length === 0 || node.type === "ArrayExpression" && node.elements.length === 0 || node.type === "SwitchStatement" && node.cases.length === 0 ) { comments.trailing = this.getTokens(node, { includeComments: true, filter: astUtils.isCommentToken }); } /* * Iterate over tokens before and after node and collect comment tokens. * Do not include comments that exist outside of the parent node * to avoid duplication. */ let currentToken = this.getTokenBefore(node, { includeComments: true }); while (currentToken && astUtils.isCommentToken(currentToken)) { if (node.parent && (currentToken.start < node.parent.start)) { break; } comments.leading.push(currentToken); currentToken = this.getTokenBefore(currentToken, { includeComments: true }); } comments.leading.reverse(); currentToken = this.getTokenAfter(node, { includeComments: true }); while (currentToken && astUtils.isCommentToken(currentToken)) { if (node.parent && (currentToken.end > node.parent.end)) { break; } comments.trailing.push(currentToken); currentToken = this.getTokenAfter(currentToken, { includeComments: true }); } } this._commentCache.set(node, comments); return comments; } /** * Retrieves the JSDoc comment for a given node. * @param {ASTNode} node The AST node to get the comment for. * @returns {Token|null} The Block comment token containing the JSDoc comment * for the given node or null if not found. * @public */ getJSDocComment(node) { /** * Checks for the presence of a JSDoc comment for the given node and returns it. * @param {ASTNode} astNode The AST node to get the comment for. * @returns {Token|null} The Block comment token containing the JSDoc comment * for the given node or null if not found. * @private */ const findJSDocComment = astNode => { const tokenBefore = this.getTokenBefore(astNode, { includeComments: true }); if ( tokenBefore && astUtils.isCommentToken(tokenBefore) && tokenBefore.type === "Block" && tokenBefore.value.charAt(0) === "*" && astNode.loc.start.line - tokenBefore.loc.end.line <= 1 ) { return tokenBefore; } return null; }; let parent = node.parent; switch (node.type) { case "ClassDeclaration": case "FunctionDeclaration": return findJSDocComment(looksLikeExport(parent) ? parent : node); case "ClassExpression": return findJSDocComment(parent.parent); case "ArrowFunctionExpression": case "FunctionExpression": if (parent.type !== "CallExpression" && parent.type !== "NewExpression") { while ( !this.getCommentsBefore(parent).length && !/Function/.test(parent.type) && parent.type !== "MethodDefinition" && parent.type !== "Property" ) { parent = parent.parent; if (!parent) { break; } } if (parent && parent.type !== "FunctionDeclaration" && parent.type !== "Program") { return findJSDocComment(parent); } } return findJSDocComment(node); // falls through default: return null; } } /** * Gets the deepest node containing a range index. * @param {int} index Range index of the desired node. * @returns {ASTNode} The node if found or null if not found. * @public */ getNodeByRangeIndex(index) { let result = null, resultParent = null; Traverser.traverse(this.ast, { visitorKeys: this.visitorKeys, enter(node, parent) { if (node.range[0] <= index && index < node.range[1]) { result = node; resultParent = parent; } else { this.skip(); } }, leave(node) { if (node === result) { this.break(); } } }); return result ? Object.assign({ parent: resultParent }, result) : null; } /** * Determines if two tokens have at least one whitespace character * between them. This completely disregards comments in making the * determination, so comments count as zero-length substrings. * @param {Token} first The token to check after. * @param {Token} second The token to check before. * @returns {boolean} True if there is only space between tokens, false * if there is anything other than whitespace between tokens. * @public */ isSpaceBetweenTokens(first, second) { const text = this.text.slice(first.range[1], second.range[0]); return /\s/.test(text.replace(/\/\*.*?\*\//g, "")); } /** * Converts a source text index into a (line, column) pair. * @param {number} index The index of a character in a file * @returns {Object} A {line, column} location object with a 0-indexed column * @public */ getLocFromIndex(index) { if (typeof index !== "number") { throw new TypeError("Expected `index` to be a number."); } if (index < 0 || index > this.text.length) { throw new RangeError(`Index out of range (requested index ${index}, but source text has length ${this.text.length}).`); } /* * For an argument of this.text.length, return the location one "spot" past the last character * of the file. If the last character is a linebreak, the location will be column 0 of the next * line; otherwise, the location will be in the next column on the same line. * * See getIndexFromLoc for the motivation for this special case. */ if (index === this.text.length) { return { line: this.lines.length, column: this.lines[this.lines.length - 1].length }; } /* * To figure out which line rangeIndex is on, determine the last index at which rangeIndex could * be inserted into lineIndices to keep the list sorted. */ const lineNumber = lodash.sortedLastIndex(this.lineStartIndices, index); return { line: lineNumber, column: index - this.lineStartIndices[lineNumber - 1] }; } /** * Converts a (line, column) pair into a range index. * @param {Object} loc A line/column location * @param {number} loc.line The line number of the location (1-indexed) * @param {number} loc.column The column number of the location (0-indexed) * @returns {number} The range index of the location in the file. * @public */ getIndexFromLoc(loc) { if (typeof loc !== "object" || typeof loc.line !== "number" || typeof loc.column !== "number") { throw new TypeError("Expected `loc` to be an object with numeric `line` and `column` properties."); } if (loc.line <= 0) { throw new RangeError(`Line number out of range (line ${loc.line} requested). Line numbers should be 1-based.`); } if (loc.line > this.lineStartIndices.length) { throw new RangeError(`Line number out of range (line ${loc.line} requested, but only ${this.lineStartIndices.length} lines present).`); } const lineStartIndex = this.lineStartIndices[loc.line - 1]; const lineEndIndex = loc.line === this.lineStartIndices.length ? this.text.length : this.lineStartIndices[loc.line]; const positionIndex = lineStartIndex + loc.column; /* * By design, getIndexFromLoc({ line: lineNum, column: 0 }) should return the start index of * the given line, provided that the line number is valid element of this.lines. Since the * last element of this.lines is an empty string for files with trailing newlines, add a * special case where getting the index for the first location after the end of the file * will return the length of the file, rather than throwing an error. This allows rules to * use getIndexFromLoc consistently without worrying about edge cases at the end of a file. */ if ( loc.line === this.lineStartIndices.length && positionIndex > lineEndIndex || loc.line < this.lineStartIndices.length && positionIndex >= lineEndIndex ) { throw new RangeError(`Column number out of range (column ${loc.column} requested, but the length of line ${loc.line} is ${lineEndIndex - lineStartIndex}).`); } return positionIndex; } } module.exports = SourceCode;
/** * @author gero3 / https://github.com/gero3 * @author tentone / https://github.com/tentone * * Requires opentype.js to be included in the project. * Loads TTF files and converts them into typeface JSON that can be used directly * to create THREE.Font objects. */ THREE.TTFLoader = function ( manager ) { this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager; this.reversed = false; }; THREE.TTFLoader.prototype = { constructor: THREE.TTFLoader, load: function ( url, onLoad, onProgress, onError ) { var scope = this; var loader = new THREE.FileLoader( this.manager ); loader.setPath( this.path ); loader.setResponseType( 'arraybuffer' ); loader.load( url, function ( buffer ) { onLoad( scope.parse( buffer ) ); }, onProgress, onError ); }, setPath: function ( value ) { this.path = value; return this; }, parse: function ( arraybuffer ) { function convert( font, reversed ) { var round = Math.round; var glyphs = {}; var scale = ( 100000 ) / ( ( font.unitsPerEm || 2048 ) * 72 ); for ( var i = 0; i < font.glyphs.length; i ++ ) { var glyph = font.glyphs.glyphs[ i ]; if ( glyph.unicode !== undefined ) { var token = { ha: round( glyph.advanceWidth * scale ), x_min: round( glyph.xMin * scale ), x_max: round( glyph.xMax * scale ), o: '' }; if ( reversed ) { glyph.path.commands = reverseCommands( glyph.path.commands ); } glyph.path.commands.forEach( function ( command, i ) { if ( command.type.toLowerCase() === 'c' ) { command.type = 'b'; } token.o += command.type.toLowerCase() + ' '; if ( command.x !== undefined && command.y !== undefined ) { token.o += round( command.x * scale ) + ' ' + round( command.y * scale ) + ' '; } if ( command.x1 !== undefined && command.y1 !== undefined ) { token.o += round( command.x1 * scale ) + ' ' + round( command.y1 * scale ) + ' '; } if ( command.x2 !== undefined && command.y2 !== undefined ) { token.o += round( command.x2 * scale ) + ' ' + round( command.y2 * scale ) + ' '; } } ); glyphs[ String.fromCharCode( glyph.unicode ) ] = token; } } return { glyphs: glyphs, familyName: font.familyName, ascender: round( font.ascender * scale ), descender: round( font.descender * scale ), underlinePosition: font.tables.post.underlinePosition, underlineThickness: font.tables.post.underlineThickness, boundingBox: { xMin: font.tables.head.xMin, xMax: font.tables.head.xMax, yMin: font.tables.head.yMin, yMax: font.tables.head.yMax }, resolution: 1000, original_font_information: font.tables.name }; } function reverseCommands( commands ) { var paths = []; var path; commands.forEach( function ( c ) { if ( c.type.toLowerCase() === 'm' ) { path = [ c ]; paths.push( path ); } else if ( c.type.toLowerCase() !== 'z' ) { path.push( c ); } } ); var reversed = []; paths.forEach( function ( p ) { var result = { type: 'm', x: p[ p.length - 1 ].x, y: p[ p.length - 1 ].y }; reversed.push( result ); for ( var i = p.length - 1; i > 0; i -- ) { var command = p[ i ]; var result = { type: command.type }; if ( command.x2 !== undefined && command.y2 !== undefined ) { result.x1 = command.x2; result.y1 = command.y2; result.x2 = command.x1; result.y2 = command.y1; } else if ( command.x1 !== undefined && command.y1 !== undefined ) { result.x1 = command.x1; result.y1 = command.y1; } result.x = p[ i - 1 ].x; result.y = p[ i - 1 ].y; reversed.push( result ); } } ); return reversed; } if ( typeof opentype === 'undefined' ) { console.warn( 'THREE.TTFLoader: The loader requires opentype.js. Make sure it\'s included before using the loader.' ); return null; } return convert( opentype.parse( arraybuffer ), this.reversed ); } };
define(["require","exports","module","system"],function(e,t,n){t.print=typeof print!="undefined"?print:function(){var t=e("system"),n=t.stdio;n.print.apply(n,arguments)},t.assert=function(e,n){e?t.print("PASS "+n,"pass"):t.print("FAIL "+n,"fail")}});
/* YUI 3.17.0 (build ce55cc9) Copyright 2014 Yahoo! Inc. All rights reserved. Licensed under the BSD License. http://yuilibrary.com/license/ */ YUI.add("lang/calendar-base_zh-Hans-CN",function(e){e.Intl.add("calendar-base","zh-Hans-CN",{very_short_weekdays:["\u65e5","\u4e00","\u4e8c","\u4e09","\u56db","\u4e94","\u516d"],first_weekday:0,weekends:[0,6]})},"3.17.0");
import Ember from 'ember'; export default Ember.Mixin.create({ queryParams: ["page", "perPage"], pageBinding: "content.page", totalPagesBinding: "content.totalPages", pagedContentBinding: "content" });
/*#__PURE__*/ React.createElement("div", null);
var BottomBar = require("../lib/ui/bottom-bar"); var cmdify = require("cmdify"); var loader = [ "/ Installing", "| Installing", "\\ Installing", "- Installing" ]; var i = 4; var ui = new BottomBar({ bottomBar: loader[i % 4] }); setInterval(function() { ui.updateBottomBar( loader[i++ % 4] ); }, 300 ); var spawn = require("child_process").spawn; var cmd = spawn(cmdify("npm"), [ "-g", "install", "inquirer" ], { stdio: "pipe" }); cmd.stdout.pipe( ui.log ); cmd.on( "close", function() { ui.updateBottomBar("Installation done!\n"); process.exit(); });
// // Copyright (c) Microsoft and contributors. 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. // // Module dependencies. var HeaderConstants = require('./../../../common/common').Constants.HeaderConstants; function DirectoryResult(name) { this.name = name; } DirectoryResult.parse = function (dirXml) { return new DirectoryResult(dirXml.Name); }; DirectoryResult.prototype.getPropertiesFromHeaders = function (headers) { var self = this; var setDirectoryPropertyFromHeaders = function (directoryProperty, headerProperty) { if (!self[directoryProperty] && headers[headerProperty.toLowerCase()]) { self[directoryProperty] = headers[headerProperty.toLowerCase()]; } }; setDirectoryPropertyFromHeaders('etag', HeaderConstants.ETAG); setDirectoryPropertyFromHeaders('lastModified', HeaderConstants.LAST_MODIFIED); setDirectoryPropertyFromHeaders('requestId', HeaderConstants.REQUEST_ID_HEADER); }; module.exports = DirectoryResult;
/** * @license * Visual Blocks Editor * * Copyright 2011 Google Inc. * https://developers.google.com/blockly/ * * 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 Components for creating connections between blocks. * @author fraser@google.com (Neil Fraser) */ 'use strict'; goog.provide('Blockly.Connection'); goog.provide('Blockly.ConnectionDB'); goog.require('goog.dom'); /** * Class for a connection between blocks. * @param {!Blockly.Block} source The block establishing this connection. * @param {number} type The type of the connection. * @constructor */ Blockly.Connection = function(source, type) { this.sourceBlock_ = source; this.targetConnection = null; this.type = type; this.x_ = 0; this.y_ = 0; // Shortcut for the databases for this connection's workspace. this.dbList_ = source.workspace.connectionDBList; this.hidden_ = !this.dbList_; this.inDB_ = false; }; /** * Sever all links to this connection (not including from the source object). */ Blockly.Connection.prototype.dispose = function() { if (this.targetConnection) { throw 'Disconnect connection before disposing of it.'; } if (this.inDB_) { this.dbList_[this.type].removeConnection_(this); } if (Blockly.highlightedConnection_ == this) { Blockly.highlightedConnection_ = null; } if (Blockly.localConnection_ == this) { Blockly.localConnection_ = null; } }; /** * Does the connection belong to a superior block (higher in the source stack)? * @return {boolean} True if connection faces down or right. */ Blockly.Connection.prototype.isSuperior = function() { return this.type == Blockly.INPUT_VALUE || this.type == Blockly.NEXT_STATEMENT; }; /** * Connect this connection to another connection. * @param {!Blockly.Connection} otherConnection Connection to connect to. */ Blockly.Connection.prototype.connect = function(otherConnection) { if (this.sourceBlock_ == otherConnection.sourceBlock_) { throw 'Attempted to connect a block to itself.'; } if (this.sourceBlock_.workspace !== otherConnection.sourceBlock_.workspace) { throw 'Blocks are on different workspaces.'; } if (Blockly.OPPOSITE_TYPE[this.type] != otherConnection.type) { throw 'Attempt to connect incompatible types.'; } if (this.type == Blockly.INPUT_VALUE || this.type == Blockly.OUTPUT_VALUE) { if (this.targetConnection) { // Can't make a value connection if male block is already connected. throw 'Source connection already connected (value).'; } else if (otherConnection.targetConnection) { // If female block is already connected, disconnect and bump the male. var orphanBlock = otherConnection.targetBlock(); orphanBlock.setParent(null); if (!orphanBlock.outputConnection) { throw 'Orphan block does not have an output connection.'; } // Attempt to reattach the orphan at the end of the newly inserted // block. Since this block may be a row, walk down to the end. var newBlock = this.sourceBlock_; var connection; while (connection = Blockly.Connection.singleConnection_( /** @type {!Blockly.Block} */ (newBlock), orphanBlock)) { // '=' is intentional in line above. if (connection.targetBlock()) { newBlock = connection.targetBlock(); } else { connection.connect(orphanBlock.outputConnection); orphanBlock = null; break; } } if (orphanBlock) { // Unable to reattach orphan. Bump it off to the side. setTimeout(function() { orphanBlock.outputConnection.bumpAwayFrom_(otherConnection); }, Blockly.BUMP_DELAY); } } } else { if (this.targetConnection) { throw 'Source connection already connected (block).'; } else if (otherConnection.targetConnection) { // Statement blocks may be inserted into the middle of a stack. if (this.type != Blockly.PREVIOUS_STATEMENT) { throw 'Can only do a mid-stack connection with the top of a block.'; } // Split the stack. var orphanBlock = otherConnection.targetBlock(); orphanBlock.setParent(null); if (!orphanBlock.previousConnection) { throw 'Orphan block does not have a previous connection.'; } // Attempt to reattach the orphan at the bottom of the newly inserted // block. Since this block may be a stack, walk down to the end. var newBlock = this.sourceBlock_; while (newBlock.nextConnection) { if (newBlock.nextConnection.targetConnection) { newBlock = newBlock.getNextBlock(); } else { if (orphanBlock.previousConnection.checkType_( newBlock.nextConnection)) { newBlock.nextConnection.connect(orphanBlock.previousConnection); orphanBlock = null; } break; } } if (orphanBlock) { // Unable to reattach orphan. Bump it off to the side. setTimeout(function() { orphanBlock.previousConnection.bumpAwayFrom_(otherConnection); }, Blockly.BUMP_DELAY); } } } // Determine which block is superior (higher in the source stack). var parentBlock, childBlock; if (this.isSuperior()) { // Superior block. parentBlock = this.sourceBlock_; childBlock = otherConnection.sourceBlock_; } else { // Inferior block. parentBlock = otherConnection.sourceBlock_; childBlock = this.sourceBlock_; } // Establish the connections. this.targetConnection = otherConnection; otherConnection.targetConnection = this; // Demote the inferior block so that one is a child of the superior one. childBlock.setParent(parentBlock); if (parentBlock.rendered) { parentBlock.updateDisabled(); } if (childBlock.rendered) { childBlock.updateDisabled(); } if (parentBlock.rendered && childBlock.rendered) { if (this.type == Blockly.NEXT_STATEMENT || this.type == Blockly.PREVIOUS_STATEMENT) { // Child block may need to square off its corners if it is in a stack. // Rendering a child will render its parent. childBlock.render(); } else { // Child block does not change shape. Rendering the parent node will // move its connected children into position. parentBlock.render(); } } }; /** * Does the given block have one and only one connection point that will accept * the orphaned block? * @param {!Blockly.Block} block The superior block. * @param {!Blockly.Block} orphanBlock The inferior block. * @return {Blockly.Connection} The suitable connection point on 'block', * or null. * @private */ Blockly.Connection.singleConnection_ = function(block, orphanBlock) { var connection = false; for (var x = 0; x < block.inputList.length; x++) { var thisConnection = block.inputList[x].connection; if (thisConnection && thisConnection.type == Blockly.INPUT_VALUE && orphanBlock.outputConnection.checkType_(thisConnection)) { if (connection) { return null; // More than one connection. } connection = thisConnection; } } return connection; }; /** * Disconnect this connection. */ Blockly.Connection.prototype.disconnect = function() { var otherConnection = this.targetConnection; if (!otherConnection) { throw 'Source connection not connected.'; } else if (otherConnection.targetConnection != this) { throw 'Target connection not connected to source connection.'; } otherConnection.targetConnection = null; this.targetConnection = null; // Rerender the parent so that it may reflow. var parentBlock, childBlock; if (this.isSuperior()) { // Superior block. parentBlock = this.sourceBlock_; childBlock = otherConnection.sourceBlock_; } else { // Inferior block. parentBlock = otherConnection.sourceBlock_; childBlock = this.sourceBlock_; } if (parentBlock.rendered) { parentBlock.render(); } if (childBlock.rendered) { childBlock.updateDisabled(); childBlock.render(); } }; /** * Returns the block that this connection connects to. * @return {Blockly.Block} The connected block or null if none is connected. */ Blockly.Connection.prototype.targetBlock = function() { if (this.targetConnection) { return this.targetConnection.sourceBlock_; } return null; }; /** * Move the block(s) belonging to the connection to a point where they don't * visually interfere with the specified connection. * @param {!Blockly.Connection} staticConnection The connection to move away * from. * @private */ Blockly.Connection.prototype.bumpAwayFrom_ = function(staticConnection) { if (Blockly.dragMode_ != 0) { // Don't move blocks around while the user is doing the same. return; } // Move the root block. var rootBlock = this.sourceBlock_.getRootBlock(); if (rootBlock.isInFlyout) { // Don't move blocks around in a flyout. return; } var reverse = false; if (!rootBlock.isMovable()) { // Can't bump an uneditable block away. // Check to see if the other block is movable. rootBlock = staticConnection.sourceBlock_.getRootBlock(); if (!rootBlock.isMovable()) { return; } // Swap the connections and move the 'static' connection instead. staticConnection = this; reverse = true; } // Raise it to the top for extra visibility. rootBlock.getSvgRoot().parentNode.appendChild(rootBlock.getSvgRoot()); var dx = (staticConnection.x_ + Blockly.SNAP_RADIUS) - this.x_; var dy = (staticConnection.y_ + Blockly.SNAP_RADIUS) - this.y_; if (reverse) { // When reversing a bump due to an uneditable block, bump up. dy = -dy; } if (Blockly.RTL) { dx = -dx; } rootBlock.moveBy(dx, dy); }; /** * Change the connection's coordinates. * @param {number} x New absolute x coordinate. * @param {number} y New absolute y coordinate. */ Blockly.Connection.prototype.moveTo = function(x, y) { // Remove it from its old location in the database (if already present) if (this.inDB_) { this.dbList_[this.type].removeConnection_(this); } this.x_ = x; this.y_ = y; // Insert it into its new location in the database. if (!this.hidden_) { this.dbList_[this.type].addConnection_(this); } }; /** * Change the connection's coordinates. * @param {number} dx Change to x coordinate. * @param {number} dy Change to y coordinate. */ Blockly.Connection.prototype.moveBy = function(dx, dy) { this.moveTo(this.x_ + dx, this.y_ + dy); }; /** * Add highlighting around this connection. */ Blockly.Connection.prototype.highlight = function() { var steps; if (this.type == Blockly.INPUT_VALUE || this.type == Blockly.OUTPUT_VALUE) { var tabWidth = Blockly.RTL ? -Blockly.BlockSvg.TAB_WIDTH : Blockly.BlockSvg.TAB_WIDTH; steps = 'm 0,0 v 5 c 0,10 ' + -tabWidth + ',-8 ' + -tabWidth + ',7.5 s ' + tabWidth + ',-2.5 ' + tabWidth + ',7.5 v 5'; } else { if (Blockly.RTL) { steps = 'm 20,0 h -5 ' + Blockly.BlockSvg.NOTCH_PATH_RIGHT + ' h -5'; } else { steps = 'm -20,0 h 5 ' + Blockly.BlockSvg.NOTCH_PATH_LEFT + ' h 5'; } } var xy = this.sourceBlock_.getRelativeToSurfaceXY(); var x = this.x_ - xy.x; var y = this.y_ - xy.y; Blockly.Connection.highlightedPath_ = Blockly.createSvgElement('path', {'class': 'blocklyHighlightedConnectionPath', 'd': steps, transform: 'translate(' + x + ', ' + y + ')'}, this.sourceBlock_.getSvgRoot()); }; /** * Remove the highlighting around this connection. */ Blockly.Connection.prototype.unhighlight = function() { goog.dom.removeNode(Blockly.Connection.highlightedPath_); delete Blockly.Connection.highlightedPath_; }; /** * Move the blocks on either side of this connection right next to each other. * @private */ Blockly.Connection.prototype.tighten_ = function() { var dx = Math.round(this.targetConnection.x_ - this.x_); var dy = Math.round(this.targetConnection.y_ - this.y_); if (dx != 0 || dy != 0) { var block = this.targetBlock(); var svgRoot = block.getSvgRoot(); if (!svgRoot) { throw 'block is not rendered.'; } var xy = Blockly.getRelativeXY_(svgRoot); block.getSvgRoot().setAttribute('transform', 'translate(' + (xy.x - dx) + ', ' + (xy.y - dy) + ')'); block.moveConnections_(-dx, -dy); } }; /** * Find the closest compatible connection to this connection. * @param {number} maxLimit The maximum radius to another connection. * @param {number} dx Horizontal offset between this connection's location * in the database and the current location (as a result of dragging). * @param {number} dy Vertical offset between this connection's location * in the database and the current location (as a result of dragging). * @return {!Object} Contains two properties: 'connection' which is either * another connection or null, and 'radius' which is the distance. */ Blockly.Connection.prototype.closest = function(maxLimit, dx, dy) { if (this.targetConnection) { // Don't offer to connect to a connection that's already connected. return {connection: null, radius: maxLimit}; } // Determine the opposite type of connection. var oppositeType = Blockly.OPPOSITE_TYPE[this.type]; var db = this.dbList_[oppositeType]; // Since this connection is probably being dragged, add the delta. var currentX = this.x_ + dx; var currentY = this.y_ + dy; // Binary search to find the closest y location. var pointerMin = 0; var pointerMax = db.length - 2; var pointerMid = pointerMax; while (pointerMin < pointerMid) { if (db[pointerMid].y_ < currentY) { pointerMin = pointerMid; } else { pointerMax = pointerMid; } pointerMid = Math.floor((pointerMin + pointerMax) / 2); } // Walk forward and back on the y axis looking for the closest x,y point. pointerMin = pointerMid; pointerMax = pointerMid; var closestConnection = null; var sourceBlock = this.sourceBlock_; var thisConnection = this; if (db.length) { while (pointerMin >= 0 && checkConnection_(pointerMin)) { pointerMin--; } do { pointerMax++; } while (pointerMax < db.length && checkConnection_(pointerMax)); } /** * Computes if the current connection is within the allowed radius of another * connection. * This function is a closure and has access to outside variables. * @param {number} yIndex The other connection's index in the database. * @return {boolean} True if the search needs to continue: either the current * connection's vertical distance from the other connection is less than * the allowed radius, or if the connection is not compatible. * @private */ function checkConnection_(yIndex) { var connection = db[yIndex]; if (connection.type == Blockly.OUTPUT_VALUE || connection.type == Blockly.PREVIOUS_STATEMENT) { // Don't offer to connect an already connected left (male) value plug to // an available right (female) value plug. Don't offer to connect the // bottom of a statement block to one that's already connected. if (connection.targetConnection) { return true; } } // Offering to connect the top of a statement block to an already connected // connection is ok, we'll just insert it into the stack. // Offering to connect the left (male) of a value block to an already // connected value pair is ok, we'll splice it in. // However, don't offer to splice into an unmovable block. if (connection.type == Blockly.INPUT_VALUE && connection.targetConnection && !connection.targetBlock().isMovable()) { return true; } // Do type checking. if (!thisConnection.checkType_(connection)) { return true; } // Don't let blocks try to connect to themselves or ones they nest. var targetSourceBlock = connection.sourceBlock_; do { if (sourceBlock == targetSourceBlock) { return true; } targetSourceBlock = targetSourceBlock.getParent(); } while (targetSourceBlock); // Only connections within the maxLimit radius. var dx = currentX - db[yIndex].x_; var dy = currentY - db[yIndex].y_; var r = Math.sqrt(dx * dx + dy * dy); if (r <= maxLimit) { closestConnection = db[yIndex]; maxLimit = r; } return dy < maxLimit; } return {connection: closestConnection, radius: maxLimit}; }; /** * Is this connection compatible with another connection with respect to the * value type system. E.g. square_root("Hello") is not compatible. * @param {!Blockly.Connection} otherConnection Connection to compare against. * @return {boolean} True if the connections share a type. * @private */ Blockly.Connection.prototype.checkType_ = function(otherConnection) { // Don't split a connection where both sides are immovable. var thisTargetBlock = this.targetBlock(); if (thisTargetBlock && !thisTargetBlock.isMovable() && !this.sourceBlock_.isMovable()) { return false; } var otherTargetBlock = otherConnection.targetBlock(); if (otherTargetBlock && !otherTargetBlock.isMovable() && !otherConnection.sourceBlock_.isMovable()) { return false; } if (!this.check_ || !otherConnection.check_) { // One or both sides are promiscuous enough that anything will fit. return true; } // Find any intersection in the check lists. for (var x = 0; x < this.check_.length; x++) { if (otherConnection.check_.indexOf(this.check_[x]) != -1) { return true; } } // No intersection. return false; }; /** * Change a connection's compatibility. * @param {*} check Compatible value type or list of value types. * Null if all types are compatible. * @return {!Blockly.Connection} The connection being modified * (to allow chaining). */ Blockly.Connection.prototype.setCheck = function(check) { if (check) { // Ensure that check is in an array. if (!goog.isArray(check)) { check = [check]; } this.check_ = check; // The new value type may not be compatible with the existing connection. if (this.targetConnection && !this.checkType_(this.targetConnection)) { if (this.isSuperior()) { this.targetBlock().setParent(null); } else { this.sourceBlock_.setParent(null); } // Bump away. this.sourceBlock_.bumpNeighbours_(); } } else { this.check_ = null; } return this; }; /** * Find all nearby compatible connections to this connection. * Type checking does not apply, since this function is used for bumping. * @param {number} maxLimit The maximum radius to another connection. * @return {!Array.<Blockly.Connection>} List of connections. * @private */ Blockly.Connection.prototype.neighbours_ = function(maxLimit) { // Determine the opposite type of connection. var oppositeType = Blockly.OPPOSITE_TYPE[this.type]; var db = this.dbList_[oppositeType]; var currentX = this.x_; var currentY = this.y_; // Binary search to find the closest y location. var pointerMin = 0; var pointerMax = db.length - 2; var pointerMid = pointerMax; while (pointerMin < pointerMid) { if (db[pointerMid].y_ < currentY) { pointerMin = pointerMid; } else { pointerMax = pointerMid; } pointerMid = Math.floor((pointerMin + pointerMax) / 2); } // Walk forward and back on the y axis looking for the closest x,y point. pointerMin = pointerMid; pointerMax = pointerMid; var neighbours = []; var sourceBlock = this.sourceBlock_; if (db.length) { while (pointerMin >= 0 && checkConnection_(pointerMin)) { pointerMin--; } do { pointerMax++; } while (pointerMax < db.length && checkConnection_(pointerMax)); } /** * Computes if the current connection is within the allowed radius of another * connection. * This function is a closure and has access to outside variables. * @param {number} yIndex The other connection's index in the database. * @return {boolean} True if the current connection's vertical distance from * the other connection is less than the allowed radius. */ function checkConnection_(yIndex) { var dx = currentX - db[yIndex].x_; var dy = currentY - db[yIndex].y_; var r = Math.sqrt(dx * dx + dy * dy); if (r <= maxLimit) { neighbours.push(db[yIndex]); } return dy < maxLimit; } return neighbours; }; /** * Set whether this connections is hidden (not tracked in a database) or not. * @param {boolean} hidden True if connection is hidden. */ Blockly.Connection.prototype.setHidden = function(hidden) { this.hidden_ = hidden; if (hidden && this.inDB_) { this.dbList_[this.type].removeConnection_(this); } else if (!hidden && !this.inDB_) { this.dbList_[this.type].addConnection_(this); } }; /** * Hide this connection, as well as all down-stream connections on any block * attached to this connection. This happens when a block is collapsed. * Also hides down-stream comments. */ Blockly.Connection.prototype.hideAll = function() { this.setHidden(true); if (this.targetConnection) { var blocks = this.targetBlock().getDescendants(); for (var b = 0; b < blocks.length; b++) { var block = blocks[b]; // Hide all connections of all children. var connections = block.getConnections_(true); for (var c = 0; c < connections.length; c++) { connections[c].setHidden(true); } // Close all bubbles of all children. var icons = block.getIcons(); for (var x = 0; x < icons.length; x++) { icons[x].setVisible(false); } } } }; /** * Unhide this connection, as well as all down-stream connections on any block * attached to this connection. This happens when a block is expanded. * Also unhides down-stream comments. * @return {!Array.<!Blockly.Block>} List of blocks to render. */ Blockly.Connection.prototype.unhideAll = function() { this.setHidden(false); // All blocks that need unhiding must be unhidden before any rendering takes // place, since rendering requires knowing the dimensions of lower blocks. // Also, since rendering a block renders all its parents, we only need to // render the leaf nodes. var renderList = []; if (this.type != Blockly.INPUT_VALUE && this.type != Blockly.NEXT_STATEMENT) { // Only spider down. return renderList; } var block = this.targetBlock(); if (block) { var connections; if (block.isCollapsed()) { // This block should only be partially revealed since it is collapsed. connections = []; block.outputConnection && connections.push(block.outputConnection); block.nextConnection && connections.push(block.nextConnection); block.previousConnection && connections.push(block.previousConnection); } else { // Show all connections of this block. connections = block.getConnections_(true); } for (var c = 0; c < connections.length; c++) { renderList.push.apply(renderList, connections[c].unhideAll()); } if (renderList.length == 0) { // Leaf block. renderList[0] = block; } } return renderList; }; /** * Database of connections. * Connections are stored in order of their vertical component. This way * connections in an area may be looked up quickly using a binary search. * @constructor */ Blockly.ConnectionDB = function() { }; Blockly.ConnectionDB.prototype = new Array(); /** * Don't inherit the constructor from Array. * @type {!Function} */ Blockly.ConnectionDB.constructor = Blockly.ConnectionDB; /** * Add a connection to the database. Must not already exist in DB. * @param {!Blockly.Connection} connection The connection to be added. * @private */ Blockly.ConnectionDB.prototype.addConnection_ = function(connection) { if (connection.inDB_) { throw 'Connection already in database.'; } if (connection.sourceBlock_.isInFlyout) { // Don't bother maintaining a database of connections in a flyout. return; } // Insert connection using binary search. var pointerMin = 0; var pointerMax = this.length; while (pointerMin < pointerMax) { var pointerMid = Math.floor((pointerMin + pointerMax) / 2); if (this[pointerMid].y_ < connection.y_) { pointerMin = pointerMid + 1; } else if (this[pointerMid].y_ > connection.y_) { pointerMax = pointerMid; } else { pointerMin = pointerMid; break; } } this.splice(pointerMin, 0, connection); connection.inDB_ = true; }; /** * Remove a connection from the database. Must already exist in DB. * @param {!Blockly.Connection} connection The connection to be removed. * @private */ Blockly.ConnectionDB.prototype.removeConnection_ = function(connection) { if (!connection.inDB_) { throw 'Connection not in database.'; } connection.inDB_ = false; // Find the connection using a binary search. var pointerMin = 0; var pointerMax = this.length - 2; var pointerMid = pointerMax; while (pointerMin < pointerMid) { if (this[pointerMid].y_ < connection.y_) { pointerMin = pointerMid; } else { pointerMax = pointerMid; } pointerMid = Math.floor((pointerMin + pointerMax) / 2); } // Walk forward and back on the y axis looking for the connection. // When found, splice it out of the array. pointerMin = pointerMid; pointerMax = pointerMid; while (pointerMin >= 0 && this[pointerMin].y_ == connection.y_) { if (this[pointerMin] == connection) { this.splice(pointerMin, 1); return; } pointerMin--; } do { if (this[pointerMax] == connection) { this.splice(pointerMax, 1); return; } pointerMax++; } while (pointerMax < this.length && this[pointerMax].y_ == connection.y_); throw 'Unable to find connection in connectionDB.'; }; /** * Initialize a set of connection DBs for a specified workspace. * @param {!Blockly.Workspace} workspace The workspace this DB is for. */ Blockly.ConnectionDB.init = function(workspace) { // Create four databases, one for each connection type. var dbList = []; dbList[Blockly.INPUT_VALUE] = new Blockly.ConnectionDB(); dbList[Blockly.OUTPUT_VALUE] = new Blockly.ConnectionDB(); dbList[Blockly.NEXT_STATEMENT] = new Blockly.ConnectionDB(); dbList[Blockly.PREVIOUS_STATEMENT] = new Blockly.ConnectionDB(); workspace.connectionDBList = dbList; };
// [VexFlow](http://vexflow.com) - Copyright (c) Mohit Muthanna 2010. // // ## Description // // This class implements vibratos. Vex.Flow.Vibrato = (function() { function Vibrato() { this.init(); } Vibrato.CATEGORY = "vibratos"; var Modifier = Vex.Flow.Modifier; // ## Static Methods // Arrange vibratos inside a `ModifierContext`. Vibrato.format = function(vibratos, state, context) { if (!vibratos || vibratos.length === 0) return false; var text_line = state.text_line; var width = 0; var shift = state.right_shift - 7; // If there's a bend, drop the text line var bends = context.getModifiers(Vex.Flow.Bend.CATEGORY); if (bends && bends.length > 0) { text_line--; } // Format Vibratos for (var i = 0; i < vibratos.length; ++i) { var vibrato = vibratos[i]; vibrato.setXShift(shift); vibrato.setTextLine(text_line); width += vibrato.getWidth(); shift += width; } state.right_shift += width; state.text_line += 1; return true; } // ## Prototype Methods Vex.Inherit(Vibrato, Modifier, { init: function() { var superclass = Vex.Flow.Vibrato.superclass; superclass.init.call(this); this.harsh = false; this.position = Vex.Flow.Modifier.Position.RIGHT; this.render_options = { vibrato_width: 20, wave_height: 6, wave_width: 4, wave_girth: 2 }; this.setVibratoWidth(this.render_options.vibrato_width); }, setHarsh: function(harsh) { this.harsh = harsh; return this; }, setVibratoWidth: function(width) { this.vibrato_width = width; this.setWidth(this.vibrato_width); return this; }, draw: function() { if (!this.context) throw new Vex.RERR("NoContext", "Can't draw vibrato without a context."); if (!this.note) throw new Vex.RERR("NoNoteForVibrato", "Can't draw vibrato without an attached note."); var start = this.note.getModifierStartXY(Vex.Flow.Modifier.Position.RIGHT, this.index); var ctx = this.context; var that = this; var vibrato_width = this.vibrato_width; function renderVibrato(x, y) { var wave_width = that.render_options.wave_width; var wave_girth = that.render_options.wave_girth; var wave_height = that.render_options.wave_height; var num_waves = vibrato_width / wave_width; ctx.beginPath(); var i; if (that.harsh) { ctx.moveTo(x, y + wave_girth + 1); for (i = 0; i < num_waves / 2; ++i) { ctx.lineTo(x + wave_width, y - (wave_height / 2)); x += wave_width; ctx.lineTo(x + wave_width, y + (wave_height / 2)); x += wave_width; } for (i = 0; i < num_waves / 2; ++i) { ctx.lineTo(x - wave_width, (y - (wave_height / 2)) + wave_girth + 1); x -= wave_width; ctx.lineTo(x - wave_width, (y + (wave_height / 2)) + wave_girth + 1); x -= wave_width; } ctx.fill(); } else { ctx.moveTo(x, y + wave_girth); for (i = 0; i < num_waves / 2; ++i) { ctx.quadraticCurveTo(x + (wave_width / 2), y - (wave_height / 2), x + wave_width, y); x += wave_width; ctx.quadraticCurveTo(x + (wave_width / 2), y + (wave_height / 2), x + wave_width, y); x += wave_width; } for (i = 0; i < num_waves / 2; ++i) { ctx.quadraticCurveTo( x - (wave_width / 2), (y + (wave_height / 2)) + wave_girth, x - wave_width, y + wave_girth); x -= wave_width; ctx.quadraticCurveTo( x - (wave_width / 2), (y - (wave_height / 2)) + wave_girth, x - wave_width, y + wave_girth); x -= wave_width; } ctx.fill(); } } var vx = start.x + this.x_shift; var vy = this.note.getYForTopText(this.text_line) + 2; renderVibrato(vx, vy); } }); return Vibrato; }());
version https://git-lfs.github.com/spec/v1 oid sha256:498ba5a89f8fe3e5627189b345eecaead4d7daa943daa9d714329d72a690dc16 size 287
/** * Interaction for the pages templates * * @author Matthias Mullie <forkcms@mullie.eu> */ jsBackend.template = { // default position names defaultPositions: new Array('', 'main', 'left', 'right', 'top'), /** * Kind of constructor */ init: function() { // add first default position if($('#position1').length == 0) jsBackend.template.addPosition(); // first position can't be removed $('#position1').parent().find('.deletePosition').remove(); // add handlers $(document).on('click', '#addPosition', jsBackend.template.addPosition); $(document).on('click', '.addBlock', jsBackend.template.addBlock); $(document).on('click', '.deletePosition', jsBackend.template.deletePosition); $(document).on('click', '.deleteBlock', jsBackend.template.deleteBlock); }, /** * Add a block to a position */ addBlock: function(e) { // prevent default event action e.preventDefault(); // clone default extras dropdown var blockContainer = $('#type00').parent().clone(); // fetch position & block index var positionIndex = $(this).parent().prevAll('input[id^=position]').attr('id').replace('position', ''); var blockIndex = $(this).prevAll('div.defaultBlock').length; // update for id & name $('#type00', blockContainer).attr('id', 'type' + positionIndex + blockIndex).attr('name', 'type_' + positionIndex + '_' + blockIndex); // add to dom blockContainer.insertBefore($(this)); }, /** * Add a position */ addPosition: function(e) { // prevent default event action if(e) e.preventDefault(); // clone default position var positionContainer = $('#position0').parent().clone(); // set new index var index = $('#positionsList .position').length; // update for (label), id & name (input) $('input[id^=position]', positionContainer).attr('id', 'position' + index).attr('name', 'position_' + index); $('label[for^=position]', positionContainer).attr('for', 'position' + index); // remove default blocks $('.defaultBlocks > *:not(a.addBlock)', positionContainer).remove(); // update default name $('#position' + index, positionContainer).val(jsBackend.template.defaultPositions[index]); // show position positionContainer.show(); // add to dom positionContainer.insertAfter($('#positionsList .position:last')); }, /** * Delete a block in a position */ deleteBlock: function(e) { // prevent default event action e.preventDefault(); // get blocks container var blocksContainer = $(this).parent().parent(); // delete container $(this).parent().remove(); // loop all remaining blocks $('.defaultBlock', blocksContainer).each(function(i) { // fetch position & block index var positionIndex = $(this).parent().prevAll('input[id^=position]').attr('id').replace('position', ''); var blockIndex = $(this).prevAll('div.defaultBlock').length; // update for id & name $('select[id^=type]', this).attr('id', 'type' + positionIndex + blockIndex).attr('name', 'type_' + positionIndex + '_' + blockIndex); }); }, /** * Delete a position */ deletePosition: function(e) { // prevent default event action e.preventDefault(); // get positions container var positionsContainer = $(this).parent().parent().parent(); // delete container $(this).parent().parent().remove(); // loop all remaining positions $('.position', positionsContainer).each(function(i) { // fetch position index var positionIndex = i; // update for (label), id & name (input) $('input[id^=position]', this).attr('id', 'position' + positionIndex).attr('name', 'position_' + positionIndex); $('label[for^=position]', this).attr('for', 'position' + positionIndex); // loop all blocks $('.defaultBlock', this).each(function(i) { // fetch block index var blockIndex = $(this).prevAll('div.defaultBlock').length; // update for id & name $('select[id^=type]', this).attr('id', 'type' + positionIndex + blockIndex).attr('name', 'type_' + positionIndex + '_' + blockIndex); }); }); } } $(jsBackend.template.init);
"use strict"; exports.__esModule = true; exports.is = is; exports.isType = isType; exports.shallowEqual = shallowEqual; exports.appendToMemberExpression = appendToMemberExpression; exports.prependToMemberExpression = prependToMemberExpression; exports.ensureBlock = ensureBlock; exports.clone = clone; exports.cloneDeep = cloneDeep; exports.buildMatchMemberExpression = buildMatchMemberExpression; exports.removeComments = removeComments; exports.inheritsComments = inheritsComments; exports.inherits = inherits; // istanbul ignore next function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } var _toFastProperties = require("to-fast-properties"); var _toFastProperties2 = _interopRequireDefault(_toFastProperties); var _lodashArrayCompact = require("lodash/array/compact"); var _lodashArrayCompact2 = _interopRequireDefault(_lodashArrayCompact); var _lodashObjectAssign = require("lodash/object/assign"); var _lodashObjectAssign2 = _interopRequireDefault(_lodashObjectAssign); var _lodashCollectionEach = require("lodash/collection/each"); var _lodashCollectionEach2 = _interopRequireDefault(_lodashCollectionEach); var _lodashArrayUniq = require("lodash/array/uniq"); var _lodashArrayUniq2 = _interopRequireDefault(_lodashArrayUniq); require("./definitions/init"); var _definitions = require("./definitions"); var t = exports; /** * Registers `is[Type]` and `assert[Type]` generated functions for a given `type`. * Pass `skipAliasCheck` to force it to directly compare `node.type` with `type`. */ function registerType(type, skipAliasCheck) { var is = t["is" + type] = function (node, opts) { return t.is(type, node, opts, skipAliasCheck); }; t["assert" + type] = function (node, opts) { opts = opts || {}; if (!is(node, opts)) { throw new Error("Expected type " + JSON.stringify(type) + " with option " + JSON.stringify(opts)); } }; } /** * Constants. */ var STATEMENT_OR_BLOCK_KEYS = ["consequent", "body", "alternate"]; exports.STATEMENT_OR_BLOCK_KEYS = STATEMENT_OR_BLOCK_KEYS; var FLATTENABLE_KEYS = ["body", "expressions"]; exports.FLATTENABLE_KEYS = FLATTENABLE_KEYS; var FOR_INIT_KEYS = ["left", "init"]; exports.FOR_INIT_KEYS = FOR_INIT_KEYS; var COMMENT_KEYS = ["leadingComments", "trailingComments", "innerComments"]; exports.COMMENT_KEYS = COMMENT_KEYS; var INHERIT_KEYS = { optional: ["typeAnnotation", "typeParameters", "returnType"], force: ["_scopeInfo", "_paths", "start", "loc", "end"] }; exports.INHERIT_KEYS = INHERIT_KEYS; var BOOLEAN_NUMBER_BINARY_OPERATORS = [">", "<", ">=", "<="]; exports.BOOLEAN_NUMBER_BINARY_OPERATORS = BOOLEAN_NUMBER_BINARY_OPERATORS; var EQUALITY_BINARY_OPERATORS = ["==", "===", "!=", "!=="]; exports.EQUALITY_BINARY_OPERATORS = EQUALITY_BINARY_OPERATORS; var COMPARISON_BINARY_OPERATORS = EQUALITY_BINARY_OPERATORS.concat(["in", "instanceof"]); exports.COMPARISON_BINARY_OPERATORS = COMPARISON_BINARY_OPERATORS; var BOOLEAN_BINARY_OPERATORS = [].concat(COMPARISON_BINARY_OPERATORS, BOOLEAN_NUMBER_BINARY_OPERATORS); exports.BOOLEAN_BINARY_OPERATORS = BOOLEAN_BINARY_OPERATORS; var NUMBER_BINARY_OPERATORS = ["-", "/", "*", "**", "&", "|", ">>", ">>>", "<<", "^"]; exports.NUMBER_BINARY_OPERATORS = NUMBER_BINARY_OPERATORS; var BOOLEAN_UNARY_OPERATORS = ["delete", "!"]; exports.BOOLEAN_UNARY_OPERATORS = BOOLEAN_UNARY_OPERATORS; var NUMBER_UNARY_OPERATORS = ["+", "-", "++", "--", "~"]; exports.NUMBER_UNARY_OPERATORS = NUMBER_UNARY_OPERATORS; var STRING_UNARY_OPERATORS = ["typeof"]; exports.STRING_UNARY_OPERATORS = STRING_UNARY_OPERATORS; exports.VISITOR_KEYS = _definitions.VISITOR_KEYS; /** * Registers `is[Type]` and `assert[Type]` for all types. */ exports.BUILDER_KEYS = _definitions.BUILDER_KEYS; exports.ALIAS_KEYS = _definitions.ALIAS_KEYS; _lodashCollectionEach2["default"](t.VISITOR_KEYS, function (keys, type) { registerType(type, true); }); /** * Flip `ALIAS_KEYS` for faster access in the reverse direction. */ t.FLIPPED_ALIAS_KEYS = {}; _lodashCollectionEach2["default"](t.ALIAS_KEYS, function (aliases, type) { _lodashCollectionEach2["default"](aliases, function (alias) { var types = t.FLIPPED_ALIAS_KEYS[alias] = t.FLIPPED_ALIAS_KEYS[alias] || []; types.push(type); }); }); /** * Registers `is[Alias]` and `assert[Alias]` functions for all aliases. */ _lodashCollectionEach2["default"](t.FLIPPED_ALIAS_KEYS, function (types, type) { t[type.toUpperCase() + "_TYPES"] = types; registerType(type, false); }); var TYPES = Object.keys(t.VISITOR_KEYS).concat(Object.keys(t.FLIPPED_ALIAS_KEYS)); /** * Returns whether `node` is of given `type`. * * For better performance, use this instead of `is[Type]` when `type` is unknown. * Optionally, pass `skipAliasCheck` to directly compare `node.type` with `type`. */ // @TODO should `skipAliasCheck` be removed? exports.TYPES = TYPES; function is(type, node, opts, skipAliasCheck) { if (!node) return false; var matches = isType(node.type, type); if (!matches) return false; if (typeof opts === "undefined") { return true; } else { return t.shallowEqual(node, opts); } } /** * Test if a `nodeType` is a `targetType` or if `targetType` is an alias of `nodeType`. */ function isType(nodeType, targetType) { if (nodeType === targetType) return true; var aliases = t.FLIPPED_ALIAS_KEYS[targetType]; if (aliases) { if (aliases[0] === nodeType) return true; var _arr = aliases; for (var _i = 0; _i < _arr.length; _i++) { var alias = _arr[_i]; if (nodeType === alias) return true; } } return false; } /** * [Please add a description.] */ _lodashCollectionEach2["default"](t.VISITOR_KEYS, function (keys, type) { if (t.BUILDER_KEYS[type]) return; var defs = {}; _lodashCollectionEach2["default"](keys, function (key) { defs[key] = null; }); t.BUILDER_KEYS[type] = defs; }); /** * [Please add a description.] */ _lodashCollectionEach2["default"](t.BUILDER_KEYS, function (keys, type) { var builder = function builder() { var node = {}; node.type = type; var i = 0; for (var key in keys) { var arg = arguments[i++]; if (arg === undefined) arg = keys[key]; node[key] = arg; } return node; }; t[type] = builder; t[type[0].toLowerCase() + type.slice(1)] = builder; }); /** * Test if an object is shallowly equal. */ function shallowEqual(actual, expected) { var keys = Object.keys(expected); var _arr2 = keys; for (var _i2 = 0; _i2 < _arr2.length; _i2++) { var key = _arr2[_i2]; if (actual[key] !== expected[key]) { return false; } } return true; } /** * Append a node to a member expression. */ function appendToMemberExpression(member, append, computed) { member.object = t.memberExpression(member.object, member.property, member.computed); member.property = append; member.computed = !!computed; return member; } /** * Prepend a node to a member expression. */ function prependToMemberExpression(member, prepend) { member.object = t.memberExpression(prepend, member.object); return member; } /** * Ensure the `key` (defaults to "body") of a `node` is a block. * Casting it to a block if it is not. */ function ensureBlock(node) { var key = arguments.length <= 1 || arguments[1] === undefined ? "body" : arguments[1]; return node[key] = t.toBlock(node[key], node); } /** * Create a shallow clone of a `node` excluding `_private` properties. */ function clone(node) { var newNode = {}; for (var key in node) { if (key[0] === "_") continue; newNode[key] = node[key]; } return newNode; } /** * Create a deep clone of a `node` and all of it's child nodes * exluding `_private` properties. */ function cloneDeep(node) { var newNode = {}; for (var key in node) { if (key[0] === "_") continue; var val = node[key]; if (val) { if (val.type) { val = t.cloneDeep(val); } else if (Array.isArray(val)) { val = val.map(t.cloneDeep); } } newNode[key] = val; } return newNode; } /** * Build a function that when called will return whether or not the * input `node` `MemberExpression` matches the input `match`. * * For example, given the match `React.createClass` it would match the * parsed nodes of `React.createClass` and `React["createClass"]`. */ function buildMatchMemberExpression(match, allowPartial) { var parts = match.split("."); return function (member) { // not a member expression if (!t.isMemberExpression(member)) return false; var search = [member]; var i = 0; while (search.length) { var node = search.shift(); if (allowPartial && i === parts.length) { return true; } if (t.isIdentifier(node)) { // this part doesn't match if (parts[i] !== node.name) return false; } else if (t.isLiteral(node)) { // this part doesn't match if (parts[i] !== node.value) return false; } else if (t.isMemberExpression(node)) { if (node.computed && !t.isLiteral(node.property)) { // we can't deal with this return false; } else { search.push(node.object); search.push(node.property); continue; } } else { // we can't deal with this return false; } // too many parts if (++i > parts.length) { return false; } } return true; }; } /** * Remove comment properties from a node. */ function removeComments(node) { var _arr3 = COMMENT_KEYS; for (var _i3 = 0; _i3 < _arr3.length; _i3++) { var key = _arr3[_i3]; delete node[key]; } return node; } /** * Inherit all unique comments from `parent` node to `child` node. */ function inheritsComments(child, parent) { if (child && parent) { var _arr4 = COMMENT_KEYS; for (var _i4 = 0; _i4 < _arr4.length; _i4++) { var key = _arr4[_i4]; child[key] = _lodashArrayUniq2["default"](_lodashArrayCompact2["default"]([].concat(child[key], parent[key]))); } } return child; } /** * Inherit all contextual properties from `parent` node to `child` node. */ function inherits(child, parent) { if (!child || !parent) return child; var _arr5 = t.INHERIT_KEYS.optional; for (var _i5 = 0; _i5 < _arr5.length; _i5++) { var key = _arr5[_i5]; if (child[key] == null) { child[key] = parent[key]; } } var _arr6 = t.INHERIT_KEYS.force; for (var _i6 = 0; _i6 < _arr6.length; _i6++) { var key = _arr6[_i6]; child[key] = parent[key]; } t.inheritsComments(child, parent); return child; } // Optimize property access. _toFastProperties2["default"](t); _toFastProperties2["default"](t.VISITOR_KEYS); // Export all type checkers from other files. _lodashObjectAssign2["default"](t, require("./retrievers")); _lodashObjectAssign2["default"](t, require("./validators")); _lodashObjectAssign2["default"](t, require("./converters")); _lodashObjectAssign2["default"](t, require("./flow"));
var CoreBot = require(__dirname+'/CoreBot.js'); var Slackbot = require(__dirname+'/SlackBot.js'); module.exports = { core: CoreBot, slackbot: Slackbot, }
/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2007 Frederico Caldeira Knabben * * == BEGIN LICENSE == * * Licensed under the terms of any of the following licenses at your * choice: * * - GNU General Public License Version 2 or later (the "GPL") * http://www.gnu.org/licenses/gpl.html * * - GNU Lesser General Public License Version 2.1 or later (the "LGPL") * http://www.gnu.org/licenses/lgpl.html * * - Mozilla Public License Version 1.1 or later (the "MPL") * http://www.mozilla.org/MPL/MPL-1.1.html * * == END LICENSE == * * Arabic language file. */ var FCKLang = { // Language direction : "ltr" (left to right) or "rtl" (right to left). Dir : "rtl", ToolbarCollapse : "ضم شريط الأدوات", ToolbarExpand : "تمدد شريط الأدوات", // Toolbar Items and Context Menu Save : "حفظ", NewPage : "صفحة جديدة", Preview : "معاينة الصفحة", Cut : "قص", Copy : "نسخ", Paste : "لصق", PasteText : "لصق كنص بسيط", PasteWord : "لصق من وورد", Print : "طباعة", SelectAll : "تحديد الكل", RemoveFormat : "إزالة التنسيقات", InsertLinkLbl : "رابط", InsertLink : "إدراج/تحرير رابط", RemoveLink : "إزالة رابط", Anchor : "إدراج/تحرير إشارة مرجعية", InsertImageLbl : "صورة", InsertImage : "إدراج/تحرير صورة", InsertFlashLbl : "فلاش", InsertFlash : "إدراج/تحرير فيلم فلاش", InsertTableLbl : "جدول", InsertTable : "إدراج/تحرير جدول", InsertLineLbl : "خط فاصل", InsertLine : "إدراج خط فاصل", InsertSpecialCharLbl: "رموز", InsertSpecialChar : "إدراج رموز..ِ", InsertSmileyLbl : "ابتسامات", InsertSmiley : "إدراج ابتسامات", About : "حول FCKeditor", Bold : "غامق", Italic : "مائل", Underline : "تسطير", StrikeThrough : "يتوسطه خط", Subscript : "منخفض", Superscript : "مرتفع", LeftJustify : "محاذاة إلى اليسار", CenterJustify : "توسيط", RightJustify : "محاذاة إلى اليمين", BlockJustify : "ضبط", DecreaseIndent : "إنقاص المسافة البادئة", IncreaseIndent : "زيادة المسافة البادئة", Undo : "تراجع", Redo : "إعادة", NumberedListLbl : "تعداد رقمي", NumberedList : "إدراج/إلغاء تعداد رقمي", BulletedListLbl : "تعداد نقطي", BulletedList : "إدراج/إلغاء تعداد نقطي", ShowTableBorders : "معاينة حدود الجداول", ShowDetails : "معاينة التفاصيل", Style : "نمط", FontFormat : "تنسيق", Font : "خط", FontSize : "حجم الخط", TextColor : "لون النص", BGColor : "لون الخلفية", Source : "شفرة المصدر", Find : "بحث", Replace : "إستبدال", SpellCheck : "تدقيق إملائي", UniversalKeyboard : "لوحة المفاتيح العالمية", PageBreakLbl : "فصل الصفحة", PageBreak : "إدخال صفحة جديدة", Form : "نموذج", Checkbox : "خانة إختيار", RadioButton : "زر خيار", TextField : "مربع نص", Textarea : "ناحية نص", HiddenField : "إدراج حقل خفي", Button : "زر ضغط", SelectionField : "قائمة منسدلة", ImageButton : "زر صورة", FitWindow : "تكبير حجم المحرر", // Context Menu EditLink : "تحرير رابط", CellCM : "خلية", RowCM : "صف", ColumnCM : "عمود", InsertRow : "إدراج صف", DeleteRows : "حذف صفوف", InsertColumn : "إدراج عمود", DeleteColumns : "حذف أعمدة", InsertCell : "إدراج خلية", DeleteCells : "حذف خلايا", MergeCells : "دمج خلايا", SplitCell : "تقسيم خلية", TableDelete : "حذف الجدول", CellProperties : "خصائص الخلية", TableProperties : "خصائص الجدول", ImageProperties : "خصائص الصورة", FlashProperties : "خصائص فيلم الفلاش", AnchorProp : "خصائص الإشارة المرجعية", ButtonProp : "خصائص زر الضغط", CheckboxProp : "خصائص خانة الإختيار", HiddenFieldProp : "خصائص الحقل الخفي", RadioButtonProp : "خصائص زر الخيار", ImageButtonProp : "خصائص زر الصورة", TextFieldProp : "خصائص مربع النص", SelectionFieldProp : "خصائص القائمة المنسدلة", TextareaProp : "خصائص ناحية النص", FormProp : "خصائص النموذج", FontFormats : "عادي;منسّق;دوس;العنوان 1;العنوان 2;العنوان 3;العنوان 4;العنوان 5;العنوان 6", //REVIEW : Check _getfontformat.html // Alerts and Messages ProcessingXHTML : "إنتظر قليلاً ريثما تتم معالَجة‏ XHTML. لن يستغرق طويلاً...", Done : "تم", PasteWordConfirm : "يبدو أن النص المراد لصقه منسوخ من برنامج وورد. هل تود تنظيفه قبل الشروع في عملية اللصق؟", NotCompatiblePaste : "هذه الميزة تحتاج لمتصفح من النوعInternet Explorer إصدار 5.5 فما فوق. هل تود اللصق دون تنظيف الكود؟", UnknownToolbarItem : "عنصر شريط أدوات غير معروف \"%1\"", UnknownCommand : "أمر غير معروف \"%1\"", NotImplemented : "لم يتم دعم هذا الأمر", UnknownToolbarSet : "لم أتمكن من العثور على طقم الأدوات \"%1\" ", NoActiveX : "لتأمين متصفحك يجب أن تحدد بعض مميزات المحرر. يتوجب عليك تمكين الخيار \"Run ActiveX controls and plug-ins\". قد تواجة أخطاء وتلاحظ مميزات مفقودة", BrowseServerBlocked : "لايمكن فتح مصدر المتصفح. فضلا يجب التأكد بأن جميع موانع النوافذ المنبثقة معطلة", DialogBlocked : "لايمكن فتح نافذة الحوار . فضلا تأكد من أن مانع النوافذ المنبثة معطل .", // Dialogs DlgBtnOK : "موافق", DlgBtnCancel : "إلغاء الأمر", DlgBtnClose : "إغلاق", DlgBtnBrowseServer : "تصفح الخادم", DlgAdvancedTag : "متقدم", DlgOpOther : "<أخرى>", DlgInfoTab : "معلومات", DlgAlertUrl : "الرجاء كتابة عنوان الإنترنت", // General Dialogs Labels DlgGenNotSet : "<بدون تحديد>", DlgGenId : "الرقم", DlgGenLangDir : "إتجاه النص", DlgGenLangDirLtr : "اليسار لليمين (LTR)", DlgGenLangDirRtl : "اليمين لليسار (RTL)", DlgGenLangCode : "رمز اللغة", DlgGenAccessKey : "مفاتيح الإختصار", DlgGenName : "الاسم", DlgGenTabIndex : "الترتيب", DlgGenLongDescr : "عنوان الوصف المفصّل", DlgGenClass : "فئات التنسيق", DlgGenTitle : "تلميح الشاشة", DlgGenContType : "نوع التلميح", DlgGenLinkCharset : "ترميز المادة المطلوبة", DlgGenStyle : "نمط", // Image Dialog DlgImgTitle : "خصائص الصورة", DlgImgInfoTab : "معلومات الصورة", DlgImgBtnUpload : "أرسلها للخادم", DlgImgURL : "موقع الصورة", DlgImgUpload : "رفع", DlgImgAlt : "الوصف", DlgImgWidth : "العرض", DlgImgHeight : "الإرتفاع", DlgImgLockRatio : "تناسق الحجم", DlgBtnResetSize : "إستعادة الحجم الأصلي", DlgImgBorder : "سمك الحدود", DlgImgHSpace : "تباعد أفقي", DlgImgVSpace : "تباعد عمودي", DlgImgAlign : "محاذاة", DlgImgAlignLeft : "يسار", DlgImgAlignAbsBottom: "أسفل النص", DlgImgAlignAbsMiddle: "وسط السطر", DlgImgAlignBaseline : "على السطر", DlgImgAlignBottom : "أسفل", DlgImgAlignMiddle : "وسط", DlgImgAlignRight : "يمين", DlgImgAlignTextTop : "أعلى النص", DlgImgAlignTop : "أعلى", DlgImgPreview : "معاينة", DlgImgAlertUrl : "فضلاً أكتب الموقع الذي توجد عليه هذه الصورة.", DlgImgLinkTab : "الرابط", // Flash Dialog DlgFlashTitle : "خصائص فيلم الفلاش", DlgFlashChkPlay : "تشغيل تلقائي", DlgFlashChkLoop : "تكرار", DlgFlashChkMenu : "تمكين قائمة فيلم الفلاش", DlgFlashScale : "الحجم", DlgFlashScaleAll : "إظهار الكل", DlgFlashScaleNoBorder : "بلا حدود", DlgFlashScaleFit : "ضبط تام", // Link Dialog DlgLnkWindowTitle : "إرتباط تشعبي", DlgLnkInfoTab : "معلومات الرابط", DlgLnkTargetTab : "الهدف", DlgLnkType : "نوع الربط", DlgLnkTypeURL : "العنوان", DlgLnkTypeAnchor : "مكان في هذا المستند", DlgLnkTypeEMail : "بريد إلكتروني", DlgLnkProto : "البروتوكول", DlgLnkProtoOther : "<أخرى>", DlgLnkURL : "الموقع", DlgLnkAnchorSel : "اختر علامة مرجعية", DlgLnkAnchorByName : "حسب اسم العلامة", DlgLnkAnchorById : "حسب تعريف العنصر", DlgLnkNoAnchors : "<لا يوجد علامات مرجعية في هذا المستند>", //REVIEW : Change < and > with ( and ) DlgLnkEMail : "عنوان بريد إلكتروني", DlgLnkEMailSubject : "موضوع الرسالة", DlgLnkEMailBody : "محتوى الرسالة", DlgLnkUpload : "رفع", DlgLnkBtnUpload : "أرسلها للخادم", DlgLnkTarget : "الهدف", DlgLnkTargetFrame : "<إطار>", DlgLnkTargetPopup : "<نافذة منبثقة>", DlgLnkTargetBlank : "إطار جديد (_blank)", DlgLnkTargetParent : "الإطار الأصل (_parent)", DlgLnkTargetSelf : "نفس الإطار (_self)", DlgLnkTargetTop : "صفحة كاملة (_top)", DlgLnkTargetFrameName : "اسم الإطار الهدف", DlgLnkPopWinName : "تسمية النافذة المنبثقة", DlgLnkPopWinFeat : "خصائص النافذة المنبثقة", DlgLnkPopResize : "قابلة للتحجيم", DlgLnkPopLocation : "شريط العنوان", DlgLnkPopMenu : "القوائم الرئيسية", DlgLnkPopScroll : "أشرطة التمرير", DlgLnkPopStatus : "شريط الحالة السفلي", DlgLnkPopToolbar : "شريط الأدوات", DlgLnkPopFullScrn : "ملئ الشاشة (IE)", DlgLnkPopDependent : "تابع (Netscape)", DlgLnkPopWidth : "العرض", DlgLnkPopHeight : "الإرتفاع", DlgLnkPopLeft : "التمركز لليسار", DlgLnkPopTop : "التمركز للأعلى", DlnLnkMsgNoUrl : "فضلاً أدخل عنوان الموقع الذي يشير إليه الرابط", DlnLnkMsgNoEMail : "فضلاً أدخل عنوان البريد الإلكتروني", DlnLnkMsgNoAnchor : "فضلاً حدد العلامة المرجعية المرغوبة", DlnLnkMsgInvPopName : "اسم النافذة المنبثقة يجب أن يبدأ بحرف أبجدي دون مسافات", // Color Dialog DlgColorTitle : "اختر لوناً", DlgColorBtnClear : "مسح", DlgColorHighlight : "تحديد", DlgColorSelected : "إختيار", // Smiley Dialog DlgSmileyTitle : "إدراج إبتسامات ", // Special Character Dialog DlgSpecialCharTitle : "إدراج رمز", // Table Dialog DlgTableTitle : "إدراج جدول", DlgTableRows : "صفوف", DlgTableColumns : "أعمدة", DlgTableBorder : "سمك الحدود", DlgTableAlign : "المحاذاة", DlgTableAlignNotSet : "<بدون تحديد>", DlgTableAlignLeft : "يسار", DlgTableAlignCenter : "وسط", DlgTableAlignRight : "يمين", DlgTableWidth : "العرض", DlgTableWidthPx : "بكسل", DlgTableWidthPc : "بالمئة", DlgTableHeight : "الإرتفاع", DlgTableCellSpace : "تباعد الخلايا", DlgTableCellPad : "المسافة البادئة", DlgTableCaption : "الوصف", DlgTableSummary : "الخلاصة", // Table Cell Dialog DlgCellTitle : "خصائص الخلية", DlgCellWidth : "العرض", DlgCellWidthPx : "بكسل", DlgCellWidthPc : "بالمئة", DlgCellHeight : "الإرتفاع", DlgCellWordWrap : "التفاف النص", DlgCellWordWrapNotSet : "<بدون تحديد>", DlgCellWordWrapYes : "نعم", DlgCellWordWrapNo : "لا", DlgCellHorAlign : "المحاذاة الأفقية", DlgCellHorAlignNotSet : "<بدون تحديد>", DlgCellHorAlignLeft : "يسار", DlgCellHorAlignCenter : "وسط", DlgCellHorAlignRight: "يمين", DlgCellVerAlign : "المحاذاة العمودية", DlgCellVerAlignNotSet : "<بدون تحديد>", DlgCellVerAlignTop : "أعلى", DlgCellVerAlignMiddle : "وسط", DlgCellVerAlignBottom : "أسفل", DlgCellVerAlignBaseline : "على السطر", DlgCellRowSpan : "إمتداد الصفوف", DlgCellCollSpan : "إمتداد الأعمدة", DlgCellBackColor : "لون الخلفية", DlgCellBorderColor : "لون الحدود", DlgCellBtnSelect : "حدّد...", // Find Dialog DlgFindTitle : "بحث", DlgFindFindBtn : "ابحث", DlgFindNotFoundMsg : "لم يتم العثور على النص المحدد.", // Replace Dialog DlgReplaceTitle : "إستبدال", DlgReplaceFindLbl : "البحث عن:", DlgReplaceReplaceLbl : "إستبدال بـ:", DlgReplaceCaseChk : "مطابقة حالة الأحرف", DlgReplaceReplaceBtn : "إستبدال", DlgReplaceReplAllBtn : "إستبدال الكل", DlgReplaceWordChk : "الكلمة بالكامل فقط", // Paste Operations / Dialog PasteErrorCut : "الإعدادات الأمنية للمتصفح الذي تستخدمه تمنع القص التلقائي. فضلاً إستخدم لوحة المفاتيح لفعل ذلك (Ctrl+X).", PasteErrorCopy : "الإعدادات الأمنية للمتصفح الذي تستخدمه تمنع النسخ التلقائي. فضلاً إستخدم لوحة المفاتيح لفعل ذلك (Ctrl+C).", PasteAsText : "لصق كنص بسيط", PasteFromWord : "لصق من وورد", DlgPasteMsg2 : "الصق داخل الصندوق بإستخدام زرّي (<STRONG>Ctrl+V</STRONG>) في لوحة المفاتيح، ثم اضغط زر <STRONG>موافق</STRONG>.", DlgPasteSec : "Because of your browser security settings, the editor is not able to access your clipboard data directly. You are required to paste it again in this window.", //MISSING DlgPasteIgnoreFont : "تجاهل تعريفات أسماء الخطوط", DlgPasteRemoveStyles : "إزالة تعريفات الأنماط", DlgPasteCleanBox : "نظّف محتوى الصندوق", // Color Picker ColorAutomatic : "تلقائي", ColorMoreColors : "ألوان إضافية...", // Document Properties DocProps : "خصائص الصفحة", // Anchor Dialog DlgAnchorTitle : "خصائص إشارة مرجعية", DlgAnchorName : "اسم الإشارة المرجعية", DlgAnchorErrorName : "الرجاء كتابة اسم الإشارة المرجعية", // Speller Pages Dialog DlgSpellNotInDic : "ليست في القاموس", DlgSpellChangeTo : "التغيير إلى", DlgSpellBtnIgnore : "تجاهل", DlgSpellBtnIgnoreAll : "تجاهل الكل", DlgSpellBtnReplace : "تغيير", DlgSpellBtnReplaceAll : "تغيير الكل", DlgSpellBtnUndo : "تراجع", DlgSpellNoSuggestions : "- لا توجد إقتراحات -", DlgSpellProgress : "جاري التدقيق إملائياً", DlgSpellNoMispell : "تم إكمال التدقيق الإملائي: لم يتم العثور على أي أخطاء إملائية", DlgSpellNoChanges : "تم إكمال التدقيق الإملائي: لم يتم تغيير أي كلمة", DlgSpellOneChange : "تم إكمال التدقيق الإملائي: تم تغيير كلمة واحدة فقط", DlgSpellManyChanges : "تم إكمال التدقيق الإملائي: تم تغيير %1 كلمات\كلمة", IeSpellDownload : "المدقق الإملائي (الإنجليزي) غير مثبّت. هل تود تحميله الآن؟", // Button Dialog DlgButtonText : "القيمة/التسمية", DlgButtonType : "نوع الزر", DlgButtonTypeBtn : "زر", DlgButtonTypeSbm : "إرسال", DlgButtonTypeRst : "إعادة تعيين", // Checkbox and Radio Button Dialogs DlgCheckboxName : "الاسم", DlgCheckboxValue : "القيمة", DlgCheckboxSelected : "محدد", // Form Dialog DlgFormName : "الاسم", DlgFormAction : "اسم الملف", DlgFormMethod : "الأسلوب", // Select Field Dialog DlgSelectName : "الاسم", DlgSelectValue : "القيمة", DlgSelectSize : "الحجم", DlgSelectLines : "الأسطر", DlgSelectChkMulti : "السماح بتحديدات متعددة", DlgSelectOpAvail : "الخيارات المتاحة", DlgSelectOpText : "النص", DlgSelectOpValue : "القيمة", DlgSelectBtnAdd : "إضافة", DlgSelectBtnModify : "تعديل", DlgSelectBtnUp : "تحريك لأعلى", DlgSelectBtnDown : "تحريك لأسفل", DlgSelectBtnSetValue : "إجعلها محددة", DlgSelectBtnDelete : "إزالة", // Textarea Dialog DlgTextareaName : "الاسم", DlgTextareaCols : "الأعمدة", DlgTextareaRows : "الصفوف", // Text Field Dialog DlgTextName : "الاسم", DlgTextValue : "القيمة", DlgTextCharWidth : "العرض بالأحرف", DlgTextMaxChars : "عدد الحروف الأقصى", DlgTextType : "نوع المحتوى", DlgTextTypeText : "نص", DlgTextTypePass : "كلمة مرور", // Hidden Field Dialog DlgHiddenName : "الاسم", DlgHiddenValue : "القيمة", // Bulleted List Dialog BulletedListProp : "خصائص التعداد النقطي", NumberedListProp : "خصائص التعداد الرقمي", DlgLstStart : "البدء عند", DlgLstType : "النوع", DlgLstTypeCircle : "دائرة", DlgLstTypeDisc : "قرص", DlgLstTypeSquare : "مربع", DlgLstTypeNumbers : "أرقام (1، 2، 3)َ", DlgLstTypeLCase : "حروف صغيرة (a, b, c)َ", DlgLstTypeUCase : "حروف كبيرة (A, B, C)َ", DlgLstTypeSRoman : "ترقيم روماني صغير (i, ii, iii)َ", DlgLstTypeLRoman : "ترقيم روماني كبير (I, II, III)َ", // Document Properties Dialog DlgDocGeneralTab : "عام", DlgDocBackTab : "الخلفية", DlgDocColorsTab : "الألوان والهوامش", DlgDocMetaTab : "المعرّفات الرأسية", DlgDocPageTitle : "عنوان الصفحة", DlgDocLangDir : "إتجاه اللغة", DlgDocLangDirLTR : "اليسار لليمين (LTR)", DlgDocLangDirRTL : "اليمين لليسار (RTL)", DlgDocLangCode : "رمز اللغة", DlgDocCharSet : "ترميز الحروف", DlgDocCharSetCE : "أوروبا الوسطى", DlgDocCharSetCT : "الصينية التقليدية (Big5)", DlgDocCharSetCR : "السيريلية", DlgDocCharSetGR : "اليونانية", DlgDocCharSetJP : "اليابانية", DlgDocCharSetKR : "الكورية", DlgDocCharSetTR : "التركية", DlgDocCharSetUN : "Unicode (UTF-8)", DlgDocCharSetWE : "أوروبا الغربية", DlgDocCharSetOther : "ترميز آخر", DlgDocDocType : "ترويسة نوع الصفحة", DlgDocDocTypeOther : "ترويسة نوع صفحة أخرى", DlgDocIncXHTML : "تضمين إعلانات‏ لغة XHTMLَ", DlgDocBgColor : "لون الخلفية", DlgDocBgImage : "رابط الصورة الخلفية", DlgDocBgNoScroll : "جعلها علامة مائية", DlgDocCText : "النص", DlgDocCLink : "الروابط", DlgDocCVisited : "المزارة", DlgDocCActive : "النشطة", DlgDocMargins : "هوامش الصفحة", DlgDocMaTop : "علوي", DlgDocMaLeft : "أيسر", DlgDocMaRight : "أيمن", DlgDocMaBottom : "سفلي", DlgDocMeIndex : "الكلمات الأساسية (مفصولة بفواصل)َ", DlgDocMeDescr : "وصف الصفحة", DlgDocMeAuthor : "الكاتب", DlgDocMeCopy : "المالك", DlgDocPreview : "معاينة", // Templates Dialog Templates : "القوالب", DlgTemplatesTitle : "قوالب المحتوى", DlgTemplatesSelMsg : "اختر القالب الذي تود وضعه في المحرر <br>(سيتم فقدان المحتوى الحالي):", DlgTemplatesLoading : "جاري تحميل قائمة القوالب، الرجاء الإنتظار...", DlgTemplatesNoTpl : "(لم يتم تعريف أي قالب)", DlgTemplatesReplace : "استبدال المحتوى", // About Dialog DlgAboutAboutTab : "نبذة", DlgAboutBrowserInfoTab : "معلومات متصفحك", DlgAboutLicenseTab : "الترخيص", DlgAboutVersion : "الإصدار", DlgAboutInfo : "لمزيد من المعلومات تفضل بزيارة" };
tinymce.addI18n('it',{ "Cut": "Taglia", "Your browser doesn't support direct access to the clipboard. Please use the Ctrl+X\/C\/V keyboard shortcuts instead.": "Il tuo browser non supporta l'accesso diretto negli Appunti. Per favore usa i tasti di scelta rapida Ctrl+X\/C\/V.", "Paste": "Incolla", "Close": "Chiudi", "Align right": "Allinea a Destra", "New document": "Nuovo Documento", "Numbered list": "Elenchi Numerati", "Increase indent": "Aumenta Rientro", "Formats": "Formattazioni", "Select all": "Seleziona Tutto", "Undo": "Indietro", "Strikethrough": "Barrato", "Bullet list": "Elenchi Puntati", "Superscript": "Apice", "Clear formatting": "Cancella Formattazione", "Subscript": "Pedice", "Redo": "Ripeti", "Ok": "Ok", "Bold": "Grassetto", "Italic": "Corsivo", "Align center": "Allinea al Cento", "Decrease indent": "Riduci Rientro", "Underline": "Sottolineato", "Cancel": "Cancella", "Justify": "Giustifica", "Copy": "Copia", "Align left": "Allinea a Sinistra", "Visual aids": "Elementi Visivi", "Lower Greek": "Greek Minore", "Square": "Quadrato", "Default": "Default", "Lower Alpha": "Alpha Minore", "Circle": "Cerchio", "Disc": "Disco", "Upper Alpha": "Alpha Superiore", "Upper Roman": "Roman Superiore", "Lower Roman": "Roman Minore", "Name": "Nome", "Anchor": "Fissa", "You have unsaved changes are you sure you want to navigate away?": "Non hai salvato delle modifiche, sei sicuro di andartene?", "Restore last draft": "Ripristina l'ultima bozza.", "Special character": "Carattere Speciale", "Source code": "Codice Sorgente", "Right to left": "Da Destra a Sinistra", "Left to right": "Da Sinistra a Destra", "Emoticons": "Emoction", "Robots": "Robot", "Document properties": "Propriet\u00e0 Documento", "Title": "Titolo", "Keywords": "Parola Chiave", "Encoding": "Codifica", "Description": "Descrizione", "Author": "Autore", "Fullscreen": "Schermo Intero", "Horizontal line": "Linea Orizzontale", "Horizontal space": "Spazio Orizzontale", "Insert\/edit image": "Aggiungi\/Modifica Immagine", "General": "Generale", "Advanced": "Avanzato", "Source": "Fonte", "Border": "Bordo", "Constrain proportions": "Mantieni Proporzioni", "Vertical space": "Spazio Verticale", "Image description": "Descrizione Immagine", "Style": "Stile", "Dimensions": "Dimenzioni", "Insert date\/time": "Inserisci Data\/Ora", "Url": "Url", "Text to display": "Testo da Visualizzare", "Insert link": "Inserisci il Link", "New window": "Nuova Finestra", "None": "No", "Target": "Target", "Insert\/edit link": "Inserisci\/Modifica Link", "Insert\/edit video": "Inserisci\/Modifica Video", "Poster": "Anteprima", "Alternative source": "Alternativo", "Paste your embed code below:": "Incolla il codice d'incorporamento qui:", "Insert video": "Inserisci Video", "Embed": "Incorporare", "Nonbreaking space": "Spazio unificatore", "Preview": "Anteprima", "Print": "Stampa", "Save": "Salva", "Could not find the specified string.": "Impossibile trovare la parola specifica.", "Replace": "Sostituisci", "Next": "Successivo", "Whole words": "Parole Sbagliate", "Find and replace": "Trova e Sostituisci", "Replace with": "Sostituisci Con", "Find": "Trova", "Replace all": "Sostituisci Tutto", "Match case": "Maiuscole\/Minuscole ", "Prev": "Precedente", "Spellcheck": "Controllo ortografico", "Finish": "Termina", "Ignore all": "Ignora Tutto", "Ignore": "Ignora", "Insert row before": "Inserisci una Riga Prima", "Rows": "Righe", "Height": "Altezza", "Paste row after": "Incolla una Riga Dopo", "Alignment": "Allineamento", "Column group": "Gruppo di Colonne", "Row": "Riga", "Insert column before": "Inserisci una Colonna Prima", "Split cell": "Dividi Cella", "Cell padding": "Padding della Cella", "Cell spacing": "Spaziatura della Cella", "Row type": "Tipo di Riga", "Insert table": "Inserisci Tabella", "Body": "Body", "Caption": "Didascalia", "Footer": "Footer", "Delete row": "Cancella Riga", "Paste row before": "Incolla una Riga Prima", "Scope": "Campo", "Delete table": "Cancella Tabella", "Header cell": "cella d'intestazione", "Column": "Colonna", "Cell": "Cella", "Header": "Header", "Cell type": "Tipo di Cella", "Copy row": "Copia Riga", "Row properties": "Propriet\u00e0 della Riga", "Table properties": "Propiet\u00e0 della Tabella", "Row group": "Gruppo di Righe", "Right": "Destra", "Insert column after": "Inserisci una Colonna Dopo", "Cols": "Colonne", "Insert row after": "Inserisci una Riga Dopo", "Width": "Larghezza", "Cell properties": "Propiet\u00e0 della Cella", "Left": "Sinistra", "Cut row": "Taglia Riga", "Delete column": "Cancella Colonna", "Center": "Centro", "Merge cells": "Unisci Cella", "Insert template": "Inserisci Template", "Templates": "Template", "Background color": "Colore Background", "Text color": "Colore Testo", "Show blocks": "Mostra Blocchi", "Show invisible characters": "Mostra Caratteri Invisibili", "Words: {0}": "Parole: {0}", "Insert": "Inserisci", "File": "File", "Edit": "Modifica", "Rich Text Area. Press ALT-F9 for menu. Press ALT-F10 for toolbar. Press ALT-0 for help": "Rich Text Area. Premi ALT-F9 per il men\u00f9. Premi ALT-F10 per la barra degli strumenti. Premi ALT-0 per l'aiuto.", "Tools": "Strumenti", "View": "Visualiza", "Table": "Tabella", "Format": "Formato" });
var searchData= [ ['nameresolve',['NameResolve',['../classblackbone_1_1_name_resolve.html',1,'blackbone']]], ['native',['Native',['../classblackbone_1_1_native.html',1,'blackbone']]], ['nativewow64',['NativeWow64',['../classblackbone_1_1_native_wow64.html',1,'blackbone']]], ['noclass',['NoClass',['../classblackbone_1_1_no_class.html',1,'blackbone']]], ['ntldr',['NtLdr',['../classblackbone_1_1_nt_ldr.html',1,'blackbone']]] ];
"use strict"; 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 _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 _possibleConstructorReturn(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; } function _inherits(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; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } /********************************************/ /* © Arthur Guiot 2017 */ /* DisplayJS */ /* https://display.js.org/ */ /********************************************/ var DisplayJS = function () { function DisplayJS(obj) { _classCallCheck(this, DisplayJS); this.obj = obj; } /* DOM manipulation and browser API.*/ _createClass(DisplayJS, [{ key: "var", value: function _var(push) { var _this = this; // the function var var_push = function var_push() { _this.if(); _this.else(); var elements = document.querySelectorAll("[var]"); for (var i = 0; i < elements.length; i++) { var attr = elements[i].getAttribute("var"); elements[i].innerHTML = _this.obj[attr]; } }; // push var cheking if (!push) { var_push(); } else if (push == true) { var_push(); this.live(this.obj, function () { var_push(); }); } else { window.setInterval(function () { var_push(); }, push); } } // aliases of $.var(); }, { key: "render", value: function render(push) { this.var(push); } }, { key: "renderVariables", value: function renderVariables(push) { this.var(push); } // Transform HTML special chars }, { key: "xss", value: function xss(str) { var lt = /</g; var gt = />/g; var ap = /'/g; var ic = /"/g; return str.toString().replace(lt, "&lt;").replace(gt, "&gt;").replace(ap, "&#39;").replace(ic, "&#34;"); } // encode the URI }, { key: "xssURI", value: function xssURI(str) { return encodeURI(str); } // Target input to variable }, { key: "target", value: function target() { var _this2 = this; var callback = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : function () { _this2.var(); }; var addEventListener = function () { if (document.addEventListener) { return function (element, event, handler) { element.addEventListener(event, handler, false); }; } return function (element, event, handler) { element.attachEvent("on" + event, handler); }; }(); var obj = this.obj; [].forEach.call(document.querySelectorAll("[target]"), function (x) { addEventListener(x, "change", function () { var attr1 = x.getAttribute("target"); if (this.type == "checkbox") { obj[attr1] = this.checked; } else if (this.type == "select") { obj[attr1] = this.options[this.selectedIndex].value; } else { obj[attr1] = this.value; } callback(x); }); addEventListener(x, "keydown", function () { var attr2 = x.getAttribute("target"); if (this.type == "checkbox") { obj[attr2] = this.checked; } else if (this.type == "select") { obj[attr2] = this.options[this.selectedIndex].value; } else { obj[attr2] = this.value; } callback(x); }); addEventListener(x, "input", function () { var attr3 = x.getAttribute("target"); if (this.type == "checkbox") { obj[attr3] = this.checked; } else if (this.type == "select") { obj[attr3] = this.options[this.selectedIndex].value; } else { obj[attr3] = this.value; } callback(x); }); addEventListener(x, "paste", function () { var attr4 = x.getAttribute("target"); if (this.type == "checkbox") { obj[attr4] = this.checked; } else if (this.type == "select") { obj[attr4] = this.options[this.selectedIndex].value; } else { obj[attr4] = this.value; } callback(x); }); }); } // if...else function }, { key: "if", value: function _if(push) { var _this3 = this; var if_push = function if_push() { var elements = document.querySelectorAll("[if]"); for (var i = 0; i < elements.length; i++) { var attr = elements[i].getAttribute("if"); var el = []; el.push(elements[i]); if (eval(_this3.obj[attr])) { _this3.show(_this3.toNodeList(el[0])); } else { _this3.hide(_this3.toNodeList(el[0])); } } }; if (!push) { if_push(); } else if (push == true) { if_push(); this.live(this.obj, function () { if_push(); }); } else { window.setInterval(function () { if_push(); }, push); } } }, { key: "else", value: function _else(push) { var _this4 = this; var else_push = function else_push() { var elements = document.querySelectorAll("[else]"); for (var i = 0; i < elements.length; i++) { var attr = elements[i].getAttribute("else"); var el = []; el.push(elements[i]); if (eval(_this4.obj[attr])) { _this4.hide(_this4.toNodeList(el[0])); } else { _this4.show(_this4.toNodeList(el[0])); } } }; if (!push) { else_push(); } else if (push == true) { else_push(); this.live(this.obj, function () { else_push(); }); } else { window.setInterval(function () { else_push(); }, push); } } }, { key: "toNodeList", value: function toNodeList(el) { el.setAttribute('wrapNodeList', ''); var list = document.querySelectorAll('[wrapNodeList]'); el.removeAttribute('wrapNodeList'); return list; } // custom repeat function }, { key: "repeat", value: function repeat(el, array, join) { var start = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : ""; var end = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : ""; el = this.s(el); var text = start; if ((typeof join === "undefined" ? "undefined" : _typeof(join)) == "object") { for (var i = 0; i < array.length; i++) { text += join[i] + String(array[i]); } } else { for (var _i = 0; _i < array.length; _i++) { text += join + String(array[_i]); } } text += end; el[0].innerHTML = text; } // parsing the DOM for on and action attribute }, { key: "onEvent", value: function onEvent() { var elements = document.querySelectorAll("[on]"); var _loop = function _loop(i) { var attr = elements[i].getAttribute("on"); var action = elements[i].getAttribute("action"); elements[i].addEventListener(attr, function () { eval(action); }); }; for (var i = 0; i < elements.length; i++) { _loop(i); } } // apply function to each elements selected }, { key: "all", value: function all(el, callback) { var _this5 = this; el = this.s(el); el.forEach(function (data) { callback(_this5.toNodeList(data)); }); } /* Basic DOM manipulation */ }, { key: "text", value: function text(el, _text) { el = this.s(el); return _text ? el[0].innerHTML = this.xss(_text) : el[0].innerHTML; } }, { key: "html", value: function html(el, _html) { el = this.s(el); return _html ? el[0].innerHTML = _html : el[0].innerHTML; } }, { key: "append", value: function append(el, html) { el = this.s(el); el[0].innerHTML += html; } }, { key: "after", value: function after(el, html) { el = this.s(el); el[0].insertAdjacentHTML("afterend", html); } }, { key: "before", value: function before(el, html) { el = this.s(el); el[0].insertAdjacentHTML("beforebegin", html); } }, { key: "clone", value: function clone(el) { el[0].cloneNode(true); } }, { key: "is", value: function is(el1, el2) { el1 = this.s(el1); el2 = this.s(el2); if (el1[0] === el2[0]) { return true; } return false; } }, { key: "select", value: function select(str) { return str instanceof NodeList ? str : document.querySelectorAll(str); } }, { key: "single", value: function single(str) { return this.isElement(str) ? str : document.querySelector(str); } // alias of $.select() }, { key: "s", value: function s(str) { return this.select(str); } }, { key: "empty", value: function empty(el) { el = this.s(el); el[0].innerHTML = ""; } }, { key: "valEmpty", value: function valEmpty(el) { el = this.s(el); el[0].value = null; } }, { key: "remove", value: function remove(el) { el = this.s(el); el[0].parentNode.removeChild(el[0]); } }, { key: "on", value: function on(el, event, callback) { el = this.s(el); el[0].addEventListener(event, callback); } }, { key: "ready", value: function ready(fn) { if (document.attachEvent ? document.readyState === "complete" : document.readyState !== "loading") { fn(); } else { document.addEventListener("DOMContentLoaded", fn); } } }, { key: "scroll", value: function scroll(callback) { window.addEventListener("scroll", callback); } }, { key: "scrollTo", value: function scrollTo(x, y) { window.scroll(x, y); } }, { key: "scrollTop", value: function scrollTop() { var el = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : this.toNodeList(document.body); el = this.s(el); return el[0].scrollTop; } }, { key: "show", value: function show(el) { el = this.s(el); el[0].style.display = "block"; return true; } }, { key: "hide", value: function hide(el) { el = this.s(el); el[0].style.display = "none"; return true; } }, { key: "hasClass", value: function hasClass(el, className) { el = this.s(el); if (el[0].classList) { return el[0].classList.contains(className); } return !!el[0].className.match(new RegExp("(\\s|^)" + className + "(\\s|$)")); } }, { key: "addClass", value: function addClass(el, className) { el = this.s(el); if (el[0].classList) { el[0].classList.add(className); } else if (!this.hasClass(el, className)) { el[0].className += " " + className; } } }, { key: "removeClass", value: function removeClass(el, className) { el = this.s(el); if (el[0].classList) { el[0].classList.remove(className); } else if (this.hasClass(el, className)) { var reg = new RegExp("(\\s|^)" + className + "(\\s|$)"); el[0].className = el[0].className.replace(reg, " "); } } }, { key: "toggleClass", value: function toggleClass(el, className) { el = this.s(el); if (this.hasClass(el, className)) { this.removeClass(el, className); } else { this.addClass(el, className); } } }, { key: "css", value: function css(el, name, value) { el = this.s(el); el[0].style[name] = value; } }, { key: "getStyle", value: function getStyle(el, styleProp) { el = this.s(el); return el[0].style[styleProp]; } }, { key: "fadeOut", value: function fadeOut(el) { var i = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0.1; el = this.s(el)[0]; el.style.opacity = 1; (function fade() { if ((el.style.opacity -= i) < 0) { el.style.display = "none"; } else { requestAnimationFrame(fade); } })(); } }, { key: "fadeIn", value: function fadeIn(el) { var i = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0.1; var display = arguments[2]; el = this.s(el)[0]; el.style.opacity = 0; el.style.display = display || "block"; (function fade() { var val = parseFloat(el.style.opacity); if (!((val += i) > 1)) { el.style.opacity = val; requestAnimationFrame(fade); } })(); } // Create a function in the DisplayJS object }, { key: "dynamic", // dynamically update something value: function dynamic(callback) { var push = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 250; window.setInterval(callback, push); } }, { key: "parent", value: function parent(el) { var n = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; el = this.s(el); var newEl = el[0]; for (var i in this.range(n)) { newEl = newEl.parentNode; } return this.toNodeList(newEl); } }, { key: "isNode", value: function isNode(el) { return (typeof Node === "undefined" ? "undefined" : _typeof(Node)) === "object" ? el instanceof Node : el && (typeof el === "undefined" ? "undefined" : _typeof(el)) === "object" && typeof el.nodeType === "number" && typeof el.nodeName === "string"; } }, { key: "isElement", value: function isElement(el) { return (typeof HTMLElement === "undefined" ? "undefined" : _typeof(HTMLElement)) === "object" ? el instanceof HTMLElement : //DOM2 el && (typeof el === "undefined" ? "undefined" : _typeof(el)) === "object" && el !== null && el.nodeType === 1 && typeof el.nodeName === "string"; } // create custom component }, { key: "component", value: function component(name, callback) { var component = function (_HTMLElement) { _inherits(component, _HTMLElement); function component() { _classCallCheck(this, component); var _this6 = _possibleConstructorReturn(this, (component.__proto__ || Object.getPrototypeOf(component)).call(this)); callback(_this6); return _this6; } return component; }(HTMLElement); customElements.define(name, component); } // import a script }, { key: "import", value: function _import(source, callback) { var script = document.createElement("script"); var prior = document.getElementsByTagName("script")[0]; script.async = 1; script.onload = script.onreadystatechange = function (_, isAbort) { if (isAbort || !script.readyState || /loaded|complete/.test(script.readyState)) { script.onload = script.onreadystatechange = null; script = undefined; if (!isAbort) { if (callback) callback(); } } }; script.src = source; prior.parentNode.insertBefore(script, prior); } }, { key: "sleep", value: function sleep(ms) { var waitUntil = new Date().getTime() + ms; while (new Date().getTime() < waitUntil) { true; } } // Math and array manipulation + includes }, { key: "extend", value: function extend(defaults, options) { var extended = {}; var prop = void 0; for (prop in defaults) { if (Object.prototype.hasOwnProperty.call(defaults, prop)) { extended[prop] = defaults[prop]; } } for (prop in options) { if (Object.prototype.hasOwnProperty.call(options, prop)) { extended[prop] = options[prop]; } } return extended; } }, { key: "arange", value: function arange(start, end, step, offset) { var len = (Math.abs(end - start) + (offset || 0) * 2) / (step || 1) + 1; var direction = start < end ? 1 : -1; var startingPoint = start - direction * (offset || 0); var stepSize = direction * (step || 1); return Array(len).fill(0).map(function (_, index) { return startingPoint + stepSize * index; }); } }, { key: "range", value: function range(n) { return this.arange(0, n, 1); } }, { key: "linespace", value: function linespace(start, end, n) { var diff = end - start; var step = diff / n; return this.arange(start, end, step); } }, { key: "reshape", value: function reshape(array, part) { var tmp = []; for (var i = 0; i < array.length; i += part) { tmp.push(array.slice(i, i + part)); } return tmp; } }, { key: "flatten", value: function flatten(array) { return array.reduce(function (a, b) { return a.concat(b); }, []); } }, { key: "drop", value: function drop(array, val) { return val > 0 ? array.slice(val, array.length) : array.slice(0, array.length + val); } }, { key: "isIn", value: function isIn(array, val) { return array.includes(val) ? true : false; } }, { key: "rmFromArray", value: function rmFromArray(array, condition) { var obj = []; for (var i in array) { if (!condition(i)) { obj.push(array[i]); } } return obj; } //= includes }, { key: "fn", get: function get() { return DisplayJS.prototype; } }]); return DisplayJS; }(); // Browserify / Node.js if (typeof define === "function" && define.amd) { define(function () { return new DisplayJS(); }); // CommonJS and Node.js module support. } else if (typeof exports !== "undefined") { // Support Node.js specific `module.exports` (which can be a function) if (typeof module !== "undefined" && module.exports) { exports = module.exports = new DisplayJS(); } // But always support CommonJS module 1.1.1 spec (`exports` cannot be a function) exports.DisplayJS = new DisplayJS(); } else if (typeof global !== "undefined") { global.DisplayJS = new DisplayJS(); }
/** * ReactDOMServer v16.0.0-alpha */ ;(function(f) { // CommonJS if (typeof exports === "object" && typeof module !== "undefined") { module.exports = f(require('react')); // RequireJS } else if (typeof define === "function" && define.amd) { define(['react'], f); // <script> } else { var g; if (typeof window !== "undefined") { g = window; } else if (typeof global !== "undefined") { g = global; } else if (typeof self !== "undefined") { g = self; } else { // works providing we're not in "use strict"; // needed for Java 8 Nashorn // see https://github.com/facebook/react/issues/3037 g = this; } g.ReactDOMServer = f(g.React); } })(function(React) { return (function(f){return f()})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){ /** * 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. * */ 'use strict'; var ARIADOMPropertyConfig = { Properties: { // Global States and Properties 'aria-current': 0, // state 'aria-details': 0, 'aria-disabled': 0, // state 'aria-hidden': 0, // state 'aria-invalid': 0, // state 'aria-keyshortcuts': 0, 'aria-label': 0, 'aria-roledescription': 0, // Widget Attributes 'aria-autocomplete': 0, 'aria-checked': 0, 'aria-expanded': 0, 'aria-haspopup': 0, 'aria-level': 0, 'aria-modal': 0, 'aria-multiline': 0, 'aria-multiselectable': 0, 'aria-orientation': 0, 'aria-placeholder': 0, 'aria-pressed': 0, 'aria-readonly': 0, 'aria-required': 0, 'aria-selected': 0, 'aria-sort': 0, 'aria-valuemax': 0, 'aria-valuemin': 0, 'aria-valuenow': 0, 'aria-valuetext': 0, // Live Region Attributes 'aria-atomic': 0, 'aria-busy': 0, 'aria-live': 0, 'aria-relevant': 0, // Drag-and-Drop Attributes 'aria-dropeffect': 0, 'aria-grabbed': 0, // Relationship Attributes 'aria-activedescendant': 0, 'aria-colcount': 0, 'aria-colindex': 0, 'aria-colspan': 0, 'aria-controls': 0, 'aria-describedby': 0, 'aria-errormessage': 0, 'aria-flowto': 0, 'aria-labelledby': 0, 'aria-owns': 0, 'aria-posinset': 0, 'aria-rowcount': 0, 'aria-rowindex': 0, 'aria-rowspan': 0, 'aria-setsize': 0 }, DOMAttributeNames: {}, DOMPropertyNames: {} }; module.exports = ARIADOMPropertyConfig; },{}],2:[function(_dereq_,module,exports){ /** * 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. * */ 'use strict'; var ReactDOMComponentTree = _dereq_(34); var focusNode = _dereq_(143); var AutoFocusUtils = { focusDOMComponent: function () { focusNode(ReactDOMComponentTree.getNodeFromInstance(this)); } }; module.exports = AutoFocusUtils; },{"143":143,"34":34}],3:[function(_dereq_,module,exports){ /** * 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. * */ 'use strict'; var EventPropagators = _dereq_(19); var ExecutionEnvironment = _dereq_(135); var FallbackCompositionState = _dereq_(20); var SyntheticCompositionEvent = _dereq_(86); var SyntheticInputEvent = _dereq_(90); var END_KEYCODES = [9, 13, 27, 32]; // Tab, Return, Esc, Space var START_KEYCODE = 229; var canUseCompositionEvent = ExecutionEnvironment.canUseDOM && 'CompositionEvent' in window; var documentMode = null; if (ExecutionEnvironment.canUseDOM && 'documentMode' in document) { documentMode = document.documentMode; } // Webkit offers a very useful `textInput` event that can be used to // directly represent `beforeInput`. The IE `textinput` event is not as // useful, so we don't use it. var canUseTextInputEvent = ExecutionEnvironment.canUseDOM && 'TextEvent' in window && !documentMode && !isPresto(); // In IE9+, we have access to composition events, but the data supplied // by the native compositionend event may be incorrect. Japanese ideographic // spaces, for instance (\u3000) are not recorded correctly. var useFallbackCompositionData = ExecutionEnvironment.canUseDOM && (!canUseCompositionEvent || documentMode && documentMode > 8 && documentMode <= 11); /** * Opera <= 12 includes TextEvent in window, but does not fire * text input events. Rely on keypress instead. */ function isPresto() { var opera = window.opera; return typeof opera === 'object' && typeof opera.version === 'function' && parseInt(opera.version(), 10) <= 12; } var SPACEBAR_CODE = 32; var SPACEBAR_CHAR = String.fromCharCode(SPACEBAR_CODE); // Events and their corresponding property names. var eventTypes = { beforeInput: { phasedRegistrationNames: { bubbled: 'onBeforeInput', captured: 'onBeforeInputCapture' }, dependencies: ['topCompositionEnd', 'topKeyPress', 'topTextInput', 'topPaste'] }, compositionEnd: { phasedRegistrationNames: { bubbled: 'onCompositionEnd', captured: 'onCompositionEndCapture' }, dependencies: ['topBlur', 'topCompositionEnd', 'topKeyDown', 'topKeyPress', 'topKeyUp', 'topMouseDown'] }, compositionStart: { phasedRegistrationNames: { bubbled: 'onCompositionStart', captured: 'onCompositionStartCapture' }, dependencies: ['topBlur', 'topCompositionStart', 'topKeyDown', 'topKeyPress', 'topKeyUp', 'topMouseDown'] }, compositionUpdate: { phasedRegistrationNames: { bubbled: 'onCompositionUpdate', captured: 'onCompositionUpdateCapture' }, dependencies: ['topBlur', 'topCompositionUpdate', 'topKeyDown', 'topKeyPress', 'topKeyUp', 'topMouseDown'] } }; // Track whether we've ever handled a keypress on the space key. var hasSpaceKeypress = false; /** * Return whether a native keypress event is assumed to be a command. * This is required because Firefox fires `keypress` events for key commands * (cut, copy, select-all, etc.) even though no character is inserted. */ function isKeypressCommand(nativeEvent) { return (nativeEvent.ctrlKey || nativeEvent.altKey || nativeEvent.metaKey) && // ctrlKey && altKey is equivalent to AltGr, and is not a command. !(nativeEvent.ctrlKey && nativeEvent.altKey); } /** * Translate native top level events into event types. * * @param {string} topLevelType * @return {object} */ function getCompositionEventType(topLevelType) { switch (topLevelType) { case 'topCompositionStart': return eventTypes.compositionStart; case 'topCompositionEnd': return eventTypes.compositionEnd; case 'topCompositionUpdate': return eventTypes.compositionUpdate; } } /** * Does our fallback best-guess model think this event signifies that * composition has begun? * * @param {string} topLevelType * @param {object} nativeEvent * @return {boolean} */ function isFallbackCompositionStart(topLevelType, nativeEvent) { return topLevelType === 'topKeyDown' && nativeEvent.keyCode === START_KEYCODE; } /** * Does our fallback mode think that this event is the end of composition? * * @param {string} topLevelType * @param {object} nativeEvent * @return {boolean} */ function isFallbackCompositionEnd(topLevelType, nativeEvent) { switch (topLevelType) { case 'topKeyUp': // Command keys insert or clear IME input. return END_KEYCODES.indexOf(nativeEvent.keyCode) !== -1; case 'topKeyDown': // Expect IME keyCode on each keydown. If we get any other // code we must have exited earlier. return nativeEvent.keyCode !== START_KEYCODE; case 'topKeyPress': case 'topMouseDown': case 'topBlur': // Events are not possible without cancelling IME. return true; default: return false; } } /** * Google Input Tools provides composition data via a CustomEvent, * with the `data` property populated in the `detail` object. If this * is available on the event object, use it. If not, this is a plain * composition event and we have nothing special to extract. * * @param {object} nativeEvent * @return {?string} */ function getDataFromCustomEvent(nativeEvent) { var detail = nativeEvent.detail; if (typeof detail === 'object' && 'data' in detail) { return detail.data; } return null; } // Track the current IME composition fallback object, if any. var currentComposition = null; /** * @return {?object} A SyntheticCompositionEvent. */ function extractCompositionEvent(topLevelType, targetInst, nativeEvent, nativeEventTarget) { var eventType; var fallbackData; if (canUseCompositionEvent) { eventType = getCompositionEventType(topLevelType); } else if (!currentComposition) { if (isFallbackCompositionStart(topLevelType, nativeEvent)) { eventType = eventTypes.compositionStart; } } else if (isFallbackCompositionEnd(topLevelType, nativeEvent)) { eventType = eventTypes.compositionEnd; } if (!eventType) { return null; } if (useFallbackCompositionData) { // The current composition is stored statically and must not be // overwritten while composition continues. if (!currentComposition && eventType === eventTypes.compositionStart) { currentComposition = FallbackCompositionState.getPooled(nativeEventTarget); } else if (eventType === eventTypes.compositionEnd) { if (currentComposition) { fallbackData = currentComposition.getData(); } } } var event = SyntheticCompositionEvent.getPooled(eventType, targetInst, nativeEvent, nativeEventTarget); if (fallbackData) { // Inject data generated from fallback path into the synthetic event. // This matches the property of native CompositionEventInterface. event.data = fallbackData; } else { var customData = getDataFromCustomEvent(nativeEvent); if (customData !== null) { event.data = customData; } } EventPropagators.accumulateTwoPhaseDispatches(event); return event; } /** * @param {string} topLevelType Record from `EventConstants`. * @param {object} nativeEvent Native browser event. * @return {?string} The string corresponding to this `beforeInput` event. */ function getNativeBeforeInputChars(topLevelType, nativeEvent) { switch (topLevelType) { case 'topCompositionEnd': return getDataFromCustomEvent(nativeEvent); case 'topKeyPress': /** * If native `textInput` events are available, our goal is to make * use of them. However, there is a special case: the spacebar key. * In Webkit, preventing default on a spacebar `textInput` event * cancels character insertion, but it *also* causes the browser * to fall back to its default spacebar behavior of scrolling the * page. * * Tracking at: * https://code.google.com/p/chromium/issues/detail?id=355103 * * To avoid this issue, use the keypress event as if no `textInput` * event is available. */ var which = nativeEvent.which; if (which !== SPACEBAR_CODE) { return null; } hasSpaceKeypress = true; return SPACEBAR_CHAR; case 'topTextInput': // Record the characters to be added to the DOM. var chars = nativeEvent.data; // If it's a spacebar character, assume that we have already handled // it at the keypress level and bail immediately. Android Chrome // doesn't give us keycodes, so we need to blacklist it. if (chars === SPACEBAR_CHAR && hasSpaceKeypress) { return null; } return chars; default: // For other native event types, do nothing. return null; } } /** * For browsers that do not provide the `textInput` event, extract the * appropriate string to use for SyntheticInputEvent. * * @param {string} topLevelType Record from `EventConstants`. * @param {object} nativeEvent Native browser event. * @return {?string} The fallback string for this `beforeInput` event. */ function getFallbackBeforeInputChars(topLevelType, nativeEvent) { // If we are currently composing (IME) and using a fallback to do so, // try to extract the composed characters from the fallback object. // If composition event is available, we extract a string only at // compositionevent, otherwise extract it at fallback events. if (currentComposition) { if (topLevelType === 'topCompositionEnd' || !canUseCompositionEvent && isFallbackCompositionEnd(topLevelType, nativeEvent)) { var chars = currentComposition.getData(); FallbackCompositionState.release(currentComposition); currentComposition = null; return chars; } return null; } switch (topLevelType) { case 'topPaste': // If a paste event occurs after a keypress, throw out the input // chars. Paste events should not lead to BeforeInput events. return null; case 'topKeyPress': /** * As of v27, Firefox may fire keypress events even when no character * will be inserted. A few possibilities: * * - `which` is `0`. Arrow keys, Esc key, etc. * * - `which` is the pressed key code, but no char is available. * Ex: 'AltGr + d` in Polish. There is no modified character for * this key combination and no character is inserted into the * document, but FF fires the keypress for char code `100` anyway. * No `input` event will occur. * * - `which` is the pressed key code, but a command combination is * being used. Ex: `Cmd+C`. No character is inserted, and no * `input` event will occur. */ if (nativeEvent.which && !isKeypressCommand(nativeEvent)) { return String.fromCharCode(nativeEvent.which); } return null; case 'topCompositionEnd': return useFallbackCompositionData ? null : nativeEvent.data; default: return null; } } /** * Extract a SyntheticInputEvent for `beforeInput`, based on either native * `textInput` or fallback behavior. * * @return {?object} A SyntheticInputEvent. */ function extractBeforeInputEvent(topLevelType, targetInst, nativeEvent, nativeEventTarget) { var chars; if (canUseTextInputEvent) { chars = getNativeBeforeInputChars(topLevelType, nativeEvent); } else { chars = getFallbackBeforeInputChars(topLevelType, nativeEvent); } // If no characters are being inserted, no BeforeInput event should // be fired. if (!chars) { return null; } var event = SyntheticInputEvent.getPooled(eventTypes.beforeInput, targetInst, nativeEvent, nativeEventTarget); event.data = chars; EventPropagators.accumulateTwoPhaseDispatches(event); return event; } /** * Create an `onBeforeInput` event to match * http://www.w3.org/TR/2013/WD-DOM-Level-3-Events-20131105/#events-inputevents. * * This event plugin is based on the native `textInput` event * available in Chrome, Safari, Opera, and IE. This event fires after * `onKeyPress` and `onCompositionEnd`, but before `onInput`. * * `beforeInput` is spec'd but not implemented in any browsers, and * the `input` event does not provide any useful information about what has * actually been added, contrary to the spec. Thus, `textInput` is the best * available event to identify the characters that have actually been inserted * into the target node. * * This plugin is also responsible for emitting `composition` events, thus * allowing us to share composition fallback code for both `beforeInput` and * `composition` event types. */ var BeforeInputEventPlugin = { eventTypes: eventTypes, extractEvents: function (topLevelType, targetInst, nativeEvent, nativeEventTarget) { return [extractCompositionEvent(topLevelType, targetInst, nativeEvent, nativeEventTarget), extractBeforeInputEvent(topLevelType, targetInst, nativeEvent, nativeEventTarget)]; } }; module.exports = BeforeInputEventPlugin; },{"135":135,"19":19,"20":20,"86":86,"90":90}],4:[function(_dereq_,module,exports){ /** * 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. * */ 'use strict'; /** * CSS properties which accept numbers but are not in units of "px". */ var isUnitlessNumber = { animationIterationCount: true, borderImageOutset: true, borderImageSlice: true, borderImageWidth: true, boxFlex: true, boxFlexGroup: true, boxOrdinalGroup: true, columnCount: true, flex: true, flexGrow: true, flexPositive: true, flexShrink: true, flexNegative: true, flexOrder: true, gridRow: true, gridColumn: true, fontWeight: true, lineClamp: true, lineHeight: true, opacity: true, order: true, orphans: true, tabSize: true, widows: true, zIndex: true, zoom: true, // SVG-related properties fillOpacity: true, floodOpacity: true, stopOpacity: true, strokeDasharray: true, strokeDashoffset: true, strokeMiterlimit: true, strokeOpacity: true, strokeWidth: true }; /** * @param {string} prefix vendor-specific prefix, eg: Webkit * @param {string} key style name, eg: transitionDuration * @return {string} style name prefixed with `prefix`, properly camelCased, eg: * WebkitTransitionDuration */ function prefixKey(prefix, key) { return prefix + key.charAt(0).toUpperCase() + key.substring(1); } /** * Support style names that may come passed in prefixed by adding permutations * of vendor prefixes. */ var prefixes = ['Webkit', 'ms', 'Moz', 'O']; // Using Object.keys here, or else the vanilla for-in loop makes IE8 go into an // infinite loop, because it iterates over the newly added props too. Object.keys(isUnitlessNumber).forEach(function (prop) { prefixes.forEach(function (prefix) { isUnitlessNumber[prefixKey(prefix, prop)] = isUnitlessNumber[prop]; }); }); /** * Most style properties can be unset by doing .style[prop] = '' but IE8 * doesn't like doing that with shorthand properties so for the properties that * IE8 breaks on, which are listed here, we instead unset each of the * individual properties. See http://bugs.jquery.com/ticket/12385. * The 4-value 'clock' properties like margin, padding, border-width seem to * behave without any problems. Curiously, list-style works too without any * special prodding. */ var shorthandPropertyExpansions = { background: { backgroundAttachment: true, backgroundColor: true, backgroundImage: true, backgroundPositionX: true, backgroundPositionY: true, backgroundRepeat: true }, backgroundPosition: { backgroundPositionX: true, backgroundPositionY: true }, border: { borderWidth: true, borderStyle: true, borderColor: true }, borderBottom: { borderBottomWidth: true, borderBottomStyle: true, borderBottomColor: true }, borderLeft: { borderLeftWidth: true, borderLeftStyle: true, borderLeftColor: true }, borderRight: { borderRightWidth: true, borderRightStyle: true, borderRightColor: true }, borderTop: { borderTopWidth: true, borderTopStyle: true, borderTopColor: true }, font: { fontStyle: true, fontVariant: true, fontWeight: true, fontSize: true, lineHeight: true, fontFamily: true }, outline: { outlineWidth: true, outlineStyle: true, outlineColor: true } }; var CSSProperty = { isUnitlessNumber: isUnitlessNumber, shorthandPropertyExpansions: shorthandPropertyExpansions }; module.exports = CSSProperty; },{}],5:[function(_dereq_,module,exports){ /** * 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. * */ 'use strict'; var CSSProperty = _dereq_(4); var ExecutionEnvironment = _dereq_(135); var camelizeStyleName = _dereq_(137); var dangerousStyleValue = _dereq_(103); var getComponentName = _dereq_(108); var hyphenateStyleName = _dereq_(148); var memoizeStringOnly = _dereq_(152); var warning = _dereq_(156); if ("development" !== 'production') { var _require = _dereq_(48), getCurrentFiberOwnerName = _require.getCurrentFiberOwnerName; } var processStyleName = memoizeStringOnly(function (styleName) { return hyphenateStyleName(styleName); }); var hasShorthandPropertyBug = false; var styleFloatAccessor = 'cssFloat'; if (ExecutionEnvironment.canUseDOM) { var tempStyle = document.createElement('div').style; try { // IE8 throws "Invalid argument." if resetting shorthand style properties. tempStyle.font = ''; } catch (e) { hasShorthandPropertyBug = true; } // IE8 only supports accessing cssFloat (standard) as styleFloat if (document.documentElement.style.cssFloat === undefined) { styleFloatAccessor = 'styleFloat'; } } if ("development" !== 'production') { // 'msTransform' is correct, but the other prefixes should be capitalized var badVendoredStyleNamePattern = /^(?:webkit|moz|o)[A-Z]/; // style values shouldn't contain a semicolon var badStyleValueWithSemicolonPattern = /;\s*$/; var warnedStyleNames = {}; var warnedStyleValues = {}; var warnedForNaNValue = false; var warnHyphenatedStyleName = function (name, owner) { if (warnedStyleNames.hasOwnProperty(name) && warnedStyleNames[name]) { return; } warnedStyleNames[name] = true; "development" !== 'production' ? warning(false, 'Unsupported style property %s. Did you mean %s?%s', name, camelizeStyleName(name), checkRenderMessage(owner)) : void 0; }; var warnBadVendoredStyleName = function (name, owner) { if (warnedStyleNames.hasOwnProperty(name) && warnedStyleNames[name]) { return; } warnedStyleNames[name] = true; "development" !== 'production' ? warning(false, 'Unsupported vendor-prefixed style property %s. Did you mean %s?%s', name, name.charAt(0).toUpperCase() + name.slice(1), checkRenderMessage(owner)) : void 0; }; var warnStyleValueWithSemicolon = function (name, value, owner) { if (warnedStyleValues.hasOwnProperty(value) && warnedStyleValues[value]) { return; } warnedStyleValues[value] = true; "development" !== 'production' ? warning(false, 'Style property values shouldn\'t contain a semicolon.%s ' + 'Try "%s: %s" instead.', checkRenderMessage(owner), name, value.replace(badStyleValueWithSemicolonPattern, '')) : void 0; }; var warnStyleValueIsNaN = function (name, value, owner) { if (warnedForNaNValue) { return; } warnedForNaNValue = true; "development" !== 'production' ? warning(false, '`NaN` is an invalid value for the `%s` css style property.%s', name, checkRenderMessage(owner)) : void 0; }; var checkRenderMessage = function (owner) { var ownerName; if (owner != null) { // Stack passes the owner manually all the way to CSSPropertyOperations. ownerName = getComponentName(owner); } else { // Fiber doesn't pass it but uses ReactDebugCurrentFiber to track it. // It is only enabled in development and tracks host components too. ownerName = getCurrentFiberOwnerName(); // TODO: also report the stack. } if (ownerName) { return ' Check the render method of `' + ownerName + '`.'; } return ''; }; /** * @param {string} name * @param {*} value * @param {ReactDOMComponent} component */ var warnValidStyle = function (name, value, component) { var owner; if (component) { owner = component._currentElement._owner; } if (name.indexOf('-') > -1) { warnHyphenatedStyleName(name, owner); } else if (badVendoredStyleNamePattern.test(name)) { warnBadVendoredStyleName(name, owner); } else if (badStyleValueWithSemicolonPattern.test(value)) { warnStyleValueWithSemicolon(name, value, owner); } if (typeof value === 'number' && isNaN(value)) { warnStyleValueIsNaN(name, value, owner); } }; } /** * Operations for dealing with CSS properties. */ var CSSPropertyOperations = { /** * Serializes a mapping of style properties for use as inline styles: * * > createMarkupForStyles({width: '200px', height: 0}) * "width:200px;height:0;" * * Undefined values are ignored so that declarative programming is easier. * The result should be HTML-escaped before insertion into the DOM. * * @param {object} styles * @param {ReactDOMComponent} component * @return {?string} */ createMarkupForStyles: function (styles, component) { var serialized = ''; for (var styleName in styles) { if (!styles.hasOwnProperty(styleName)) { continue; } var styleValue = styles[styleName]; if ("development" !== 'production') { warnValidStyle(styleName, styleValue, component); } if (styleValue != null) { serialized += processStyleName(styleName) + ':'; serialized += dangerousStyleValue(styleName, styleValue, component) + ';'; } } return serialized || null; }, /** * Sets the value for multiple styles on a node. If a value is specified as * '' (empty string), the corresponding style property will be unset. * * @param {DOMElement} node * @param {object} styles * @param {ReactDOMComponent} component */ setValueForStyles: function (node, styles, component) { var style = node.style; for (var styleName in styles) { if (!styles.hasOwnProperty(styleName)) { continue; } if ("development" !== 'production') { warnValidStyle(styleName, styles[styleName], component); } var styleValue = dangerousStyleValue(styleName, styles[styleName], component); if (styleName === 'float' || styleName === 'cssFloat') { styleName = styleFloatAccessor; } if (styleValue) { style[styleName] = styleValue; } else { var expansion = hasShorthandPropertyBug && CSSProperty.shorthandPropertyExpansions[styleName]; if (expansion) { // Shorthand property that IE8 won't like unsetting, so unset each // component to placate it for (var individualStyleName in expansion) { style[individualStyleName] = ''; } } else { style[styleName] = ''; } } } } }; module.exports = CSSPropertyOperations; },{"103":103,"108":108,"135":135,"137":137,"148":148,"152":152,"156":156,"4":4,"48":48}],6:[function(_dereq_,module,exports){ /** * 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. * * */ 'use strict'; var _prodInvariant = _dereq_(124); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var PooledClass = _dereq_(23); var invariant = _dereq_(149); /** * A specialized pseudo-event module to help keep track of components waiting to * be notified when their DOM representations are available for use. * * This implements `PooledClass`, so you should never need to instantiate this. * Instead, use `CallbackQueue.getPooled()`. * * @class ReactMountReady * @implements PooledClass * @internal */ var CallbackQueue = function () { function CallbackQueue(arg) { _classCallCheck(this, CallbackQueue); this._callbacks = null; this._contexts = null; this._arg = arg; } /** * Enqueues a callback to be invoked when `notifyAll` is invoked. * * @param {function} callback Invoked when `notifyAll` is invoked. * @param {?object} context Context to call `callback` with. * @internal */ CallbackQueue.prototype.enqueue = function enqueue(callback, context) { this._callbacks = this._callbacks || []; this._callbacks.push(callback); this._contexts = this._contexts || []; this._contexts.push(context); }; /** * Invokes all enqueued callbacks and clears the queue. This is invoked after * the DOM representation of a component has been created or updated. * * @internal */ CallbackQueue.prototype.notifyAll = function notifyAll() { var callbacks = this._callbacks; var contexts = this._contexts; var arg = this._arg; if (callbacks && contexts) { !(callbacks.length === contexts.length) ? "development" !== 'production' ? invariant(false, 'Mismatched list of contexts in callback queue') : _prodInvariant('24') : void 0; this._callbacks = null; this._contexts = null; for (var i = 0; i < callbacks.length; i++) { callbacks[i].call(contexts[i], arg); } callbacks.length = 0; contexts.length = 0; } }; CallbackQueue.prototype.checkpoint = function checkpoint() { return this._callbacks ? this._callbacks.length : 0; }; CallbackQueue.prototype.rollback = function rollback(len) { if (this._callbacks && this._contexts) { this._callbacks.length = len; this._contexts.length = len; } }; /** * Resets the internal queue. * * @internal */ CallbackQueue.prototype.reset = function reset() { this._callbacks = null; this._contexts = null; }; /** * `PooledClass` looks for this. */ CallbackQueue.prototype.destructor = function destructor() { this.reset(); }; return CallbackQueue; }(); module.exports = PooledClass.addPoolingTo(CallbackQueue); },{"124":124,"149":149,"23":23}],7:[function(_dereq_,module,exports){ /** * 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. * */ 'use strict'; var EventPluginHub = _dereq_(16); var EventPropagators = _dereq_(19); var ExecutionEnvironment = _dereq_(135); var ReactControlledComponent = _dereq_(30); var ReactDOMComponentTree = _dereq_(34); var ReactGenericBatching = _dereq_(57); var SyntheticEvent = _dereq_(88); var inputValueTracking = _dereq_(119); var getEventTarget = _dereq_(112); var isEventSupported = _dereq_(121); var isTextInputElement = _dereq_(122); var eventTypes = { change: { phasedRegistrationNames: { bubbled: 'onChange', captured: 'onChangeCapture' }, dependencies: ['topBlur', 'topChange', 'topClick', 'topFocus', 'topInput', 'topKeyDown', 'topKeyUp', 'topSelectionChange'] } }; function createAndAccumulateChangeEvent(inst, nativeEvent, target) { var event = SyntheticEvent.getPooled(eventTypes.change, inst, nativeEvent, target); event.type = 'change'; // Flag this event loop as needing state restore. ReactControlledComponent.enqueueStateRestore(target); EventPropagators.accumulateTwoPhaseDispatches(event); return event; } /** * For IE shims */ var activeElement = null; var activeElementInst = null; /** * SECTION: handle `change` event */ function shouldUseChangeEvent(elem) { var nodeName = elem.nodeName && elem.nodeName.toLowerCase(); return nodeName === 'select' || nodeName === 'input' && elem.type === 'file'; } var doesChangeEventBubble = false; if (ExecutionEnvironment.canUseDOM) { // See `handleChange` comment below doesChangeEventBubble = isEventSupported('change') && (!document.documentMode || document.documentMode > 8); } function manualDispatchChangeEvent(nativeEvent) { var event = createAndAccumulateChangeEvent(activeElementInst, nativeEvent, getEventTarget(nativeEvent)); // If change and propertychange bubbled, we'd just bind to it like all the // other events and have it go through ReactBrowserEventEmitter. Since it // doesn't, we manually listen for the events and so we have to enqueue and // process the abstract event manually. // // Batching is necessary here in order to ensure that all event handlers run // before the next rerender (including event handlers attached to ancestor // elements instead of directly on the input). Without this, controlled // components don't work properly in conjunction with event bubbling because // the component is rerendered and the value reverted before all the event // handlers can run. See https://github.com/facebook/react/issues/708. ReactGenericBatching.batchedUpdates(runEventInBatch, event); } function runEventInBatch(event) { EventPluginHub.enqueueEvents(event); EventPluginHub.processEventQueue(false); } function startWatchingForChangeEventIE8(target, targetInst) { activeElement = target; activeElementInst = targetInst; activeElement.attachEvent('onchange', manualDispatchChangeEvent); } function stopWatchingForChangeEventIE8() { if (!activeElement) { return; } activeElement.detachEvent('onchange', manualDispatchChangeEvent); activeElement = null; activeElementInst = null; } function getInstIfValueChanged(targetInst) { if (inputValueTracking.updateValueIfChanged(targetInst)) { return targetInst; } } function getTargetInstForChangeEvent(topLevelType, targetInst) { if (topLevelType === 'topChange') { return targetInst; } } function handleEventsForChangeEventIE8(topLevelType, target, targetInst) { if (topLevelType === 'topFocus') { // stopWatching() should be a noop here but we call it just in case we // missed a blur event somehow. stopWatchingForChangeEventIE8(); startWatchingForChangeEventIE8(target, targetInst); } else if (topLevelType === 'topBlur') { stopWatchingForChangeEventIE8(); } } /** * SECTION: handle `input` event */ var isInputEventSupported = false; if (ExecutionEnvironment.canUseDOM) { // IE9 claims to support the input event but fails to trigger it when // deleting text, so we ignore its input events. isInputEventSupported = isEventSupported('input') && (!document.documentMode || document.documentMode > 9); } /** * (For IE <=9) Starts tracking propertychange events on the passed-in element * and override the value property so that we can distinguish user events from * value changes in JS. */ function startWatchingForValueChange(target, targetInst) { activeElement = target; activeElementInst = targetInst; activeElement.attachEvent('onpropertychange', handlePropertyChange); } /** * (For IE <=9) Removes the event listeners from the currently-tracked element, * if any exists. */ function stopWatchingForValueChange() { if (!activeElement) { return; } activeElement.detachEvent('onpropertychange', handlePropertyChange); activeElement = null; activeElementInst = null; } /** * (For IE <=9) Handles a propertychange event, sending a `change` event if * the value of the active element has changed. */ function handlePropertyChange(nativeEvent) { if (nativeEvent.propertyName !== 'value') { return; } if (getInstIfValueChanged(activeElementInst)) { manualDispatchChangeEvent(nativeEvent); } } function handleEventsForInputEventPolyfill(topLevelType, target, targetInst) { if (topLevelType === 'topFocus') { // In IE8, we can capture almost all .value changes by adding a // propertychange handler and looking for events with propertyName // equal to 'value' // In IE9, propertychange fires for most input events but is buggy and // doesn't fire when text is deleted, but conveniently, selectionchange // appears to fire in all of the remaining cases so we catch those and // forward the event if the value has changed // In either case, we don't want to call the event handler if the value // is changed from JS so we redefine a setter for `.value` that updates // our activeElementValue variable, allowing us to ignore those changes // // stopWatching() should be a noop here but we call it just in case we // missed a blur event somehow. stopWatchingForValueChange(); startWatchingForValueChange(target, targetInst); } else if (topLevelType === 'topBlur') { stopWatchingForValueChange(); } } // For IE8 and IE9. function getTargetInstForInputEventPolyfill(topLevelType, targetInst) { if (topLevelType === 'topSelectionChange' || topLevelType === 'topKeyUp' || topLevelType === 'topKeyDown') { // On the selectionchange event, the target is just document which isn't // helpful for us so just check activeElement instead. // // 99% of the time, keydown and keyup aren't necessary. IE8 fails to fire // propertychange on the first input event after setting `value` from a // script and fires only keydown, keypress, keyup. Catching keyup usually // gets it and catching keydown lets us fire an event for the first // keystroke if user does a key repeat (it'll be a little delayed: right // before the second keystroke). Other input methods (e.g., paste) seem to // fire selectionchange normally. return getInstIfValueChanged(activeElementInst); } } /** * SECTION: handle `click` event */ function shouldUseClickEvent(elem) { // Use the `click` event to detect changes to checkbox and radio inputs. // This approach works across all browsers, whereas `change` does not fire // until `blur` in IE8. var nodeName = elem.nodeName; return nodeName && nodeName.toLowerCase() === 'input' && (elem.type === 'checkbox' || elem.type === 'radio'); } function getTargetInstForClickEvent(topLevelType, targetInst) { if (topLevelType === 'topClick') { return getInstIfValueChanged(targetInst); } } function getTargetInstForInputOrChangeEvent(topLevelType, targetInst) { if (topLevelType === 'topInput' || topLevelType === 'topChange') { return getInstIfValueChanged(targetInst); } } /** * This plugin creates an `onChange` event that normalizes change events * across form elements. This event fires at a time when it's possible to * change the element's value without seeing a flicker. * * Supported elements are: * - input (see `isTextInputElement`) * - textarea * - select */ var ChangeEventPlugin = { eventTypes: eventTypes, _isInputEventSupported: isInputEventSupported, extractEvents: function (topLevelType, targetInst, nativeEvent, nativeEventTarget) { var targetNode = targetInst ? ReactDOMComponentTree.getNodeFromInstance(targetInst) : window; var getTargetInstFunc, handleEventFunc; if (shouldUseChangeEvent(targetNode)) { if (doesChangeEventBubble) { getTargetInstFunc = getTargetInstForChangeEvent; } else { handleEventFunc = handleEventsForChangeEventIE8; } } else if (isTextInputElement(targetNode)) { if (isInputEventSupported) { getTargetInstFunc = getTargetInstForInputOrChangeEvent; } else { getTargetInstFunc = getTargetInstForInputEventPolyfill; handleEventFunc = handleEventsForInputEventPolyfill; } } else if (shouldUseClickEvent(targetNode)) { getTargetInstFunc = getTargetInstForClickEvent; } if (getTargetInstFunc) { var inst = getTargetInstFunc(topLevelType, targetInst); if (inst) { var event = createAndAccumulateChangeEvent(inst, nativeEvent, nativeEventTarget); return event; } } if (handleEventFunc) { handleEventFunc(topLevelType, targetNode, targetInst); } } }; module.exports = ChangeEventPlugin; },{"112":112,"119":119,"121":121,"122":122,"135":135,"16":16,"19":19,"30":30,"34":34,"57":57,"88":88}],8:[function(_dereq_,module,exports){ /** * 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. * */ 'use strict'; var DOMLazyTree = _dereq_(10); var Danger = _dereq_(14); var ReactDOMComponentTree = _dereq_(34); var ReactInstrumentation = _dereq_(62); var createMicrosoftUnsafeLocalFunction = _dereq_(102); var setInnerHTML = _dereq_(125); var setTextContent = _dereq_(126); function getNodeAfter(parentNode, node) { // Special case for text components, which return [open, close] comments // from getHostNode. if (Array.isArray(node)) { node = node[1]; } return node ? node.nextSibling : parentNode.firstChild; } /** * Inserts `childNode` as a child of `parentNode` at the `index`. * * @param {DOMElement} parentNode Parent node in which to insert. * @param {DOMElement} childNode Child node to insert. * @param {number} index Index at which to insert the child. * @internal */ var insertChildAt = createMicrosoftUnsafeLocalFunction(function (parentNode, childNode, referenceNode) { // We rely exclusively on `insertBefore(node, null)` instead of also using // `appendChild(node)`. (Using `undefined` is not allowed by all browsers so // we are careful to use `null`.) parentNode.insertBefore(childNode, referenceNode); }); function insertLazyTreeChildAt(parentNode, childTree, referenceNode) { DOMLazyTree.insertTreeBefore(parentNode, childTree, referenceNode); } function moveChild(parentNode, childNode, referenceNode) { if (Array.isArray(childNode)) { moveDelimitedText(parentNode, childNode[0], childNode[1], referenceNode); } else { insertChildAt(parentNode, childNode, referenceNode); } } function removeChild(parentNode, childNode) { if (Array.isArray(childNode)) { var closingComment = childNode[1]; childNode = childNode[0]; removeDelimitedText(parentNode, childNode, closingComment); parentNode.removeChild(closingComment); } parentNode.removeChild(childNode); } function moveDelimitedText(parentNode, openingComment, closingComment, referenceNode) { var node = openingComment; while (true) { var nextNode = node.nextSibling; insertChildAt(parentNode, node, referenceNode); if (node === closingComment) { break; } node = nextNode; } } function removeDelimitedText(parentNode, startNode, closingComment) { while (true) { var node = startNode.nextSibling; if (node === closingComment) { // The closing comment is removed by ReactMultiChild. break; } else { parentNode.removeChild(node); } } } function replaceDelimitedText(openingComment, closingComment, stringText) { var parentNode = openingComment.parentNode; var nodeAfterComment = openingComment.nextSibling; if (nodeAfterComment === closingComment) { // There are no text nodes between the opening and closing comments; insert // a new one if stringText isn't empty. if (stringText) { insertChildAt(parentNode, document.createTextNode(stringText), nodeAfterComment); } } else { if (stringText) { // Set the text content of the first node after the opening comment, and // remove all following nodes up until the closing comment. setTextContent(nodeAfterComment, stringText); removeDelimitedText(parentNode, nodeAfterComment, closingComment); } else { removeDelimitedText(parentNode, openingComment, closingComment); } } if ("development" !== 'production') { ReactInstrumentation.debugTool.onHostOperation({ instanceID: ReactDOMComponentTree.getInstanceFromNode(openingComment)._debugID, type: 'replace text', payload: stringText }); } } var dangerouslyReplaceNodeWithMarkup = Danger.dangerouslyReplaceNodeWithMarkup; if ("development" !== 'production') { dangerouslyReplaceNodeWithMarkup = function (oldChild, markup, prevInstance) { Danger.dangerouslyReplaceNodeWithMarkup(oldChild, markup); if (prevInstance._debugID !== 0) { ReactInstrumentation.debugTool.onHostOperation({ instanceID: prevInstance._debugID, type: 'replace with', payload: markup.toString() }); } else { var nextInstance = ReactDOMComponentTree.getInstanceFromNode(markup.node); if (nextInstance._debugID !== 0) { ReactInstrumentation.debugTool.onHostOperation({ instanceID: nextInstance._debugID, type: 'mount', payload: markup.toString() }); } } }; } /** * Operations for updating with DOM children. */ var DOMChildrenOperations = { dangerouslyReplaceNodeWithMarkup: dangerouslyReplaceNodeWithMarkup, replaceDelimitedText: replaceDelimitedText, /** * Updates a component's children by processing a series of updates. The * update configurations are each expected to have a `parentNode` property. * * @param {array<object>} updates List of update configurations. * @internal */ processUpdates: function (parentNode, updates) { if ("development" !== 'production') { var parentNodeDebugID = ReactDOMComponentTree.getInstanceFromNode(parentNode)._debugID; } for (var k = 0; k < updates.length; k++) { var update = updates[k]; switch (update.type) { case 'INSERT_MARKUP': insertLazyTreeChildAt(parentNode, update.content, getNodeAfter(parentNode, update.afterNode)); if ("development" !== 'production') { ReactInstrumentation.debugTool.onHostOperation({ instanceID: parentNodeDebugID, type: 'insert child', payload: { toIndex: update.toIndex, content: update.content.toString() } }); } break; case 'MOVE_EXISTING': moveChild(parentNode, update.fromNode, getNodeAfter(parentNode, update.afterNode)); if ("development" !== 'production') { ReactInstrumentation.debugTool.onHostOperation({ instanceID: parentNodeDebugID, type: 'move child', payload: { fromIndex: update.fromIndex, toIndex: update.toIndex } }); } break; case 'SET_MARKUP': setInnerHTML(parentNode, update.content); if ("development" !== 'production') { ReactInstrumentation.debugTool.onHostOperation({ instanceID: parentNodeDebugID, type: 'replace children', payload: update.content.toString() }); } break; case 'TEXT_CONTENT': setTextContent(parentNode, update.content); if ("development" !== 'production') { ReactInstrumentation.debugTool.onHostOperation({ instanceID: parentNodeDebugID, type: 'replace text', payload: update.content.toString() }); } break; case 'REMOVE_NODE': removeChild(parentNode, update.fromNode); if ("development" !== 'production') { ReactInstrumentation.debugTool.onHostOperation({ instanceID: parentNodeDebugID, type: 'remove child', payload: { fromIndex: update.fromIndex } }); } break; } } } }; module.exports = DOMChildrenOperations; },{"10":10,"102":102,"125":125,"126":126,"14":14,"34":34,"62":62}],9:[function(_dereq_,module,exports){ /** * 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. * */ 'use strict'; /** * Module that is injectable into `EventPluginHub`, that specifies a * deterministic ordering of `EventPlugin`s. A convenient way to reason about * plugins, without having to package every one of them. This is better than * having plugins be ordered in the same order that they are injected because * that ordering would be influenced by the packaging order. * `ResponderEventPlugin` must occur before `SimpleEventPlugin` so that * preventing default on events is convenient in `SimpleEventPlugin` handlers. */ var DOMEventPluginOrder = ['ResponderEventPlugin', 'SimpleEventPlugin', 'TapEventPlugin', 'EnterLeaveEventPlugin', 'ChangeEventPlugin', 'SelectEventPlugin', 'BeforeInputEventPlugin']; module.exports = DOMEventPluginOrder; },{}],10:[function(_dereq_,module,exports){ /** * Copyright 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'; var DOMNamespaces = _dereq_(11); var setInnerHTML = _dereq_(125); var createMicrosoftUnsafeLocalFunction = _dereq_(102); var setTextContent = _dereq_(126); var ELEMENT_NODE_TYPE = 1; var DOCUMENT_FRAGMENT_NODE_TYPE = 11; /** * In IE (8-11) and Edge, appending nodes with no children is dramatically * faster than appending a full subtree, so we essentially queue up the * .appendChild calls here and apply them so each node is added to its parent * before any children are added. * * In other browsers, doing so is slower or neutral compared to the other order * (in Firefox, twice as slow) so we only do this inversion in IE. * * See https://github.com/spicyj/innerhtml-vs-createelement-vs-clonenode. */ var enableLazy = typeof document !== 'undefined' && typeof document.documentMode === 'number' || typeof navigator !== 'undefined' && typeof navigator.userAgent === 'string' && /\bEdge\/\d/.test(navigator.userAgent); function insertTreeChildren(tree) { if (!enableLazy) { return; } var node = tree.node; var children = tree.children; if (children.length) { for (var i = 0; i < children.length; i++) { insertTreeBefore(node, children[i], null); } } else if (tree.html != null) { setInnerHTML(node, tree.html); } else if (tree.text != null) { setTextContent(node, tree.text); } } var insertTreeBefore = createMicrosoftUnsafeLocalFunction(function (parentNode, tree, referenceNode) { // DocumentFragments aren't actually part of the DOM after insertion so // appending children won't update the DOM. We need to ensure the fragment // is properly populated first, breaking out of our lazy approach for just // this level. Also, some <object> plugins (like Flash Player) will read // <param> nodes immediately upon insertion into the DOM, so <object> // must also be populated prior to insertion into the DOM. if (tree.node.nodeType === DOCUMENT_FRAGMENT_NODE_TYPE || tree.node.nodeType === ELEMENT_NODE_TYPE && tree.node.nodeName.toLowerCase() === 'object' && (tree.node.namespaceURI == null || tree.node.namespaceURI === DOMNamespaces.html)) { insertTreeChildren(tree); parentNode.insertBefore(tree.node, referenceNode); } else { parentNode.insertBefore(tree.node, referenceNode); insertTreeChildren(tree); } }); function replaceChildWithTree(oldNode, newTree) { oldNode.parentNode.replaceChild(newTree.node, oldNode); insertTreeChildren(newTree); } function queueChild(parentTree, childTree) { if (enableLazy) { parentTree.children.push(childTree); } else { parentTree.node.appendChild(childTree.node); } } function queueHTML(tree, html) { if (enableLazy) { tree.html = html; } else { setInnerHTML(tree.node, html); } } function queueText(tree, text) { if (enableLazy) { tree.text = text; } else { setTextContent(tree.node, text); } } function toString() { return this.node.nodeName; } function DOMLazyTree(node) { return { node: node, children: [], html: null, text: null, toString: toString }; } DOMLazyTree.insertTreeBefore = insertTreeBefore; DOMLazyTree.replaceChildWithTree = replaceChildWithTree; DOMLazyTree.queueChild = queueChild; DOMLazyTree.queueHTML = queueHTML; DOMLazyTree.queueText = queueText; module.exports = DOMLazyTree; },{"102":102,"11":11,"125":125,"126":126}],11:[function(_dereq_,module,exports){ /** * 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. * */ 'use strict'; var DOMNamespaces = { html: 'http://www.w3.org/1999/xhtml', mathml: 'http://www.w3.org/1998/Math/MathML', svg: 'http://www.w3.org/2000/svg' }; module.exports = DOMNamespaces; },{}],12:[function(_dereq_,module,exports){ /** * 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. * */ 'use strict'; var _prodInvariant = _dereq_(124); var invariant = _dereq_(149); function checkMask(value, bitmask) { return (value & bitmask) === bitmask; } var DOMPropertyInjection = { /** * Mapping from normalized, camelcased property names to a configuration that * specifies how the associated DOM property should be accessed or rendered. */ MUST_USE_PROPERTY: 0x1, HAS_BOOLEAN_VALUE: 0x4, HAS_NUMERIC_VALUE: 0x8, HAS_POSITIVE_NUMERIC_VALUE: 0x10 | 0x8, HAS_OVERLOADED_BOOLEAN_VALUE: 0x20, /** * Inject some specialized knowledge about the DOM. This takes a config object * with the following properties: * * isCustomAttribute: function that given an attribute name will return true * if it can be inserted into the DOM verbatim. Useful for data-* or aria-* * attributes where it's impossible to enumerate all of the possible * attribute names, * * Properties: object mapping DOM property name to one of the * DOMPropertyInjection constants or null. If your attribute isn't in here, * it won't get written to the DOM. * * DOMAttributeNames: object mapping React attribute name to the DOM * attribute name. Attribute names not specified use the **lowercase** * normalized name. * * DOMAttributeNamespaces: object mapping React attribute name to the DOM * attribute namespace URL. (Attribute names not specified use no namespace.) * * DOMPropertyNames: similar to DOMAttributeNames but for DOM properties. * Property names not specified use the normalized name. * * DOMMutationMethods: Properties that require special mutation methods. If * `value` is undefined, the mutation method should unset the property. * * @param {object} domPropertyConfig the config as described above. */ injectDOMPropertyConfig: function (domPropertyConfig) { var Injection = DOMPropertyInjection; var Properties = domPropertyConfig.Properties || {}; var DOMAttributeNamespaces = domPropertyConfig.DOMAttributeNamespaces || {}; var DOMAttributeNames = domPropertyConfig.DOMAttributeNames || {}; var DOMPropertyNames = domPropertyConfig.DOMPropertyNames || {}; var DOMMutationMethods = domPropertyConfig.DOMMutationMethods || {}; if (domPropertyConfig.isCustomAttribute) { DOMProperty._isCustomAttributeFunctions.push(domPropertyConfig.isCustomAttribute); } for (var propName in Properties) { !!DOMProperty.properties.hasOwnProperty(propName) ? "development" !== 'production' ? invariant(false, 'injectDOMPropertyConfig(...): You\'re trying to inject DOM property \'%s\' which has already been injected. You may be accidentally injecting the same DOM property config twice, or you may be injecting two configs that have conflicting property names.', propName) : _prodInvariant('48', propName) : void 0; var lowerCased = propName.toLowerCase(); var propConfig = Properties[propName]; var propertyInfo = { attributeName: lowerCased, attributeNamespace: null, propertyName: propName, mutationMethod: null, mustUseProperty: checkMask(propConfig, Injection.MUST_USE_PROPERTY), hasBooleanValue: checkMask(propConfig, Injection.HAS_BOOLEAN_VALUE), hasNumericValue: checkMask(propConfig, Injection.HAS_NUMERIC_VALUE), hasPositiveNumericValue: checkMask(propConfig, Injection.HAS_POSITIVE_NUMERIC_VALUE), hasOverloadedBooleanValue: checkMask(propConfig, Injection.HAS_OVERLOADED_BOOLEAN_VALUE) }; !(propertyInfo.hasBooleanValue + propertyInfo.hasNumericValue + propertyInfo.hasOverloadedBooleanValue <= 1) ? "development" !== 'production' ? invariant(false, 'DOMProperty: Value can be one of boolean, overloaded boolean, or numeric value, but not a combination: %s', propName) : _prodInvariant('50', propName) : void 0; if ("development" !== 'production') { DOMProperty.getPossibleStandardName[lowerCased] = propName; } if (DOMAttributeNames.hasOwnProperty(propName)) { var attributeName = DOMAttributeNames[propName]; propertyInfo.attributeName = attributeName; if ("development" !== 'production') { DOMProperty.getPossibleStandardName[attributeName] = propName; } } if (DOMAttributeNamespaces.hasOwnProperty(propName)) { propertyInfo.attributeNamespace = DOMAttributeNamespaces[propName]; } if (DOMPropertyNames.hasOwnProperty(propName)) { propertyInfo.propertyName = DOMPropertyNames[propName]; } if (DOMMutationMethods.hasOwnProperty(propName)) { propertyInfo.mutationMethod = DOMMutationMethods[propName]; } DOMProperty.properties[propName] = propertyInfo; } } }; /* eslint-disable max-len */ 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'; /* eslint-enable max-len */ /** * DOMProperty exports lookup objects that can be used like functions: * * > DOMProperty.isValid['id'] * true * > DOMProperty.isValid['foobar'] * undefined * * Although this may be confusing, it performs better in general. * * @see http://jsperf.com/key-exists * @see http://jsperf.com/key-missing */ var DOMProperty = { ID_ATTRIBUTE_NAME: 'data-reactid', ROOT_ATTRIBUTE_NAME: 'data-reactroot', ATTRIBUTE_NAME_START_CHAR: ATTRIBUTE_NAME_START_CHAR, ATTRIBUTE_NAME_CHAR: ATTRIBUTE_NAME_START_CHAR + '\\-.0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040', /** * Map from property "standard name" to an object with info about how to set * the property in the DOM. Each object contains: * * attributeName: * Used when rendering markup or with `*Attribute()`. * attributeNamespace * propertyName: * Used on DOM node instances. (This includes properties that mutate due to * external factors.) * mutationMethod: * If non-null, used instead of the property or `setAttribute()` after * initial render. * mustUseProperty: * Whether the property must be accessed and mutated as an object property. * hasBooleanValue: * Whether the property should be removed when set to a falsey value. * hasNumericValue: * Whether the property must be numeric or parse as a numeric and should be * removed when set to a falsey value. * hasPositiveNumericValue: * Whether the property must be positive numeric or parse as a positive * numeric and should be removed when set to a falsey value. * hasOverloadedBooleanValue: * Whether the property can be used as a flag as well as with a value. * Removed when strictly equal to false; present without a value when * strictly equal to true; present with a value otherwise. */ properties: {}, /** * Mapping from lowercase property names to the properly cased version, used * to warn in the case of missing properties. Available only in __DEV__. * * autofocus is predefined, because adding it to the property whitelist * causes unintended side effects. * * @type {Object} */ getPossibleStandardName: "development" !== 'production' ? { autofocus: 'autoFocus' } : null, /** * All of the isCustomAttribute() functions that have been injected. */ _isCustomAttributeFunctions: [], /** * Checks whether a property name is a custom attribute. * @method */ isCustomAttribute: function (attributeName) { for (var i = 0; i < DOMProperty._isCustomAttributeFunctions.length; i++) { var isCustomAttributeFn = DOMProperty._isCustomAttributeFunctions[i]; if (isCustomAttributeFn(attributeName)) { return true; } } return false; }, injection: DOMPropertyInjection }; module.exports = DOMProperty; },{"124":124,"149":149}],13:[function(_dereq_,module,exports){ /** * 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. * */ 'use strict'; var DOMProperty = _dereq_(12); var ReactDOMComponentTree = _dereq_(34); var ReactInstrumentation = _dereq_(62); var quoteAttributeValueForBrowser = _dereq_(123); var warning = _dereq_(156); var VALID_ATTRIBUTE_NAME_REGEX = new RegExp('^[' + DOMProperty.ATTRIBUTE_NAME_START_CHAR + '][' + DOMProperty.ATTRIBUTE_NAME_CHAR + ']*$'); var illegalAttributeNameCache = {}; var validatedAttributeNameCache = {}; function isAttributeNameSafe(attributeName) { if (validatedAttributeNameCache.hasOwnProperty(attributeName)) { return true; } if (illegalAttributeNameCache.hasOwnProperty(attributeName)) { return false; } if (VALID_ATTRIBUTE_NAME_REGEX.test(attributeName)) { validatedAttributeNameCache[attributeName] = true; return true; } illegalAttributeNameCache[attributeName] = true; "development" !== 'production' ? warning(false, 'Invalid attribute name: `%s`', attributeName) : void 0; return false; } function shouldIgnoreValue(propertyInfo, value) { return value == null || propertyInfo.hasBooleanValue && !value || propertyInfo.hasNumericValue && isNaN(value) || propertyInfo.hasPositiveNumericValue && value < 1 || propertyInfo.hasOverloadedBooleanValue && value === false; } /** * Operations for dealing with DOM properties. */ var DOMPropertyOperations = { /** * Creates markup for the ID property. * * @param {string} id Unescaped ID. * @return {string} Markup string. */ createMarkupForID: function (id) { return DOMProperty.ID_ATTRIBUTE_NAME + '=' + quoteAttributeValueForBrowser(id); }, setAttributeForID: function (node, id) { node.setAttribute(DOMProperty.ID_ATTRIBUTE_NAME, id); }, createMarkupForRoot: function () { return DOMProperty.ROOT_ATTRIBUTE_NAME + '=""'; }, setAttributeForRoot: function (node) { node.setAttribute(DOMProperty.ROOT_ATTRIBUTE_NAME, ''); }, /** * Creates markup for a property. * * @param {string} name * @param {*} value * @return {?string} Markup string, or null if the property was invalid. */ createMarkupForProperty: function (name, value) { var propertyInfo = DOMProperty.properties.hasOwnProperty(name) ? DOMProperty.properties[name] : null; if (propertyInfo) { if (shouldIgnoreValue(propertyInfo, value)) { return ''; } var attributeName = propertyInfo.attributeName; if (propertyInfo.hasBooleanValue || propertyInfo.hasOverloadedBooleanValue && value === true) { return attributeName + '=""'; } return attributeName + '=' + quoteAttributeValueForBrowser(value); } else if (DOMProperty.isCustomAttribute(name)) { if (value == null) { return ''; } return name + '=' + quoteAttributeValueForBrowser(value); } return null; }, /** * Creates markup for a custom property. * * @param {string} name * @param {*} value * @return {string} Markup string, or empty string if the property was invalid. */ createMarkupForCustomAttribute: function (name, value) { if (!isAttributeNameSafe(name) || value == null) { return ''; } return name + '=' + quoteAttributeValueForBrowser(value); }, /** * Sets the value for a property on a node. * * @param {DOMElement} node * @param {string} name * @param {*} value */ setValueForProperty: function (node, name, value) { var propertyInfo = DOMProperty.properties.hasOwnProperty(name) ? DOMProperty.properties[name] : null; if (propertyInfo) { var mutationMethod = propertyInfo.mutationMethod; if (mutationMethod) { mutationMethod(node, value); } else if (shouldIgnoreValue(propertyInfo, value)) { this.deleteValueForProperty(node, name); return; } else if (propertyInfo.mustUseProperty) { // Contrary to `setAttribute`, object properties are properly // `toString`ed by IE8/9. node[propertyInfo.propertyName] = value; } else { var attributeName = propertyInfo.attributeName; var namespace = propertyInfo.attributeNamespace; // `setAttribute` with objects becomes only `[object]` in IE8/9, // ('' + value) makes it output the correct toString()-value. if (namespace) { node.setAttributeNS(namespace, attributeName, '' + value); } else if (propertyInfo.hasBooleanValue || propertyInfo.hasOverloadedBooleanValue && value === true) { node.setAttribute(attributeName, ''); } else { node.setAttribute(attributeName, '' + value); } } } else if (DOMProperty.isCustomAttribute(name)) { DOMPropertyOperations.setValueForAttribute(node, name, value); return; } if ("development" !== 'production') { var payload = {}; payload[name] = value; ReactInstrumentation.debugTool.onHostOperation({ instanceID: ReactDOMComponentTree.getInstanceFromNode(node)._debugID, type: 'update attribute', payload: payload }); } }, setValueForAttribute: function (node, name, value) { if (!isAttributeNameSafe(name)) { return; } if (value == null) { node.removeAttribute(name); } else { node.setAttribute(name, '' + value); } if ("development" !== 'production') { var payload = {}; payload[name] = value; ReactInstrumentation.debugTool.onHostOperation({ instanceID: ReactDOMComponentTree.getInstanceFromNode(node)._debugID, type: 'update attribute', payload: payload }); } }, /** * Deletes an attributes from a node. * * @param {DOMElement} node * @param {string} name */ deleteValueForAttribute: function (node, name) { node.removeAttribute(name); if ("development" !== 'production') { ReactInstrumentation.debugTool.onHostOperation({ instanceID: ReactDOMComponentTree.getInstanceFromNode(node)._debugID, type: 'remove attribute', payload: name }); } }, /** * Deletes the value for a property on a node. * * @param {DOMElement} node * @param {string} name */ deleteValueForProperty: function (node, name) { var propertyInfo = DOMProperty.properties.hasOwnProperty(name) ? DOMProperty.properties[name] : null; if (propertyInfo) { var mutationMethod = propertyInfo.mutationMethod; if (mutationMethod) { mutationMethod(node, undefined); } else if (propertyInfo.mustUseProperty) { var propName = propertyInfo.propertyName; if (propertyInfo.hasBooleanValue) { node[propName] = false; } else { node[propName] = ''; } } else { node.removeAttribute(propertyInfo.attributeName); } } else if (DOMProperty.isCustomAttribute(name)) { node.removeAttribute(name); } if ("development" !== 'production') { ReactInstrumentation.debugTool.onHostOperation({ instanceID: ReactDOMComponentTree.getInstanceFromNode(node)._debugID, type: 'remove attribute', payload: name }); } } }; module.exports = DOMPropertyOperations; },{"12":12,"123":123,"156":156,"34":34,"62":62}],14:[function(_dereq_,module,exports){ /** * 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. * */ 'use strict'; var _prodInvariant = _dereq_(124); var DOMLazyTree = _dereq_(10); var ExecutionEnvironment = _dereq_(135); var createNodesFromMarkup = _dereq_(140); var emptyFunction = _dereq_(141); var invariant = _dereq_(149); var Danger = { /** * Replaces a node with a string of markup at its current position within its * parent. The markup must render into a single root node. * * @param {DOMElement} oldChild Child node to replace. * @param {string} markup Markup to render in place of the child node. * @internal */ dangerouslyReplaceNodeWithMarkup: function (oldChild, markup) { !ExecutionEnvironment.canUseDOM ? "development" !== 'production' ? invariant(false, 'dangerouslyReplaceNodeWithMarkup(...): Cannot render markup in a worker thread. Make sure `window` and `document` are available globally before requiring React when unit testing or use ReactDOMServer.renderToString() for server rendering.') : _prodInvariant('56') : void 0; !markup ? "development" !== 'production' ? invariant(false, 'dangerouslyReplaceNodeWithMarkup(...): Missing markup.') : _prodInvariant('57') : void 0; !(oldChild.nodeName !== 'HTML') ? "development" !== 'production' ? invariant(false, 'dangerouslyReplaceNodeWithMarkup(...): Cannot replace markup of the <html> node. This is because browser quirks make this unreliable and/or slow. If you want to render to the root you must use server rendering. See ReactDOMServer.renderToString().') : _prodInvariant('58') : void 0; if (typeof markup === 'string') { var newChild = createNodesFromMarkup(markup, emptyFunction)[0]; oldChild.parentNode.replaceChild(newChild, oldChild); } else { DOMLazyTree.replaceChildWithTree(oldChild, markup); } } }; module.exports = Danger; },{"10":10,"124":124,"135":135,"140":140,"141":141,"149":149}],15:[function(_dereq_,module,exports){ /** * 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. * */ 'use strict'; var EventPropagators = _dereq_(19); var ReactDOMComponentTree = _dereq_(34); var SyntheticMouseEvent = _dereq_(92); var eventTypes = { mouseEnter: { registrationName: 'onMouseEnter', dependencies: ['topMouseOut', 'topMouseOver'] }, mouseLeave: { registrationName: 'onMouseLeave', dependencies: ['topMouseOut', 'topMouseOver'] } }; var EnterLeaveEventPlugin = { eventTypes: eventTypes, /** * For almost every interaction we care about, there will be both a top-level * `mouseover` and `mouseout` event that occurs. Only use `mouseout` so that * we do not extract duplicate events. However, moving the mouse into the * browser from outside will not fire a `mouseout` event. In this case, we use * the `mouseover` top-level event. */ extractEvents: function (topLevelType, targetInst, nativeEvent, nativeEventTarget) { if (topLevelType === 'topMouseOver' && (nativeEvent.relatedTarget || nativeEvent.fromElement)) { return null; } if (topLevelType !== 'topMouseOut' && topLevelType !== 'topMouseOver') { // Must not be a mouse in or mouse out - ignoring. return null; } var win; if (nativeEventTarget.window === nativeEventTarget) { // `nativeEventTarget` is probably a window object. win = nativeEventTarget; } else { // TODO: Figure out why `ownerDocument` is sometimes undefined in IE8. var doc = nativeEventTarget.ownerDocument; if (doc) { win = doc.defaultView || doc.parentWindow; } else { win = window; } } var from; var to; if (topLevelType === 'topMouseOut') { from = targetInst; var related = nativeEvent.relatedTarget || nativeEvent.toElement; to = related ? ReactDOMComponentTree.getClosestInstanceFromNode(related) : null; } else { // Moving to a node from outside the window. from = null; to = targetInst; } if (from === to) { // Nothing pertains to our managed components. return null; } var fromNode = from == null ? win : ReactDOMComponentTree.getNodeFromInstance(from); var toNode = to == null ? win : ReactDOMComponentTree.getNodeFromInstance(to); var leave = SyntheticMouseEvent.getPooled(eventTypes.mouseLeave, from, nativeEvent, nativeEventTarget); leave.type = 'mouseleave'; leave.target = fromNode; leave.relatedTarget = toNode; var enter = SyntheticMouseEvent.getPooled(eventTypes.mouseEnter, to, nativeEvent, nativeEventTarget); enter.type = 'mouseenter'; enter.target = toNode; enter.relatedTarget = fromNode; EventPropagators.accumulateEnterLeaveDispatches(leave, enter, from, to); return [leave, enter]; } }; module.exports = EnterLeaveEventPlugin; },{"19":19,"34":34,"92":92}],16:[function(_dereq_,module,exports){ /** * 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. * */ 'use strict'; var _prodInvariant = _dereq_(124); var EventPluginRegistry = _dereq_(17); var EventPluginUtils = _dereq_(18); var ReactErrorUtils = _dereq_(53); var accumulateInto = _dereq_(99); var forEachAccumulated = _dereq_(107); var invariant = _dereq_(149); /** * Internal queue of events that have accumulated their dispatches and are * waiting to have their dispatches executed. */ var eventQueue = null; /** * Dispatches an event and releases it back into the pool, unless persistent. * * @param {?object} event Synthetic event to be dispatched. * @param {boolean} simulated If the event is simulated (changes exn behavior) * @private */ var executeDispatchesAndRelease = function (event, simulated) { if (event) { EventPluginUtils.executeDispatchesInOrder(event, simulated); if (!event.isPersistent()) { event.constructor.release(event); } } }; var executeDispatchesAndReleaseSimulated = function (e) { return executeDispatchesAndRelease(e, true); }; var executeDispatchesAndReleaseTopLevel = function (e) { return executeDispatchesAndRelease(e, false); }; function isInteractive(tag) { return tag === 'button' || tag === 'input' || tag === 'select' || tag === 'textarea'; } function shouldPreventMouseEvent(name, type, props) { switch (name) { case 'onClick': case 'onClickCapture': case 'onDoubleClick': case 'onDoubleClickCapture': case 'onMouseDown': case 'onMouseDownCapture': case 'onMouseMove': case 'onMouseMoveCapture': case 'onMouseUp': case 'onMouseUpCapture': return !!(props.disabled && isInteractive(type)); default: return false; } } /** * This is a unified interface for event plugins to be installed and configured. * * Event plugins can implement the following properties: * * `extractEvents` {function(string, DOMEventTarget, string, object): *} * Required. When a top-level event is fired, this method is expected to * extract synthetic events that will in turn be queued and dispatched. * * `eventTypes` {object} * Optional, plugins that fire events must publish a mapping of registration * names that are used to register listeners. Values of this mapping must * be objects that contain `registrationName` or `phasedRegistrationNames`. * * `executeDispatch` {function(object, function, string)} * Optional, allows plugins to override how an event gets dispatched. By * default, the listener is simply invoked. * * Each plugin that is injected into `EventsPluginHub` is immediately operable. * * @public */ var EventPluginHub = { /** * Methods for injecting dependencies. */ injection: { /** * @param {array} InjectedEventPluginOrder * @public */ injectEventPluginOrder: EventPluginRegistry.injectEventPluginOrder, /** * @param {object} injectedNamesToPlugins Map from names to plugin modules. */ injectEventPluginsByName: EventPluginRegistry.injectEventPluginsByName }, /** * @param {object} inst The instance, which is the source of events. * @param {string} registrationName Name of listener (e.g. `onClick`). * @return {?function} The stored callback. */ getListener: function (inst, registrationName) { var listener; // TODO: shouldPreventMouseEvent is DOM-specific and definitely should not // live here; needs to be moved to a better place soon if (typeof inst.tag === 'number') { var props = inst.memoizedProps; listener = props[registrationName]; if (shouldPreventMouseEvent(registrationName, inst.type, props)) { return null; } } else { var _props = inst._currentElement.props; listener = _props[registrationName]; if (shouldPreventMouseEvent(registrationName, inst._currentElement.type, _props)) { return null; } } !(!listener || typeof listener === 'function') ? "development" !== 'production' ? invariant(false, 'Expected %s listener to be a function, instead got type %s', registrationName, typeof listener) : _prodInvariant('94', registrationName, typeof listener) : void 0; return listener; }, /** * Allows registered plugins an opportunity to extract events from top-level * native browser events. * * @return {*} An accumulation of synthetic events. * @internal */ extractEvents: function (topLevelType, targetInst, nativeEvent, nativeEventTarget) { var events; var plugins = EventPluginRegistry.plugins; for (var i = 0; i < plugins.length; i++) { // Not every plugin in the ordering may be loaded at runtime. var possiblePlugin = plugins[i]; if (possiblePlugin) { var extractedEvents = possiblePlugin.extractEvents(topLevelType, targetInst, nativeEvent, nativeEventTarget); if (extractedEvents) { events = accumulateInto(events, extractedEvents); } } } return events; }, /** * Enqueues a synthetic event that should be dispatched when * `processEventQueue` is invoked. * * @param {*} events An accumulation of synthetic events. * @internal */ enqueueEvents: function (events) { if (events) { eventQueue = accumulateInto(eventQueue, events); } }, /** * Dispatches all synthetic events on the event queue. * * @internal */ processEventQueue: function (simulated) { // Set `eventQueue` to null before processing it so that we can tell if more // events get enqueued while processing. var processingEventQueue = eventQueue; eventQueue = null; if (simulated) { forEachAccumulated(processingEventQueue, executeDispatchesAndReleaseSimulated); } else { forEachAccumulated(processingEventQueue, executeDispatchesAndReleaseTopLevel); } !!eventQueue ? "development" !== 'production' ? invariant(false, 'processEventQueue(): Additional events were enqueued while processing an event queue. Support for this has not yet been implemented.') : _prodInvariant('95') : void 0; // This would be a good time to rethrow if any of the event handlers threw. ReactErrorUtils.rethrowCaughtError(); } }; module.exports = EventPluginHub; },{"107":107,"124":124,"149":149,"17":17,"18":18,"53":53,"99":99}],17:[function(_dereq_,module,exports){ /** * 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. * * */ 'use strict'; var _prodInvariant = _dereq_(124); var invariant = _dereq_(149); /** * Injectable ordering of event plugins. */ var eventPluginOrder = null; /** * Injectable mapping from names to event plugin modules. */ var namesToPlugins = {}; /** * Recomputes the plugin list using the injected plugins and plugin ordering. * * @private */ function recomputePluginOrdering() { if (!eventPluginOrder) { // Wait until an `eventPluginOrder` is injected. return; } for (var pluginName in namesToPlugins) { var pluginModule = namesToPlugins[pluginName]; var pluginIndex = eventPluginOrder.indexOf(pluginName); !(pluginIndex > -1) ? "development" !== 'production' ? invariant(false, 'EventPluginRegistry: Cannot inject event plugins that do not exist in the plugin ordering, `%s`.', pluginName) : _prodInvariant('96', pluginName) : void 0; if (EventPluginRegistry.plugins[pluginIndex]) { continue; } !pluginModule.extractEvents ? "development" !== 'production' ? invariant(false, 'EventPluginRegistry: Event plugins must implement an `extractEvents` method, but `%s` does not.', pluginName) : _prodInvariant('97', pluginName) : void 0; EventPluginRegistry.plugins[pluginIndex] = pluginModule; var publishedEvents = pluginModule.eventTypes; for (var eventName in publishedEvents) { !publishEventForPlugin(publishedEvents[eventName], pluginModule, eventName) ? "development" !== 'production' ? invariant(false, 'EventPluginRegistry: Failed to publish event `%s` for plugin `%s`.', eventName, pluginName) : _prodInvariant('98', eventName, pluginName) : void 0; } } } /** * Publishes an event so that it can be dispatched by the supplied plugin. * * @param {object} dispatchConfig Dispatch configuration for the event. * @param {object} PluginModule Plugin publishing the event. * @return {boolean} True if the event was successfully published. * @private */ function publishEventForPlugin(dispatchConfig, pluginModule, eventName) { !!EventPluginRegistry.eventNameDispatchConfigs.hasOwnProperty(eventName) ? "development" !== 'production' ? invariant(false, 'EventPluginHub: More than one plugin attempted to publish the same event name, `%s`.', eventName) : _prodInvariant('99', eventName) : void 0; EventPluginRegistry.eventNameDispatchConfigs[eventName] = dispatchConfig; var phasedRegistrationNames = dispatchConfig.phasedRegistrationNames; if (phasedRegistrationNames) { for (var phaseName in phasedRegistrationNames) { if (phasedRegistrationNames.hasOwnProperty(phaseName)) { var phasedRegistrationName = phasedRegistrationNames[phaseName]; publishRegistrationName(phasedRegistrationName, pluginModule, eventName); } } return true; } else if (dispatchConfig.registrationName) { publishRegistrationName(dispatchConfig.registrationName, pluginModule, eventName); return true; } return false; } /** * Publishes a registration name that is used to identify dispatched events. * * @param {string} registrationName Registration name to add. * @param {object} PluginModule Plugin publishing the event. * @private */ function publishRegistrationName(registrationName, pluginModule, eventName) { !!EventPluginRegistry.registrationNameModules[registrationName] ? "development" !== 'production' ? invariant(false, 'EventPluginHub: More than one plugin attempted to publish the same registration name, `%s`.', registrationName) : _prodInvariant('100', registrationName) : void 0; EventPluginRegistry.registrationNameModules[registrationName] = pluginModule; EventPluginRegistry.registrationNameDependencies[registrationName] = pluginModule.eventTypes[eventName].dependencies; if ("development" !== 'production') { var lowerCasedName = registrationName.toLowerCase(); EventPluginRegistry.possibleRegistrationNames[lowerCasedName] = registrationName; if (registrationName === 'onDoubleClick') { EventPluginRegistry.possibleRegistrationNames.ondblclick = registrationName; } } } /** * Registers plugins so that they can extract and dispatch events. * * @see {EventPluginHub} */ var EventPluginRegistry = { /** * Ordered list of injected plugins. */ plugins: [], /** * Mapping from event name to dispatch config */ eventNameDispatchConfigs: {}, /** * Mapping from registration name to plugin module */ registrationNameModules: {}, /** * Mapping from registration name to event name */ registrationNameDependencies: {}, /** * Mapping from lowercase registration names to the properly cased version, * used to warn in the case of missing event handlers. Available * only in __DEV__. * @type {Object} */ possibleRegistrationNames: "development" !== 'production' ? {} : null, // Trust the developer to only use possibleRegistrationNames in __DEV__ /** * Injects an ordering of plugins (by plugin name). This allows the ordering * to be decoupled from injection of the actual plugins so that ordering is * always deterministic regardless of packaging, on-the-fly injection, etc. * * @param {array} InjectedEventPluginOrder * @internal * @see {EventPluginHub.injection.injectEventPluginOrder} */ injectEventPluginOrder: function (injectedEventPluginOrder) { !!eventPluginOrder ? "development" !== 'production' ? invariant(false, 'EventPluginRegistry: Cannot inject event plugin ordering more than once. You are likely trying to load more than one copy of React.') : _prodInvariant('101') : void 0; // Clone the ordering so it cannot be dynamically mutated. eventPluginOrder = Array.prototype.slice.call(injectedEventPluginOrder); recomputePluginOrdering(); }, /** * Injects plugins to be used by `EventPluginHub`. The plugin names must be * in the ordering injected by `injectEventPluginOrder`. * * Plugins can be injected as part of page initialization or on-the-fly. * * @param {object} injectedNamesToPlugins Map from names to plugin modules. * @internal * @see {EventPluginHub.injection.injectEventPluginsByName} */ injectEventPluginsByName: function (injectedNamesToPlugins) { var isOrderingDirty = false; for (var pluginName in injectedNamesToPlugins) { if (!injectedNamesToPlugins.hasOwnProperty(pluginName)) { continue; } var pluginModule = injectedNamesToPlugins[pluginName]; if (!namesToPlugins.hasOwnProperty(pluginName) || namesToPlugins[pluginName] !== pluginModule) { !!namesToPlugins[pluginName] ? "development" !== 'production' ? invariant(false, 'EventPluginRegistry: Cannot inject two different event plugins using the same name, `%s`.', pluginName) : _prodInvariant('102', pluginName) : void 0; namesToPlugins[pluginName] = pluginModule; isOrderingDirty = true; } } if (isOrderingDirty) { recomputePluginOrdering(); } }, /** * Looks up the plugin for the supplied event. * * @param {object} event A synthetic event. * @return {?object} The plugin that created the supplied event. * @internal */ getPluginModuleForEvent: function (event) { var dispatchConfig = event.dispatchConfig; if (dispatchConfig.registrationName) { return EventPluginRegistry.registrationNameModules[dispatchConfig.registrationName] || null; } if (dispatchConfig.phasedRegistrationNames !== undefined) { // pulling phasedRegistrationNames out of dispatchConfig helps Flow see // that it is not undefined. var phasedRegistrationNames = dispatchConfig.phasedRegistrationNames; for (var phase in phasedRegistrationNames) { if (!phasedRegistrationNames.hasOwnProperty(phase)) { continue; } var pluginModule = EventPluginRegistry.registrationNameModules[phasedRegistrationNames[phase]]; if (pluginModule) { return pluginModule; } } } return null; }, /** * Exposed for unit testing. * @private */ _resetEventPlugins: function () { eventPluginOrder = null; for (var pluginName in namesToPlugins) { if (namesToPlugins.hasOwnProperty(pluginName)) { delete namesToPlugins[pluginName]; } } EventPluginRegistry.plugins.length = 0; var eventNameDispatchConfigs = EventPluginRegistry.eventNameDispatchConfigs; for (var eventName in eventNameDispatchConfigs) { if (eventNameDispatchConfigs.hasOwnProperty(eventName)) { delete eventNameDispatchConfigs[eventName]; } } var registrationNameModules = EventPluginRegistry.registrationNameModules; for (var registrationName in registrationNameModules) { if (registrationNameModules.hasOwnProperty(registrationName)) { delete registrationNameModules[registrationName]; } } if ("development" !== 'production') { var possibleRegistrationNames = EventPluginRegistry.possibleRegistrationNames; for (var lowerCasedName in possibleRegistrationNames) { if (possibleRegistrationNames.hasOwnProperty(lowerCasedName)) { delete possibleRegistrationNames[lowerCasedName]; } } } } }; module.exports = EventPluginRegistry; },{"124":124,"149":149}],18:[function(_dereq_,module,exports){ /** * 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. * */ 'use strict'; var _prodInvariant = _dereq_(124); var ReactErrorUtils = _dereq_(53); var invariant = _dereq_(149); var warning = _dereq_(156); /** * Injected dependencies: */ /** * - `ComponentTree`: [required] Module that can convert between React instances * and actual node references. */ var ComponentTree; var injection = { injectComponentTree: function (Injected) { ComponentTree = Injected; if ("development" !== 'production') { "development" !== 'production' ? warning(Injected && Injected.getNodeFromInstance && Injected.getInstanceFromNode, 'EventPluginUtils.injection.injectComponentTree(...): Injected ' + 'module is missing getNodeFromInstance or getInstanceFromNode.') : void 0; } } }; function isEndish(topLevelType) { return topLevelType === 'topMouseUp' || topLevelType === 'topTouchEnd' || topLevelType === 'topTouchCancel'; } function isMoveish(topLevelType) { return topLevelType === 'topMouseMove' || topLevelType === 'topTouchMove'; } function isStartish(topLevelType) { return topLevelType === 'topMouseDown' || topLevelType === 'topTouchStart'; } var validateEventDispatches; if ("development" !== 'production') { validateEventDispatches = function (event) { var dispatchListeners = event._dispatchListeners; var dispatchInstances = event._dispatchInstances; var listenersIsArr = Array.isArray(dispatchListeners); var listenersLen = listenersIsArr ? dispatchListeners.length : dispatchListeners ? 1 : 0; var instancesIsArr = Array.isArray(dispatchInstances); var instancesLen = instancesIsArr ? dispatchInstances.length : dispatchInstances ? 1 : 0; "development" !== 'production' ? warning(instancesIsArr === listenersIsArr && instancesLen === listenersLen, 'EventPluginUtils: Invalid `event`.') : void 0; }; } /** * Dispatch the event to the listener. * @param {SyntheticEvent} event SyntheticEvent to handle * @param {boolean} simulated If the event is simulated (changes exn behavior) * @param {function} listener Application-level callback * @param {*} inst Internal component instance */ function executeDispatch(event, simulated, listener, inst) { var type = event.type || 'unknown-event'; event.currentTarget = EventPluginUtils.getNodeFromInstance(inst); if (simulated) { ReactErrorUtils.invokeGuardedCallbackWithCatch(type, listener, event); } else { ReactErrorUtils.invokeGuardedCallback(type, listener, event); } event.currentTarget = null; } /** * Standard/simple iteration through an event's collected dispatches. */ function executeDispatchesInOrder(event, simulated) { var dispatchListeners = event._dispatchListeners; var dispatchInstances = event._dispatchInstances; if ("development" !== 'production') { validateEventDispatches(event); } if (Array.isArray(dispatchListeners)) { for (var i = 0; i < dispatchListeners.length; i++) { if (event.isPropagationStopped()) { break; } // Listeners and Instances are two parallel arrays that are always in sync. executeDispatch(event, simulated, dispatchListeners[i], dispatchInstances[i]); } } else if (dispatchListeners) { executeDispatch(event, simulated, dispatchListeners, dispatchInstances); } event._dispatchListeners = null; event._dispatchInstances = null; } /** * Standard/simple iteration through an event's collected dispatches, but stops * at the first dispatch execution returning true, and returns that id. * * @return {?string} id of the first dispatch execution who's listener returns * true, or null if no listener returned true. */ function executeDispatchesInOrderStopAtTrueImpl(event) { var dispatchListeners = event._dispatchListeners; var dispatchInstances = event._dispatchInstances; if ("development" !== 'production') { validateEventDispatches(event); } if (Array.isArray(dispatchListeners)) { for (var i = 0; i < dispatchListeners.length; i++) { if (event.isPropagationStopped()) { break; } // Listeners and Instances are two parallel arrays that are always in sync. if (dispatchListeners[i](event, dispatchInstances[i])) { return dispatchInstances[i]; } } } else if (dispatchListeners) { if (dispatchListeners(event, dispatchInstances)) { return dispatchInstances; } } return null; } /** * @see executeDispatchesInOrderStopAtTrueImpl */ function executeDispatchesInOrderStopAtTrue(event) { var ret = executeDispatchesInOrderStopAtTrueImpl(event); event._dispatchInstances = null; event._dispatchListeners = null; return ret; } /** * Execution of a "direct" dispatch - there must be at most one dispatch * accumulated on the event or it is considered an error. It doesn't really make * sense for an event with multiple dispatches (bubbled) to keep track of the * return values at each dispatch execution, but it does tend to make sense when * dealing with "direct" dispatches. * * @return {*} The return value of executing the single dispatch. */ function executeDirectDispatch(event) { if ("development" !== 'production') { validateEventDispatches(event); } var dispatchListener = event._dispatchListeners; var dispatchInstance = event._dispatchInstances; !!Array.isArray(dispatchListener) ? "development" !== 'production' ? invariant(false, 'executeDirectDispatch(...): Invalid `event`.') : _prodInvariant('103') : void 0; event.currentTarget = dispatchListener ? EventPluginUtils.getNodeFromInstance(dispatchInstance) : null; var res = dispatchListener ? dispatchListener(event) : null; event.currentTarget = null; event._dispatchListeners = null; event._dispatchInstances = null; return res; } /** * @param {SyntheticEvent} event * @return {boolean} True iff number of dispatches accumulated is greater than 0. */ function hasDispatches(event) { return !!event._dispatchListeners; } /** * General utilities that are useful in creating custom Event Plugins. */ var EventPluginUtils = { isEndish: isEndish, isMoveish: isMoveish, isStartish: isStartish, executeDirectDispatch: executeDirectDispatch, executeDispatchesInOrder: executeDispatchesInOrder, executeDispatchesInOrderStopAtTrue: executeDispatchesInOrderStopAtTrue, hasDispatches: hasDispatches, getInstanceFromNode: function (node) { return ComponentTree.getInstanceFromNode(node); }, getNodeFromInstance: function (node) { return ComponentTree.getNodeFromInstance(node); }, injection: injection }; module.exports = EventPluginUtils; },{"124":124,"149":149,"156":156,"53":53}],19:[function(_dereq_,module,exports){ /** * 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. * */ 'use strict'; var EventPluginHub = _dereq_(16); var ReactTreeTraversal = _dereq_(76); var accumulateInto = _dereq_(99); var forEachAccumulated = _dereq_(107); var warning = _dereq_(156); var getListener = EventPluginHub.getListener; /** * Some event types have a notion of different registration names for different * "phases" of propagation. This finds listeners by a given phase. */ function listenerAtPhase(inst, event, propagationPhase) { var registrationName = event.dispatchConfig.phasedRegistrationNames[propagationPhase]; return getListener(inst, registrationName); } /** * Tags a `SyntheticEvent` with dispatched listeners. Creating this function * here, allows us to not have to bind or create functions for each event. * Mutating the event's members allows us to not have to create a wrapping * "dispatch" object that pairs the event with the listener. */ function accumulateDirectionalDispatches(inst, phase, event) { if ("development" !== 'production') { "development" !== 'production' ? warning(inst, 'Dispatching inst must not be null') : void 0; } var listener = listenerAtPhase(inst, event, phase); if (listener) { event._dispatchListeners = accumulateInto(event._dispatchListeners, listener); event._dispatchInstances = accumulateInto(event._dispatchInstances, inst); } } /** * Collect dispatches (must be entirely collected before dispatching - see unit * tests). Lazily allocate the array to conserve memory. We must loop through * each event and perform the traversal for each one. We cannot perform a * single traversal for the entire collection of events because each event may * have a different target. */ function accumulateTwoPhaseDispatchesSingle(event) { if (event && event.dispatchConfig.phasedRegistrationNames) { ReactTreeTraversal.traverseTwoPhase(event._targetInst, accumulateDirectionalDispatches, event); } } /** * Same as `accumulateTwoPhaseDispatchesSingle`, but skips over the targetID. */ function accumulateTwoPhaseDispatchesSingleSkipTarget(event) { if (event && event.dispatchConfig.phasedRegistrationNames) { var targetInst = event._targetInst; var parentInst = targetInst ? ReactTreeTraversal.getParentInstance(targetInst) : null; ReactTreeTraversal.traverseTwoPhase(parentInst, accumulateDirectionalDispatches, event); } } /** * Accumulates without regard to direction, does not look for phased * registration names. Same as `accumulateDirectDispatchesSingle` but without * requiring that the `dispatchMarker` be the same as the dispatched ID. */ function accumulateDispatches(inst, ignoredDirection, event) { if (event && event.dispatchConfig.registrationName) { var registrationName = event.dispatchConfig.registrationName; var listener = getListener(inst, registrationName); if (listener) { event._dispatchListeners = accumulateInto(event._dispatchListeners, listener); event._dispatchInstances = accumulateInto(event._dispatchInstances, inst); } } } /** * Accumulates dispatches on an `SyntheticEvent`, but only for the * `dispatchMarker`. * @param {SyntheticEvent} event */ function accumulateDirectDispatchesSingle(event) { if (event && event.dispatchConfig.registrationName) { accumulateDispatches(event._targetInst, null, event); } } function accumulateTwoPhaseDispatches(events) { forEachAccumulated(events, accumulateTwoPhaseDispatchesSingle); } function accumulateTwoPhaseDispatchesSkipTarget(events) { forEachAccumulated(events, accumulateTwoPhaseDispatchesSingleSkipTarget); } function accumulateEnterLeaveDispatches(leave, enter, from, to) { ReactTreeTraversal.traverseEnterLeave(from, to, accumulateDispatches, leave, enter); } function accumulateDirectDispatches(events) { forEachAccumulated(events, accumulateDirectDispatchesSingle); } /** * A small set of propagation patterns, each of which will accept a small amount * of information, and generate a set of "dispatch ready event objects" - which * are sets of events that have already been annotated with a set of dispatched * listener functions/ids. The API is designed this way to discourage these * propagation strategies from actually executing the dispatches, since we * always want to collect the entire set of dispatches before executing event a * single one. * * @constructor EventPropagators */ var EventPropagators = { accumulateTwoPhaseDispatches: accumulateTwoPhaseDispatches, accumulateTwoPhaseDispatchesSkipTarget: accumulateTwoPhaseDispatchesSkipTarget, accumulateDirectDispatches: accumulateDirectDispatches, accumulateEnterLeaveDispatches: accumulateEnterLeaveDispatches }; module.exports = EventPropagators; },{"107":107,"156":156,"16":16,"76":76,"99":99}],20:[function(_dereq_,module,exports){ /** * 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. * */ 'use strict'; var _assign = _dereq_(157); var PooledClass = _dereq_(23); var getTextContentAccessor = _dereq_(117); /** * This helper class stores information about text content of a target node, * allowing comparison of content before and after a given event. * * Identify the node where selection currently begins, then observe * both its text content and its current position in the DOM. Since the * browser may natively replace the target node during composition, we can * use its position to find its replacement. * * @param {DOMEventTarget} root */ function FallbackCompositionState(root) { this._root = root; this._startText = this.getText(); this._fallbackText = null; } _assign(FallbackCompositionState.prototype, { destructor: function () { this._root = null; this._startText = null; this._fallbackText = null; }, /** * Get current text of input. * * @return {string} */ getText: function () { if ('value' in this._root) { return this._root.value; } return this._root[getTextContentAccessor()]; }, /** * Determine the differing substring between the initially stored * text content and the current content. * * @return {string} */ getData: function () { if (this._fallbackText) { return this._fallbackText; } var start; var startValue = this._startText; var startLength = startValue.length; var end; var endValue = this.getText(); var endLength = endValue.length; for (start = 0; start < startLength; start++) { if (startValue[start] !== endValue[start]) { break; } } var minEnd = startLength - start; for (end = 1; end <= minEnd; end++) { if (startValue[startLength - end] !== endValue[endLength - end]) { break; } } var sliceTail = end > 1 ? 1 - end : undefined; this._fallbackText = endValue.slice(start, sliceTail); return this._fallbackText; } }); PooledClass.addPoolingTo(FallbackCompositionState); module.exports = FallbackCompositionState; },{"117":117,"157":157,"23":23}],21:[function(_dereq_,module,exports){ /** * 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. * */ 'use strict'; var DOMProperty = _dereq_(12); var MUST_USE_PROPERTY = DOMProperty.injection.MUST_USE_PROPERTY; var HAS_BOOLEAN_VALUE = DOMProperty.injection.HAS_BOOLEAN_VALUE; var HAS_NUMERIC_VALUE = DOMProperty.injection.HAS_NUMERIC_VALUE; var HAS_POSITIVE_NUMERIC_VALUE = DOMProperty.injection.HAS_POSITIVE_NUMERIC_VALUE; var HAS_OVERLOADED_BOOLEAN_VALUE = DOMProperty.injection.HAS_OVERLOADED_BOOLEAN_VALUE; var HTMLDOMPropertyConfig = { isCustomAttribute: RegExp.prototype.test.bind(new RegExp('^(data|aria)-[' + DOMProperty.ATTRIBUTE_NAME_CHAR + ']*$')), Properties: { /** * Standard Properties */ accept: 0, acceptCharset: 0, accessKey: 0, action: 0, allowFullScreen: HAS_BOOLEAN_VALUE, allowTransparency: 0, alt: 0, // specifies target context for links with `preload` type as: 0, async: HAS_BOOLEAN_VALUE, autoComplete: 0, // autoFocus is polyfilled/normalized by AutoFocusUtils // autoFocus: HAS_BOOLEAN_VALUE, autoPlay: HAS_BOOLEAN_VALUE, capture: HAS_BOOLEAN_VALUE, cellPadding: 0, cellSpacing: 0, charSet: 0, challenge: 0, checked: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE, cite: 0, classID: 0, className: 0, cols: HAS_POSITIVE_NUMERIC_VALUE, colSpan: 0, content: 0, contentEditable: 0, contextMenu: 0, controls: HAS_BOOLEAN_VALUE, coords: 0, crossOrigin: 0, data: 0, // For `<object />` acts as `src`. dateTime: 0, 'default': HAS_BOOLEAN_VALUE, defer: HAS_BOOLEAN_VALUE, dir: 0, disabled: HAS_BOOLEAN_VALUE, download: HAS_OVERLOADED_BOOLEAN_VALUE, draggable: 0, encType: 0, form: 0, formAction: 0, formEncType: 0, formMethod: 0, formNoValidate: HAS_BOOLEAN_VALUE, formTarget: 0, frameBorder: 0, headers: 0, height: 0, hidden: HAS_BOOLEAN_VALUE, high: 0, href: 0, hrefLang: 0, htmlFor: 0, httpEquiv: 0, id: 0, inputMode: 0, integrity: 0, is: 0, keyParams: 0, keyType: 0, kind: 0, label: 0, lang: 0, list: 0, loop: HAS_BOOLEAN_VALUE, low: 0, manifest: 0, marginHeight: 0, marginWidth: 0, max: 0, maxLength: 0, media: 0, mediaGroup: 0, method: 0, min: 0, minLength: 0, // Caution; `option.selected` is not updated if `select.multiple` is // disabled with `removeAttribute`. multiple: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE, muted: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE, name: 0, nonce: 0, noValidate: HAS_BOOLEAN_VALUE, open: HAS_BOOLEAN_VALUE, optimum: 0, pattern: 0, placeholder: 0, playsInline: HAS_BOOLEAN_VALUE, poster: 0, preload: 0, profile: 0, radioGroup: 0, readOnly: HAS_BOOLEAN_VALUE, referrerPolicy: 0, rel: 0, required: HAS_BOOLEAN_VALUE, reversed: HAS_BOOLEAN_VALUE, role: 0, rows: HAS_POSITIVE_NUMERIC_VALUE, rowSpan: HAS_NUMERIC_VALUE, sandbox: 0, scope: 0, scoped: HAS_BOOLEAN_VALUE, scrolling: 0, seamless: HAS_BOOLEAN_VALUE, selected: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE, shape: 0, size: HAS_POSITIVE_NUMERIC_VALUE, sizes: 0, // support for projecting regular DOM Elements via V1 named slots ( shadow dom ) slot: 0, span: HAS_POSITIVE_NUMERIC_VALUE, spellCheck: 0, src: 0, srcDoc: 0, srcLang: 0, srcSet: 0, start: HAS_NUMERIC_VALUE, step: 0, style: 0, summary: 0, tabIndex: 0, target: 0, title: 0, // Setting .type throws on non-<input> tags type: 0, useMap: 0, value: 0, width: 0, wmode: 0, wrap: 0, /** * RDFa Properties */ about: 0, datatype: 0, inlist: 0, prefix: 0, // property is also supported for OpenGraph in meta tags. property: 0, resource: 0, 'typeof': 0, vocab: 0, /** * Non-standard Properties */ // autoCapitalize and autoCorrect are supported in Mobile Safari for // keyboard hints. autoCapitalize: 0, autoCorrect: 0, // autoSave allows WebKit/Blink to persist values of input fields on page reloads autoSave: 0, // color is for Safari mask-icon link color: 0, // itemProp, itemScope, itemType are for // Microdata support. See http://schema.org/docs/gs.html itemProp: 0, itemScope: HAS_BOOLEAN_VALUE, itemType: 0, // 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: 0, itemRef: 0, // results show looking glass icon and recent searches on input // search fields in WebKit/Blink results: 0, // IE-only attribute that specifies security restrictions on an iframe // as an alternative to the sandbox attribute on IE<10 security: 0, // IE-only attribute that controls focus behavior unselectable: 0 }, DOMAttributeNames: { acceptCharset: 'accept-charset', className: 'class', htmlFor: 'for', httpEquiv: 'http-equiv' }, DOMPropertyNames: {} }; module.exports = HTMLDOMPropertyConfig; },{"12":12}],22:[function(_dereq_,module,exports){ /** * 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. * * */ 'use strict'; /** * Escape and wrap key so it is safe to use as a reactid * * @param {string} key to be escaped. * @return {string} the escaped key. */ function escape(key) { var escapeRegex = /[=:]/g; var escaperLookup = { '=': '=0', ':': '=2' }; var escapedString = ('' + key).replace(escapeRegex, function (match) { return escaperLookup[match]; }); return '$' + escapedString; } /** * Unescape and unwrap key for human-readable display * * @param {string} key to unescape. * @return {string} the unescaped key. */ function unescape(key) { var unescapeRegex = /(=0|=2)/g; var unescaperLookup = { '=0': '=', '=2': ':' }; var keySubstring = key[0] === '.' && key[1] === '$' ? key.substring(2) : key.substring(1); return ('' + keySubstring).replace(unescapeRegex, function (match) { return unescaperLookup[match]; }); } var KeyEscapeUtils = { escape: escape, unescape: unescape }; module.exports = KeyEscapeUtils; },{}],23:[function(_dereq_,module,exports){ /** * 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. * * */ 'use strict'; var _prodInvariant = _dereq_(124); var invariant = _dereq_(149); /** * Static poolers. Several custom versions for each potential number of * arguments. A completely generic pooler is easy to implement, but would * require accessing the `arguments` object. In each of these, `this` refers to * the Class itself, not an instance. If any others are needed, simply add them * here, or in their own files. */ var oneArgumentPooler = function (copyFieldsFrom) { var Klass = this; if (Klass.instancePool.length) { var instance = Klass.instancePool.pop(); Klass.call(instance, copyFieldsFrom); return instance; } else { return new Klass(copyFieldsFrom); } }; var twoArgumentPooler = function (a1, a2) { var Klass = this; if (Klass.instancePool.length) { var instance = Klass.instancePool.pop(); Klass.call(instance, a1, a2); return instance; } else { return new Klass(a1, a2); } }; var threeArgumentPooler = function (a1, a2, a3) { var Klass = this; if (Klass.instancePool.length) { var instance = Klass.instancePool.pop(); Klass.call(instance, a1, a2, a3); return instance; } else { return new Klass(a1, a2, a3); } }; var fourArgumentPooler = function (a1, a2, a3, a4) { var Klass = this; if (Klass.instancePool.length) { var instance = Klass.instancePool.pop(); Klass.call(instance, a1, a2, a3, a4); return instance; } else { return new Klass(a1, a2, a3, a4); } }; var standardReleaser = function (instance) { var Klass = this; !(instance instanceof Klass) ? "development" !== 'production' ? invariant(false, 'Trying to release an instance into a pool of a different type.') : _prodInvariant('25') : void 0; instance.destructor(); if (Klass.instancePool.length < Klass.poolSize) { Klass.instancePool.push(instance); } }; var DEFAULT_POOL_SIZE = 10; var DEFAULT_POOLER = oneArgumentPooler; /** * Augments `CopyConstructor` to be a poolable class, augmenting only the class * itself (statically) not adding any prototypical fields. Any CopyConstructor * you give this may have a `poolSize` property, and will look for a * prototypical `destructor` on instances. * * @param {Function} CopyConstructor Constructor that can be used to reset. * @param {Function} pooler Customizable pooler. */ var addPoolingTo = function (CopyConstructor, pooler) { // Casting as any so that flow ignores the actual implementation and trusts // it to match the type we declared var NewKlass = CopyConstructor; NewKlass.instancePool = []; NewKlass.getPooled = pooler || DEFAULT_POOLER; if (!NewKlass.poolSize) { NewKlass.poolSize = DEFAULT_POOL_SIZE; } NewKlass.release = standardReleaser; return NewKlass; }; var PooledClass = { addPoolingTo: addPoolingTo, oneArgumentPooler: oneArgumentPooler, twoArgumentPooler: twoArgumentPooler, threeArgumentPooler: threeArgumentPooler, fourArgumentPooler: fourArgumentPooler }; module.exports = PooledClass; },{"124":124,"149":149}],24:[function(_dereq_,module,exports){ /** * 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. * */ 'use strict'; var _assign = _dereq_(157); var EventPluginRegistry = _dereq_(17); var ReactEventEmitterMixin = _dereq_(54); var ViewportMetrics = _dereq_(98); var getVendorPrefixedEventName = _dereq_(118); var isEventSupported = _dereq_(121); /** * Summary of `ReactBrowserEventEmitter` event handling: * * - Top-level delegation is used to trap most native browser events. This * may only occur in the main thread and is the responsibility of * ReactEventListener, which is injected and can therefore support pluggable * event sources. This is the only work that occurs in the main thread. * * - We normalize and de-duplicate events to account for browser quirks. This * may be done in the worker thread. * * - Forward these native events (with the associated top-level type used to * trap it) to `EventPluginHub`, which in turn will ask plugins if they want * to extract any synthetic events. * * - The `EventPluginHub` will then process each event by annotating them with * "dispatches", a sequence of listeners and IDs that care about that event. * * - The `EventPluginHub` then dispatches the events. * * Overview of React and the event system: * * +------------+ . * | DOM | . * +------------+ . * | . * v . * +------------+ . * | ReactEvent | . * | Listener | . * +------------+ . +-----------+ * | . +--------+|SimpleEvent| * | . | |Plugin | * +-----|------+ . v +-----------+ * | | | . +--------------+ +------------+ * | +-----------.--->|EventPluginHub| | Event | * | | . | | +-----------+ | Propagators| * | ReactEvent | . | | |TapEvent | |------------| * | Emitter | . | |<---+|Plugin | |other plugin| * | | . | | +-----------+ | utilities | * | +-----------.--->| | +------------+ * | | | . +--------------+ * +-----|------+ . ^ +-----------+ * | . | |Enter/Leave| * + . +-------+|Plugin | * +-------------+ . +-----------+ * | application | . * |-------------| . * | | . * | | . * +-------------+ . * . * React Core . General Purpose Event Plugin System */ var hasEventPageXY; var alreadyListeningTo = {}; var isMonitoringScrollValue = false; var reactTopListenersCounter = 0; // For events like 'submit' which don't consistently bubble (which we trap at a // lower node than `document`), binding at `document` would cause duplicate // events so we don't include them here var topEventMapping = { topAbort: 'abort', topAnimationEnd: getVendorPrefixedEventName('animationend') || 'animationend', topAnimationIteration: getVendorPrefixedEventName('animationiteration') || 'animationiteration', topAnimationStart: getVendorPrefixedEventName('animationstart') || 'animationstart', topBlur: 'blur', topCanPlay: 'canplay', topCanPlayThrough: 'canplaythrough', topChange: 'change', topClick: 'click', topCompositionEnd: 'compositionend', topCompositionStart: 'compositionstart', topCompositionUpdate: 'compositionupdate', topContextMenu: 'contextmenu', topCopy: 'copy', topCut: 'cut', topDoubleClick: 'dblclick', topDrag: 'drag', topDragEnd: 'dragend', topDragEnter: 'dragenter', topDragExit: 'dragexit', topDragLeave: 'dragleave', topDragOver: 'dragover', topDragStart: 'dragstart', topDrop: 'drop', topDurationChange: 'durationchange', topEmptied: 'emptied', topEncrypted: 'encrypted', topEnded: 'ended', topError: 'error', topFocus: 'focus', topInput: 'input', topKeyDown: 'keydown', topKeyPress: 'keypress', topKeyUp: 'keyup', topLoadedData: 'loadeddata', topLoadedMetadata: 'loadedmetadata', topLoadStart: 'loadstart', topMouseDown: 'mousedown', topMouseMove: 'mousemove', topMouseOut: 'mouseout', topMouseOver: 'mouseover', topMouseUp: 'mouseup', topPaste: 'paste', topPause: 'pause', topPlay: 'play', topPlaying: 'playing', topProgress: 'progress', topRateChange: 'ratechange', topScroll: 'scroll', topSeeked: 'seeked', topSeeking: 'seeking', topSelectionChange: 'selectionchange', topStalled: 'stalled', topSuspend: 'suspend', topTextInput: 'textInput', topTimeUpdate: 'timeupdate', topTouchCancel: 'touchcancel', topTouchEnd: 'touchend', topTouchMove: 'touchmove', topTouchStart: 'touchstart', topTransitionEnd: getVendorPrefixedEventName('transitionend') || 'transitionend', topVolumeChange: 'volumechange', topWaiting: 'waiting', topWheel: 'wheel' }; /** * To ensure no conflicts with other potential React instances on the page */ var topListenersIDKey = '_reactListenersID' + String(Math.random()).slice(2); function getListeningForDocument(mountAt) { // In IE8, `mountAt` is a host object and doesn't have `hasOwnProperty` // directly. if (!Object.prototype.hasOwnProperty.call(mountAt, topListenersIDKey)) { mountAt[topListenersIDKey] = reactTopListenersCounter++; alreadyListeningTo[mountAt[topListenersIDKey]] = {}; } return alreadyListeningTo[mountAt[topListenersIDKey]]; } var ReactBrowserEventEmitter = _assign({}, ReactEventEmitterMixin, { /** * Injectable event backend */ ReactEventListener: null, injection: { /** * @param {object} ReactEventListener */ injectReactEventListener: function (ReactEventListener) { ReactEventListener.setHandleTopLevel(ReactBrowserEventEmitter.handleTopLevel); ReactBrowserEventEmitter.ReactEventListener = ReactEventListener; } }, /** * Sets whether or not any created callbacks should be enabled. * * @param {boolean} enabled True if callbacks should be enabled. */ setEnabled: function (enabled) { if (ReactBrowserEventEmitter.ReactEventListener) { ReactBrowserEventEmitter.ReactEventListener.setEnabled(enabled); } }, /** * @return {boolean} True if callbacks are enabled. */ isEnabled: function () { return !!(ReactBrowserEventEmitter.ReactEventListener && ReactBrowserEventEmitter.ReactEventListener.isEnabled()); }, /** * We listen for bubbled touch events on the document object. * * Firefox v8.01 (and possibly others) exhibited strange behavior when * mounting `onmousemove` events at some node that was not the document * element. The symptoms were that if your mouse is not moving over something * contained within that mount point (for example on the background) the * top-level listeners for `onmousemove` won't be called. However, if you * register the `mousemove` on the document object, then it will of course * catch all `mousemove`s. This along with iOS quirks, justifies restricting * top-level listeners to the document object only, at least for these * movement types of events and possibly all events. * * @see http://www.quirksmode.org/blog/archives/2010/09/click_event_del.html * * Also, `keyup`/`keypress`/`keydown` do not bubble to the window on IE, but * they bubble to document. * * @param {string} registrationName Name of listener (e.g. `onClick`). * @param {object} contentDocumentHandle Document which owns the container */ listenTo: function (registrationName, contentDocumentHandle) { var mountAt = contentDocumentHandle; var isListening = getListeningForDocument(mountAt); var dependencies = EventPluginRegistry.registrationNameDependencies[registrationName]; for (var i = 0; i < dependencies.length; i++) { var dependency = dependencies[i]; if (!(isListening.hasOwnProperty(dependency) && isListening[dependency])) { if (dependency === 'topWheel') { if (isEventSupported('wheel')) { ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent('topWheel', 'wheel', mountAt); } else if (isEventSupported('mousewheel')) { ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent('topWheel', 'mousewheel', mountAt); } else { // Firefox needs to capture a different mouse scroll event. // @see http://www.quirksmode.org/dom/events/tests/scroll.html ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent('topWheel', 'DOMMouseScroll', mountAt); } } else if (dependency === 'topScroll') { if (isEventSupported('scroll', true)) { ReactBrowserEventEmitter.ReactEventListener.trapCapturedEvent('topScroll', 'scroll', mountAt); } else { ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent('topScroll', 'scroll', ReactBrowserEventEmitter.ReactEventListener.WINDOW_HANDLE); } } else if (dependency === 'topFocus' || dependency === 'topBlur') { if (isEventSupported('focus', true)) { ReactBrowserEventEmitter.ReactEventListener.trapCapturedEvent('topFocus', 'focus', mountAt); ReactBrowserEventEmitter.ReactEventListener.trapCapturedEvent('topBlur', 'blur', mountAt); } else if (isEventSupported('focusin')) { // IE has `focusin` and `focusout` events which bubble. // @see http://www.quirksmode.org/blog/archives/2008/04/delegating_the.html ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent('topFocus', 'focusin', mountAt); ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent('topBlur', 'focusout', mountAt); } // to make sure blur and focus event listeners are only attached once isListening.topBlur = true; isListening.topFocus = true; } else if (topEventMapping.hasOwnProperty(dependency)) { ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(dependency, topEventMapping[dependency], mountAt); } isListening[dependency] = true; } } }, isListeningToAllDependencies: function (registrationName, mountAt) { var isListening = getListeningForDocument(mountAt); var dependencies = EventPluginRegistry.registrationNameDependencies[registrationName]; for (var i = 0; i < dependencies.length; i++) { var dependency = dependencies[i]; if (!(isListening.hasOwnProperty(dependency) && isListening[dependency])) { return false; } } return true; }, trapBubbledEvent: function (topLevelType, handlerBaseName, handle) { return ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(topLevelType, handlerBaseName, handle); }, trapCapturedEvent: function (topLevelType, handlerBaseName, handle) { return ReactBrowserEventEmitter.ReactEventListener.trapCapturedEvent(topLevelType, handlerBaseName, handle); }, /** * Protect against document.createEvent() returning null * Some popup blocker extensions appear to do this: * https://github.com/facebook/react/issues/6887 */ supportsEventPageXY: function () { if (!document.createEvent) { return false; } var ev = document.createEvent('MouseEvent'); return ev != null && 'pageX' in ev; }, /** * Listens to window scroll and resize events. We cache scroll values so that * application code can access them without triggering reflows. * * ViewportMetrics is only used by SyntheticMouse/TouchEvent and only when * pageX/pageY isn't supported (legacy browsers). * * NOTE: Scroll events do not bubble. * * @see http://www.quirksmode.org/dom/events/scroll.html */ ensureScrollValueMonitoring: function () { if (hasEventPageXY === undefined) { hasEventPageXY = ReactBrowserEventEmitter.supportsEventPageXY(); } if (!hasEventPageXY && !isMonitoringScrollValue) { var refresh = ViewportMetrics.refreshScrollValues; ReactBrowserEventEmitter.ReactEventListener.monitorScrollValue(refresh); isMonitoringScrollValue = true; } } }); module.exports = ReactBrowserEventEmitter; },{"118":118,"121":121,"157":157,"17":17,"54":54,"98":98}],25:[function(_dereq_,module,exports){ (function (process){ /** * Copyright 2014-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'; var KeyEscapeUtils = _dereq_(22); var ReactFeatureFlags = _dereq_(56); var ReactReconciler = _dereq_(70); var instantiateReactComponent = _dereq_(120); var shouldUpdateReactComponent = _dereq_(127); var traverseAllChildren = _dereq_(128); var warning = _dereq_(156); var ReactComponentTreeHook; if (typeof process !== 'undefined' && process.env && "development" === 'test') { // Temporary hack. // Inline requires don't work well with Jest: // https://github.com/facebook/react/issues/7240 // Remove the inline requires when we don't need them anymore: // https://github.com/facebook/react/pull/7178 ReactComponentTreeHook = _dereq_(131); } function instantiateChild(childInstances, child, name, selfDebugID) { // We found a component instance. var keyUnique = childInstances[name] === undefined; if ("development" !== 'production') { if (!ReactComponentTreeHook) { ReactComponentTreeHook = _dereq_(131); } if (!keyUnique) { "development" !== 'production' ? warning(false, 'flattenChildren(...): Encountered two children with the same key, ' + '`%s`. Child keys must be unique; when two children share a key, only ' + 'the first child will be used.%s', KeyEscapeUtils.unescape(name), ReactComponentTreeHook.getStackAddendumByID(selfDebugID)) : void 0; } } if (child != null && keyUnique) { childInstances[name] = instantiateReactComponent(child, true); } } /** * ReactChildReconciler provides helpers for initializing or updating a set of * children. Its output is suitable for passing it onto ReactMultiChild which * does diffed reordering and insertion. */ var ReactChildReconciler = { /** * Generates a "mount image" for each of the supplied children. In the case * of `ReactDOMComponent`, a mount image is a string of markup. * * @param {?object} nestedChildNodes Nested child maps. * @return {?object} A set of child instances. * @internal */ instantiateChildren: function (nestedChildNodes, transaction, context, selfDebugID // 0 in production and for roots ) { if (nestedChildNodes == null) { return null; } var childInstances = {}; if ("development" !== 'production') { traverseAllChildren(nestedChildNodes, function (childInsts, child, name) { return instantiateChild(childInsts, child, name, selfDebugID); }, childInstances); } else { traverseAllChildren(nestedChildNodes, instantiateChild, childInstances); } return childInstances; }, /** * Updates the rendered children and returns a new set of children. * * @param {?object} prevChildren Previously initialized set of children. * @param {?object} nextChildren Flat child element maps. * @param {ReactReconcileTransaction} transaction * @param {object} context * @return {?object} A new set of child instances. * @internal */ updateChildren: function (prevChildren, nextChildren, mountImages, removedNodes, transaction, hostParent, hostContainerInfo, context, selfDebugID // 0 in production and for roots ) { // We currently don't have a way to track moves here but if we use iterators // instead of for..in we can zip the iterators and check if an item has // moved. // TODO: If nothing has changed, return the prevChildren object so that we // can quickly bailout if nothing has changed. if (!nextChildren && !prevChildren) { return; } var name; var prevChild; for (name in nextChildren) { if (!nextChildren.hasOwnProperty(name)) { continue; } prevChild = prevChildren && prevChildren[name]; var prevElement = prevChild && prevChild._currentElement; var nextElement = nextChildren[name]; if (prevChild != null && shouldUpdateReactComponent(prevElement, nextElement)) { ReactReconciler.receiveComponent(prevChild, nextElement, transaction, context); nextChildren[name] = prevChild; } else { if (!ReactFeatureFlags.prepareNewChildrenBeforeUnmountInStack && prevChild) { removedNodes[name] = ReactReconciler.getHostNode(prevChild); ReactReconciler.unmountComponent(prevChild, false, /* safely */ false /* skipLifecycle */ ); } // The child must be instantiated before it's mounted. var nextChildInstance = instantiateReactComponent(nextElement, true); nextChildren[name] = nextChildInstance; // Creating mount image now ensures refs are resolved in right order // (see https://github.com/facebook/react/pull/7101 for explanation). var nextChildMountImage = ReactReconciler.mountComponent(nextChildInstance, transaction, hostParent, hostContainerInfo, context, selfDebugID); mountImages.push(nextChildMountImage); if (ReactFeatureFlags.prepareNewChildrenBeforeUnmountInStack && prevChild) { removedNodes[name] = ReactReconciler.getHostNode(prevChild); ReactReconciler.unmountComponent(prevChild, false, /* safely */ false /* skipLifecycle */ ); } } } // Unmount children that are no longer present. for (name in prevChildren) { if (prevChildren.hasOwnProperty(name) && !(nextChildren && nextChildren.hasOwnProperty(name))) { prevChild = prevChildren[name]; removedNodes[name] = ReactReconciler.getHostNode(prevChild); ReactReconciler.unmountComponent(prevChild, false, /* safely */ false /* skipLifecycle */ ); } } }, /** * Unmounts all rendered children. This should be used to clean up children * when this component is unmounted. * * @param {?object} renderedChildren Previously initialized set of children. * @internal */ unmountChildren: function (renderedChildren, safely, skipLifecycle) { for (var name in renderedChildren) { if (renderedChildren.hasOwnProperty(name)) { var renderedChild = renderedChildren[name]; ReactReconciler.unmountComponent(renderedChild, safely, skipLifecycle); } } } }; module.exports = ReactChildReconciler; }).call(this,undefined) },{"120":120,"127":127,"128":128,"131":131,"156":156,"22":22,"56":56,"70":70}],26:[function(_dereq_,module,exports){ /** * 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. * */ 'use strict'; var DOMChildrenOperations = _dereq_(8); var ReactDOMIDOperations = _dereq_(37); /** * Abstracts away all functionality of the reconciler that requires knowledge of * the browser context. TODO: These callers should be refactored to avoid the * need for this injection. */ var ReactComponentBrowserEnvironment = { processChildrenUpdates: ReactDOMIDOperations.dangerouslyProcessChildrenUpdates, replaceNodeWithMarkup: DOMChildrenOperations.dangerouslyReplaceNodeWithMarkup }; module.exports = ReactComponentBrowserEnvironment; },{"37":37,"8":8}],27:[function(_dereq_,module,exports){ /** * Copyright 2014-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'; var _prodInvariant = _dereq_(124); var invariant = _dereq_(149); var injected = false; var ReactComponentEnvironment = { /** * Optionally injectable hook for swapping out mount images in the middle of * the tree. */ replaceNodeWithMarkup: null, /** * Optionally injectable hook for processing a queue of child updates. Will * later move into MultiChildComponents. */ processChildrenUpdates: null, injection: { injectEnvironment: function (environment) { !!injected ? "development" !== 'production' ? invariant(false, 'ReactCompositeComponent: injectEnvironment() can only be called once.') : _prodInvariant('104') : void 0; ReactComponentEnvironment.replaceNodeWithMarkup = environment.replaceNodeWithMarkup; ReactComponentEnvironment.processChildrenUpdates = environment.processChildrenUpdates; injected = true; } } }; module.exports = ReactComponentEnvironment; },{"124":124,"149":149}],28:[function(_dereq_,module,exports){ /** * 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. * */ 'use strict'; var _prodInvariant = _dereq_(124), _assign = _dereq_(157); var React = _dereq_(133); var ReactComponentEnvironment = _dereq_(27); var ReactCompositeComponentTypes = _dereq_(29); var ReactCurrentOwner = _dereq_(132); var ReactErrorUtils = _dereq_(53); var ReactFeatureFlags = _dereq_(56); var ReactInstanceMap = _dereq_(61); var ReactInstrumentation = _dereq_(62); var ReactNodeTypes = _dereq_(66); var ReactReconciler = _dereq_(70); if ("development" !== 'production') { var checkReactTypeSpec = _dereq_(101); } var emptyObject = _dereq_(142); var invariant = _dereq_(149); var shallowEqual = _dereq_(155); var shouldUpdateReactComponent = _dereq_(127); var warning = _dereq_(156); function StatelessComponent(Component) {} StatelessComponent.prototype.render = function () { var Component = ReactInstanceMap.get(this)._currentElement.type; var element = Component(this.props, this.context, this.updater); warnIfInvalidElement(Component, element); return element; }; function warnIfInvalidElement(Component, element) { if ("development" !== 'production') { "development" !== 'production' ? warning(element === null || element === false || React.isValidElement(element), '%s(...): A valid React element (or null) must be returned. You may have ' + 'returned undefined, an array or some other invalid object.', Component.displayName || Component.name || 'Component') : void 0; "development" !== 'production' ? warning(!Component.childContextTypes, '%s(...): childContextTypes cannot be defined on a functional component.', Component.displayName || Component.name || 'Component') : void 0; } } function shouldConstruct(Component) { return !!(Component.prototype && Component.prototype.isReactComponent); } function isPureComponent(Component) { return !!(Component.prototype && Component.prototype.isPureReactComponent); } // Separated into a function to contain deoptimizations caused by try/finally. function measureLifeCyclePerf(fn, debugID, timerType) { if (debugID === 0) { // Top-level wrappers (see ReactMount) and empty components (see // ReactDOMEmptyComponent) are invisible to hooks and devtools. // Both are implementation details that should go away in the future. return fn(); } ReactInstrumentation.debugTool.onBeginLifeCycleTimer(debugID, timerType); try { return fn(); } finally { ReactInstrumentation.debugTool.onEndLifeCycleTimer(debugID, timerType); } } /** * ------------------ The Life-Cycle of a Composite Component ------------------ * * - constructor: Initialization of state. The instance is now retained. * - componentWillMount * - render * - [children's constructors] * - [children's componentWillMount and render] * - [children's componentDidMount] * - componentDidMount * * Update Phases: * - componentWillReceiveProps (only called if parent updated) * - shouldComponentUpdate * - componentWillUpdate * - render * - [children's constructors or receive props phases] * - componentDidUpdate * * - componentWillUnmount * - [children's componentWillUnmount] * - [children destroyed] * - (destroyed): The instance is now blank, released by React and ready for GC. * * ----------------------------------------------------------------------------- */ /** * An incrementing ID assigned to each component when it is mounted. This is * used to enforce the order in which `ReactUpdates` updates dirty components. * * @private */ var nextMountID = 1; /** * @lends {ReactCompositeComponent.prototype} */ var ReactCompositeComponent = { /** * Base constructor for all composite component. * * @param {ReactElement} element * @final * @internal */ construct: function (element) { this._currentElement = element; this._rootNodeID = 0; this._compositeType = null; this._instance = null; this._hostParent = null; this._hostContainerInfo = null; // See ReactUpdateQueue this._updateBatchNumber = null; this._pendingElement = null; this._pendingStateQueue = null; this._pendingReplaceState = false; this._pendingForceUpdate = false; this._renderedNodeType = null; this._renderedComponent = null; this._context = null; this._mountOrder = 0; this._topLevelWrapper = null; // See ReactUpdates and ReactUpdateQueue. this._pendingCallbacks = null; // ComponentWillUnmount shall only be called once this._calledComponentWillUnmount = false; if ("development" !== 'production') { this._warnedAboutRefsInRender = false; } }, /** * Initializes the component, renders markup, and registers event listeners. * * @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction * @param {?object} hostParent * @param {?object} hostContainerInfo * @param {?object} context * @return {?string} Rendered markup to be inserted into the DOM. * @final * @internal */ mountComponent: function (transaction, hostParent, hostContainerInfo, context) { var _this = this; this._context = context; this._mountOrder = nextMountID++; this._hostParent = hostParent; this._hostContainerInfo = hostContainerInfo; var publicProps = this._currentElement.props; var publicContext = this._processContext(context); var Component = this._currentElement.type; var updateQueue = transaction.getUpdateQueue(); // Initialize the public class var doConstruct = shouldConstruct(Component); var inst = this._constructComponent(doConstruct, publicProps, publicContext, updateQueue); var renderedElement; // Support functional components if (!doConstruct && (inst == null || inst.render == null)) { renderedElement = inst; warnIfInvalidElement(Component, renderedElement); !(inst === null || inst === false || React.isValidElement(inst)) ? "development" !== 'production' ? invariant(false, '%s(...): A valid React element (or null) must be returned. You may have returned undefined, an array or some other invalid object.', Component.displayName || Component.name || 'Component') : _prodInvariant('105', Component.displayName || Component.name || 'Component') : void 0; inst = new StatelessComponent(Component); this._compositeType = ReactCompositeComponentTypes.StatelessFunctional; } else { if (isPureComponent(Component)) { this._compositeType = ReactCompositeComponentTypes.PureClass; } else { this._compositeType = ReactCompositeComponentTypes.ImpureClass; } } if ("development" !== 'production') { // This will throw later in _renderValidatedComponent, but add an early // warning now to help debugging if (inst.render == null) { "development" !== 'production' ? warning(false, '%s(...): No `render` method found on the returned component ' + 'instance: you may have forgotten to define `render`.', Component.displayName || Component.name || 'Component') : void 0; } var propsMutated = inst.props !== publicProps; var componentName = Component.displayName || Component.name || 'Component'; "development" !== 'production' ? warning(inst.props === undefined || !propsMutated, '%s(...): When calling super() in `%s`, make sure to pass ' + 'up the same props that your component\'s constructor was passed.', componentName, componentName) : void 0; } // These should be set up in the constructor, but as a convenience for // simpler class abstractions, we set them up after the fact. inst.props = publicProps; inst.context = publicContext; inst.refs = emptyObject; inst.updater = updateQueue; this._instance = inst; // Store a reference from the instance back to the internal representation ReactInstanceMap.set(inst, this); if ("development" !== 'production') { // Since plain JS classes are defined without any special initialization // logic, we can not catch common errors early. Therefore, we have to // catch them here, at initialization time, instead. "development" !== 'production' ? warning(!inst.getInitialState || inst.getInitialState.isReactClassApproved || inst.state, 'getInitialState was defined on %s, a plain JavaScript class. ' + 'This is only supported for classes created using React.createClass. ' + 'Did you mean to define a state property instead?', this.getName() || 'a component') : void 0; "development" !== 'production' ? warning(!inst.getDefaultProps || inst.getDefaultProps.isReactClassApproved, 'getDefaultProps was defined on %s, a plain JavaScript class. ' + 'This is only supported for classes created using React.createClass. ' + 'Use a static property to define defaultProps instead.', this.getName() || 'a component') : void 0; "development" !== 'production' ? warning(!inst.propTypes, 'propTypes was defined as an instance property on %s. Use a static ' + 'property to define propTypes instead.', this.getName() || 'a component') : void 0; "development" !== 'production' ? warning(!inst.contextTypes, 'contextTypes was defined as an instance property on %s. Use a ' + 'static property to define contextTypes instead.', this.getName() || 'a component') : void 0; "development" !== 'production' ? warning(typeof inst.componentShouldUpdate !== 'function', '%s has a method called ' + 'componentShouldUpdate(). Did you mean shouldComponentUpdate()? ' + 'The name is phrased as a question because the function is ' + 'expected to return a value.', this.getName() || 'A component') : void 0; "development" !== 'production' ? warning(typeof inst.componentDidUnmount !== 'function', '%s has a method called ' + 'componentDidUnmount(). But there is no such lifecycle method. ' + 'Did you mean componentWillUnmount()?', this.getName() || 'A component') : void 0; "development" !== 'production' ? warning(typeof inst.componentWillRecieveProps !== 'function', '%s has a method called ' + 'componentWillRecieveProps(). Did you mean componentWillReceiveProps()?', this.getName() || 'A component') : void 0; } var initialState = inst.state; if (initialState === undefined) { inst.state = initialState = null; } !(typeof initialState === 'object' && !Array.isArray(initialState)) ? "development" !== 'production' ? invariant(false, '%s.state: must be set to an object or null', this.getName() || 'ReactCompositeComponent') : _prodInvariant('106', this.getName() || 'ReactCompositeComponent') : void 0; this._pendingStateQueue = null; this._pendingReplaceState = false; this._pendingForceUpdate = false; if (inst.componentWillMount) { if ("development" !== 'production') { measureLifeCyclePerf(function () { return inst.componentWillMount(); }, this._debugID, 'componentWillMount'); } else { inst.componentWillMount(); } // When mounting, calls to `setState` by `componentWillMount` will set // `this._pendingStateQueue` without triggering a re-render. if (this._pendingStateQueue) { inst.state = this._processPendingState(inst.props, inst.context); } } var markup; if (inst.unstable_handleError) { markup = this.performInitialMountWithErrorHandling(renderedElement, hostParent, hostContainerInfo, transaction, context); } else { markup = this.performInitialMount(renderedElement, hostParent, hostContainerInfo, transaction, context); } if (inst.componentDidMount) { if ("development" !== 'production') { transaction.getReactMountReady().enqueue(function () { measureLifeCyclePerf(function () { return inst.componentDidMount(); }, _this._debugID, 'componentDidMount'); }); } else { transaction.getReactMountReady().enqueue(inst.componentDidMount, inst); } } // setState callbacks during willMount should end up here var callbacks = this._pendingCallbacks; if (callbacks) { this._pendingCallbacks = null; for (var i = 0; i < callbacks.length; i++) { transaction.getReactMountReady().enqueue(callbacks[i], inst); } } return markup; }, _constructComponent: function (doConstruct, publicProps, publicContext, updateQueue) { if ("development" !== 'production') { ReactCurrentOwner.current = this; try { return this._constructComponentWithoutOwner(doConstruct, publicProps, publicContext, updateQueue); } finally { ReactCurrentOwner.current = null; } } else { return this._constructComponentWithoutOwner(doConstruct, publicProps, publicContext, updateQueue); } }, _constructComponentWithoutOwner: function (doConstruct, publicProps, publicContext, updateQueue) { var Component = this._currentElement.type; if (doConstruct) { if ("development" !== 'production') { return measureLifeCyclePerf(function () { return new Component(publicProps, publicContext, updateQueue); }, this._debugID, 'ctor'); } else { return new Component(publicProps, publicContext, updateQueue); } } // This can still be an instance in case of factory components // but we'll count this as time spent rendering as the more common case. if ("development" !== 'production') { return measureLifeCyclePerf(function () { return Component(publicProps, publicContext, updateQueue); }, this._debugID, 'render'); } else { return Component(publicProps, publicContext, updateQueue); } }, performInitialMountWithErrorHandling: function (renderedElement, hostParent, hostContainerInfo, transaction, context) { var markup; var checkpoint = transaction.checkpoint(); try { markup = this.performInitialMount(renderedElement, hostParent, hostContainerInfo, transaction, context); } catch (e) { // Roll back to checkpoint, handle error (which may add items to the transaction), and take a new checkpoint transaction.rollback(checkpoint); this._instance.unstable_handleError(e); if (this._pendingStateQueue) { this._instance.state = this._processPendingState(this._instance.props, this._instance.context); } checkpoint = transaction.checkpoint(); this._renderedComponent.unmountComponent(true, /* safely */ // Don't call componentWillUnmount() because they never fully mounted: true /* skipLifecyle */ ); transaction.rollback(checkpoint); // Try again - we've informed the component about the error, so they can render an error message this time. // If this throws again, the error will bubble up (and can be caught by a higher error boundary). markup = this.performInitialMount(renderedElement, hostParent, hostContainerInfo, transaction, context); } return markup; }, performInitialMount: function (renderedElement, hostParent, hostContainerInfo, transaction, context) { // If not a stateless component, we now render if (renderedElement === undefined) { renderedElement = this._renderValidatedComponent(); } var nodeType = ReactNodeTypes.getType(renderedElement); this._renderedNodeType = nodeType; var child = this._instantiateReactComponent(renderedElement, nodeType !== ReactNodeTypes.EMPTY /* shouldHaveDebugID */ ); this._renderedComponent = child; var debugID = 0; if ("development" !== 'production') { debugID = this._debugID; } var markup = ReactReconciler.mountComponent(child, transaction, hostParent, hostContainerInfo, this._processChildContext(context), debugID); if ("development" !== 'production') { if (debugID !== 0) { var childDebugIDs = child._debugID !== 0 ? [child._debugID] : []; ReactInstrumentation.debugTool.onSetChildren(debugID, childDebugIDs); } } return markup; }, getHostNode: function () { return ReactReconciler.getHostNode(this._renderedComponent); }, /** * Releases any resources allocated by `mountComponent`. * * @final * @internal */ unmountComponent: function (safely, skipLifecycle) { if (!this._renderedComponent) { return; } var inst = this._instance; if (inst.componentWillUnmount && !inst._calledComponentWillUnmount) { inst._calledComponentWillUnmount = true; if (safely) { if (!skipLifecycle) { var name = this.getName() + '.componentWillUnmount()'; ReactErrorUtils.invokeGuardedCallback(name, inst.componentWillUnmount.bind(inst)); } } else { if ("development" !== 'production') { measureLifeCyclePerf(function () { return inst.componentWillUnmount(); }, this._debugID, 'componentWillUnmount'); } else { inst.componentWillUnmount(); } } } if (this._renderedComponent) { ReactReconciler.unmountComponent(this._renderedComponent, safely, skipLifecycle); this._renderedNodeType = null; this._renderedComponent = null; this._instance = null; } // Reset pending fields // Even if this component is scheduled for another update in ReactUpdates, // it would still be ignored because these fields are reset. this._pendingStateQueue = null; this._pendingReplaceState = false; this._pendingForceUpdate = false; this._pendingCallbacks = null; this._pendingElement = null; // These fields do not really need to be reset since this object is no // longer accessible. this._context = null; this._rootNodeID = 0; this._topLevelWrapper = null; // Delete the reference from the instance to this internal representation // which allow the internals to be properly cleaned up even if the user // leaks a reference to the public instance. ReactInstanceMap.remove(inst); // Some existing components rely on inst.props even after they've been // destroyed (in event handlers). // TODO: inst.props = null; // TODO: inst.state = null; // TODO: inst.context = null; }, /** * Filters the context object to only contain keys specified in * `contextTypes` * * @param {object} context * @return {?object} * @private */ _maskContext: function (context) { var Component = this._currentElement.type; var contextTypes = Component.contextTypes; if (!contextTypes) { return emptyObject; } var maskedContext = {}; for (var contextName in contextTypes) { maskedContext[contextName] = context[contextName]; } return maskedContext; }, /** * Filters the context object to only contain keys specified in * `contextTypes`, and asserts that they are valid. * * @param {object} context * @return {?object} * @private */ _processContext: function (context) { var maskedContext = this._maskContext(context); if ("development" !== 'production') { var Component = this._currentElement.type; if (Component.contextTypes) { this._checkContextTypes(Component.contextTypes, maskedContext, 'context'); } } return maskedContext; }, /** * @param {object} currentContext * @return {object} * @private */ _processChildContext: function (currentContext) { var Component = this._currentElement.type; var inst = this._instance; var childContext; if (typeof inst.getChildContext === 'function') { if ("development" !== 'production') { ReactInstrumentation.debugTool.onBeginProcessingChildContext(); try { childContext = inst.getChildContext(); } finally { ReactInstrumentation.debugTool.onEndProcessingChildContext(); } } else { childContext = inst.getChildContext(); } !(typeof Component.childContextTypes === 'object') ? "development" !== 'production' ? invariant(false, '%s.getChildContext(): childContextTypes must be defined in order to use getChildContext().', this.getName() || 'ReactCompositeComponent') : _prodInvariant('107', this.getName() || 'ReactCompositeComponent') : void 0; if ("development" !== 'production') { this._checkContextTypes(Component.childContextTypes, childContext, 'childContext'); } for (var name in childContext) { !(name in Component.childContextTypes) ? "development" !== 'production' ? invariant(false, '%s.getChildContext(): key "%s" is not defined in childContextTypes.', this.getName() || 'ReactCompositeComponent', name) : _prodInvariant('108', this.getName() || 'ReactCompositeComponent', name) : void 0; } return _assign({}, currentContext, childContext); } return currentContext; }, /** * Assert that the context types are valid * * @param {object} typeSpecs Map of context field to a ReactPropType * @param {object} values Runtime values that need to be type-checked * @param {string} location e.g. "prop", "context", "child context" * @private */ _checkContextTypes: function (typeSpecs, values, location) { if ("development" !== 'production') { checkReactTypeSpec(typeSpecs, values, location, this.getName(), null, this._debugID); } }, receiveComponent: function (nextElement, transaction, nextContext) { var prevElement = this._currentElement; var prevContext = this._context; this._pendingElement = null; this.updateComponent(transaction, prevElement, nextElement, prevContext, nextContext); }, /** * If any of `_pendingElement`, `_pendingStateQueue`, or `_pendingForceUpdate` * is set, update the component. * * @param {ReactReconcileTransaction} transaction * @internal */ performUpdateIfNecessary: function (transaction) { if (this._pendingElement != null) { ReactReconciler.receiveComponent(this, this._pendingElement, transaction, this._context); } else if (this._pendingStateQueue !== null || this._pendingForceUpdate) { this.updateComponent(transaction, this._currentElement, this._currentElement, this._context, this._context); } else { var callbacks = this._pendingCallbacks; this._pendingCallbacks = null; if (callbacks) { for (var j = 0; j < callbacks.length; j++) { transaction.getReactMountReady().enqueue(callbacks[j], this.getPublicInstance()); } } this._updateBatchNumber = null; } }, /** * Perform an update to a mounted component. The componentWillReceiveProps and * shouldComponentUpdate methods are called, then (assuming the update isn't * skipped) the remaining update lifecycle methods are called and the DOM * representation is updated. * * By default, this implements React's rendering and reconciliation algorithm. * Sophisticated clients may wish to override this. * * @param {ReactReconcileTransaction} transaction * @param {ReactElement} prevParentElement * @param {ReactElement} nextParentElement * @internal * @overridable */ updateComponent: function (transaction, prevParentElement, nextParentElement, prevUnmaskedContext, nextUnmaskedContext) { var inst = this._instance; !(inst != null) ? "development" !== 'production' ? invariant(false, 'Attempted to update component `%s` that has already been unmounted (or failed to mount).', this.getName() || 'ReactCompositeComponent') : _prodInvariant('136', this.getName() || 'ReactCompositeComponent') : void 0; var willReceive = false; var nextContext; // Determine if the context has changed or not if (this._context === nextUnmaskedContext) { nextContext = inst.context; } else { nextContext = this._processContext(nextUnmaskedContext); willReceive = true; } var prevProps = prevParentElement.props; var nextProps = nextParentElement.props; // Not a simple state update but a props update if (prevParentElement !== nextParentElement) { willReceive = true; } // An update here will schedule an update but immediately set // _pendingStateQueue which will ensure that any state updates gets // immediately reconciled instead of waiting for the next batch. if (willReceive && inst.componentWillReceiveProps) { if ("development" !== 'production') { measureLifeCyclePerf(function () { return inst.componentWillReceiveProps(nextProps, nextContext); }, this._debugID, 'componentWillReceiveProps'); } else { inst.componentWillReceiveProps(nextProps, nextContext); } } // If updating happens to enqueue any new updates, we shouldn't execute new // callbacks until the next render happens, so stash the callbacks first. var callbacks = this._pendingCallbacks; this._pendingCallbacks = null; var nextState = this._processPendingState(nextProps, nextContext); var shouldUpdate = true; if (!this._pendingForceUpdate) { var prevState = inst.state; shouldUpdate = willReceive || nextState !== prevState; if (inst.shouldComponentUpdate) { if ("development" !== 'production') { shouldUpdate = measureLifeCyclePerf(function () { return inst.shouldComponentUpdate(nextProps, nextState, nextContext); }, this._debugID, 'shouldComponentUpdate'); } else { shouldUpdate = inst.shouldComponentUpdate(nextProps, nextState, nextContext); } } else { if (this._compositeType === ReactCompositeComponentTypes.PureClass) { shouldUpdate = !shallowEqual(prevProps, nextProps) || !shallowEqual(inst.state, nextState); } } } if ("development" !== 'production') { "development" !== 'production' ? warning(shouldUpdate !== undefined, '%s.shouldComponentUpdate(): Returned undefined instead of a ' + 'boolean value. Make sure to return true or false.', this.getName() || 'ReactCompositeComponent') : void 0; } this._updateBatchNumber = null; if (shouldUpdate) { this._pendingForceUpdate = false; // Will set `this.props`, `this.state` and `this.context`. this._performComponentUpdate(nextParentElement, nextProps, nextState, nextContext, transaction, nextUnmaskedContext); } else { // If it's determined that a component should not update, we still want // to set props and state but we shortcut the rest of the update. this._currentElement = nextParentElement; this._context = nextUnmaskedContext; inst.props = nextProps; inst.state = nextState; inst.context = nextContext; } if (callbacks) { for (var j = 0; j < callbacks.length; j++) { transaction.getReactMountReady().enqueue(callbacks[j], this.getPublicInstance()); } } }, _processPendingState: function (props, context) { var inst = this._instance; var queue = this._pendingStateQueue; var replace = this._pendingReplaceState; this._pendingReplaceState = false; this._pendingStateQueue = null; if (!queue) { return inst.state; } if (replace && queue.length === 1) { return queue[0]; } var nextState = replace ? queue[0] : inst.state; var dontMutate = true; for (var i = replace ? 1 : 0; i < queue.length; i++) { var partial = queue[i]; var partialState = typeof partial === 'function' ? partial.call(inst, nextState, props, context) : partial; if (partialState) { if (dontMutate) { dontMutate = false; nextState = _assign({}, nextState, partialState); } else { _assign(nextState, partialState); } } } return nextState; }, /** * Merges new props and state, notifies delegate methods of update and * performs update. * * @param {ReactElement} nextElement Next element * @param {object} nextProps Next public object to set as properties. * @param {?object} nextState Next object to set as state. * @param {?object} nextContext Next public object to set as context. * @param {ReactReconcileTransaction} transaction * @param {?object} unmaskedContext * @private */ _performComponentUpdate: function (nextElement, nextProps, nextState, nextContext, transaction, unmaskedContext) { var _this2 = this; var inst = this._instance; var hasComponentDidUpdate = Boolean(inst.componentDidUpdate); var prevProps; var prevState; var prevContext; if (hasComponentDidUpdate) { prevProps = inst.props; prevState = inst.state; prevContext = inst.context; } if (inst.componentWillUpdate) { if ("development" !== 'production') { measureLifeCyclePerf(function () { return inst.componentWillUpdate(nextProps, nextState, nextContext); }, this._debugID, 'componentWillUpdate'); } else { inst.componentWillUpdate(nextProps, nextState, nextContext); } } this._currentElement = nextElement; this._context = unmaskedContext; inst.props = nextProps; inst.state = nextState; inst.context = nextContext; if (inst.unstable_handleError) { this._updateRenderedComponentWithErrorHandling(transaction, unmaskedContext); } else { this._updateRenderedComponent(transaction, unmaskedContext); } if (hasComponentDidUpdate) { if ("development" !== 'production') { transaction.getReactMountReady().enqueue(function () { measureLifeCyclePerf(inst.componentDidUpdate.bind(inst, prevProps, prevState, prevContext), _this2._debugID, 'componentDidUpdate'); }); } else { transaction.getReactMountReady().enqueue(inst.componentDidUpdate.bind(inst, prevProps, prevState, prevContext), inst); } } }, /** * Call the component's `render` method and update the DOM accordingly. * * @param {ReactReconcileTransaction} transaction * @internal */ _updateRenderedComponentWithErrorHandling: function (transaction, context) { var checkpoint = transaction.checkpoint(); try { this._updateRenderedComponent(transaction, context); } catch (e) { // Roll back to checkpoint, handle error (which may add items to the transaction), // and take a new checkpoint transaction.rollback(checkpoint); this._instance.unstable_handleError(e); if (this._pendingStateQueue) { this._instance.state = this._processPendingState(this._instance.props, this._instance.context); } checkpoint = transaction.checkpoint(); // Gracefully update to a clean state this._updateRenderedComponentWithNextElement(transaction, context, null, true /* safely */ ); // Try again - we've informed the component about the error, so they can render an error message this time. // If this throws again, the error will bubble up (and can be caught by a higher error boundary). this._updateRenderedComponent(transaction, context); } }, /** * Call the component's `render` method and update the DOM accordingly. * * @param {ReactReconcileTransaction} transaction * @internal */ _updateRenderedComponent: function (transaction, context) { var nextRenderedElement = this._renderValidatedComponent(); this._updateRenderedComponentWithNextElement(transaction, context, nextRenderedElement, false /* safely */ ); }, /** * Call the component's `render` method and update the DOM accordingly. * * @param {ReactReconcileTransaction} transaction * @internal */ _updateRenderedComponentWithNextElement: function (transaction, context, nextRenderedElement, safely) { var prevComponentInstance = this._renderedComponent; var prevRenderedElement = prevComponentInstance._currentElement; var debugID = 0; if ("development" !== 'production') { debugID = this._debugID; } if (shouldUpdateReactComponent(prevRenderedElement, nextRenderedElement)) { ReactReconciler.receiveComponent(prevComponentInstance, nextRenderedElement, transaction, this._processChildContext(context)); } else { var oldHostNode = ReactReconciler.getHostNode(prevComponentInstance); if (!ReactFeatureFlags.prepareNewChildrenBeforeUnmountInStack) { ReactReconciler.unmountComponent(prevComponentInstance, safely, false /* skipLifecycle */ ); } var nodeType = ReactNodeTypes.getType(nextRenderedElement); this._renderedNodeType = nodeType; var child = this._instantiateReactComponent(nextRenderedElement, nodeType !== ReactNodeTypes.EMPTY /* shouldHaveDebugID */ ); this._renderedComponent = child; var nextMarkup = ReactReconciler.mountComponent(child, transaction, this._hostParent, this._hostContainerInfo, this._processChildContext(context), debugID); if (ReactFeatureFlags.prepareNewChildrenBeforeUnmountInStack) { ReactReconciler.unmountComponent(prevComponentInstance, safely, false /* skipLifecycle */ ); } if ("development" !== 'production') { if (debugID !== 0) { var childDebugIDs = child._debugID !== 0 ? [child._debugID] : []; ReactInstrumentation.debugTool.onSetChildren(debugID, childDebugIDs); } } this._replaceNodeWithMarkup(oldHostNode, nextMarkup, prevComponentInstance); } }, /** * Overridden in shallow rendering. * * @protected */ _replaceNodeWithMarkup: function (oldHostNode, nextMarkup, prevInstance) { ReactComponentEnvironment.replaceNodeWithMarkup(oldHostNode, nextMarkup, prevInstance); }, /** * @protected */ _renderValidatedComponentWithoutOwnerOrContext: function () { var inst = this._instance; var renderedElement; if ("development" !== 'production') { renderedElement = measureLifeCyclePerf(function () { return inst.render(); }, this._debugID, 'render'); } else { renderedElement = inst.render(); } if ("development" !== 'production') { // We allow auto-mocks to proceed as if they're returning null. if (renderedElement === undefined && inst.render._isMockFunction) { // This is probably bad practice. Consider warning here and // deprecating this convenience. renderedElement = null; } } return renderedElement; }, /** * @private */ _renderValidatedComponent: function () { var renderedElement; if ("development" !== 'production' || this._compositeType !== ReactCompositeComponentTypes.StatelessFunctional) { ReactCurrentOwner.current = this; try { renderedElement = this._renderValidatedComponentWithoutOwnerOrContext(); } finally { ReactCurrentOwner.current = null; } } else { renderedElement = this._renderValidatedComponentWithoutOwnerOrContext(); } !( // TODO: An `isValidNode` function would probably be more appropriate renderedElement === null || renderedElement === false || React.isValidElement(renderedElement)) ? "development" !== 'production' ? invariant(false, '%s.render(): A valid React element (or null) must be returned. You may have returned undefined, an array or some other invalid object.', this.getName() || 'ReactCompositeComponent') : _prodInvariant('109', this.getName() || 'ReactCompositeComponent') : void 0; return renderedElement; }, /** * Lazily allocates the refs object and stores `component` as `ref`. * * @param {string} ref Reference name. * @param {component} component Component to store as `ref`. * @final * @private */ attachRef: function (ref, component) { var inst = this.getPublicInstance(); !(inst != null) ? "development" !== 'production' ? invariant(false, 'Stateless function components cannot have refs.') : _prodInvariant('110') : void 0; var publicComponentInstance = component.getPublicInstance(); var refs = inst.refs === emptyObject ? inst.refs = {} : inst.refs; refs[ref] = publicComponentInstance; }, /** * Detaches a reference name. * * @param {string} ref Name to dereference. * @final * @private */ detachRef: function (ref) { var refs = this.getPublicInstance().refs; delete refs[ref]; }, /** * Get a text description of the component that can be used to identify it * in error messages. * @return {string} The name or null. * @internal */ getName: function () { var type = this._currentElement.type; var constructor = this._instance && this._instance.constructor; return type.displayName || constructor && constructor.displayName || type.name || constructor && constructor.name || null; }, /** * Get the publicly accessible representation of this component - i.e. what * is exposed by refs and returned by render. Can be null for stateless * components. * * @return {ReactComponent} the public component instance. * @internal */ getPublicInstance: function () { var inst = this._instance; if (this._compositeType === ReactCompositeComponentTypes.StatelessFunctional) { return null; } return inst; }, // Stub _instantiateReactComponent: null }; module.exports = ReactCompositeComponent; },{"101":101,"124":124,"127":127,"132":132,"133":133,"142":142,"149":149,"155":155,"156":156,"157":157,"27":27,"29":29,"53":53,"56":56,"61":61,"62":62,"66":66,"70":70}],29:[function(_dereq_,module,exports){ "use strict"; module.exports = { ImpureClass: 0, PureClass: 1, StatelessFunctional: 2 }; /** * 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 ReactCompositeComponentTypes * */ },{}],30:[function(_dereq_,module,exports){ /** * 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. * */ 'use strict'; var _prodInvariant = _dereq_(124); var EventPluginUtils = _dereq_(18); var invariant = _dereq_(149); // Use to restore controlled state after a change event has fired. var fiberHostComponent = null; var ReactControlledComponentInjection = { injectFiberControlledHostComponent: function (hostComponentImpl) { // The fiber implementation doesn't use dynamic dispatch so we need to // inject the implementation. fiberHostComponent = hostComponentImpl; } }; var restoreTarget = null; var restoreQueue = null; function restoreStateOfTarget(target) { // We perform this translation at the end of the event loop so that we // always receive the correct fiber here var internalInstance = EventPluginUtils.getInstanceFromNode(target); if (!internalInstance) { // Unmounted return; } if (typeof internalInstance.tag === 'number') { invariant(fiberHostComponent && typeof fiberHostComponent.restoreControlledState === 'function', 'Fiber needs to be injected to handle a fiber target for controlled ' + 'events.'); fiberHostComponent.restoreControlledState(internalInstance.stateNode, internalInstance.type, internalInstance.memoizedProps); return; } invariant(typeof internalInstance.restoreControlledState === 'function', 'The internal instance must be a React host component.'); // If it is not a Fiber, we can just use dynamic dispatch. internalInstance.restoreControlledState(); } var ReactControlledComponent = { injection: ReactControlledComponentInjection, enqueueStateRestore: function (target) { if (restoreTarget) { if (restoreQueue) { restoreQueue.push(target); } else { restoreQueue = [target]; } } else { restoreTarget = target; } }, restoreStateIfNeeded: function () { if (!restoreTarget) { return; } var target = restoreTarget; var queuedTargets = restoreQueue; restoreTarget = null; restoreQueue = null; restoreStateOfTarget(target); if (queuedTargets) { for (var i = 0; i < queuedTargets.length; i++) { restoreStateOfTarget(queuedTargets[i]); } } } }; module.exports = ReactControlledComponent; },{"124":124,"149":149,"18":18}],31:[function(_dereq_,module,exports){ /** * 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. * */ 'use strict'; var React = _dereq_(133); var warning = _dereq_(156); var hasReadOnlyValue = { 'button': true, 'checkbox': true, 'image': true, 'hidden': true, 'radio': true, 'reset': true, 'submit': true }; var propTypes = { value: function (props, propName, componentName) { if (!props[propName] || hasReadOnlyValue[props.type] || props.onChange || props.readOnly || props.disabled) { return null; } return new Error('You provided a `value` prop to a form field without an ' + '`onChange` handler. This will render a read-only field. If ' + 'the field should be mutable use `defaultValue`. Otherwise, ' + 'set either `onChange` or `readOnly`.'); }, checked: function (props, propName, componentName) { if (!props[propName] || props.onChange || props.readOnly || props.disabled) { return null; } return new Error('You provided a `checked` prop to a form field without an ' + '`onChange` handler. This will render a read-only field. If ' + 'the field should be mutable use `defaultChecked`. Otherwise, ' + 'set either `onChange` or `readOnly`.'); }, onChange: React.PropTypes.func }; var loggedTypeFailures = {}; function getDeclarationErrorAddendum(ownerName) { if (ownerName) { return ' Check the render method of `' + ownerName + '`.'; } return ''; } /** * Provide a linked `value` attribute for controlled forms. You should not use * this outside of the ReactDOM controlled form components. */ var ReactControlledValuePropTypes = { checkPropTypes: function (tagName, props, ownerName) { for (var propName in propTypes) { if (propTypes.hasOwnProperty(propName)) { var error = propTypes[propName](props, propName, tagName, 'prop'); } if (error instanceof Error && !(error.message in loggedTypeFailures)) { // Only monitor this failure once because there tends to be a lot of the // same error. loggedTypeFailures[error.message] = true; var addendum = getDeclarationErrorAddendum(ownerName); "development" !== 'production' ? warning(false, 'Failed form propType: %s%s', error.message, addendum) : void 0; } } } }; module.exports = ReactControlledValuePropTypes; },{"133":133,"156":156}],32:[function(_dereq_,module,exports){ /** * 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. * */ /* global hasOwnProperty:true */ 'use strict'; var _prodInvariant = _dereq_(124), _assign = _dereq_(157); var AutoFocusUtils = _dereq_(2); var CSSPropertyOperations = _dereq_(5); var DOMLazyTree = _dereq_(10); var DOMNamespaces = _dereq_(11); var DOMProperty = _dereq_(12); var DOMPropertyOperations = _dereq_(13); var EventPluginRegistry = _dereq_(17); var ReactBrowserEventEmitter = _dereq_(24); var ReactDOMComponentFlags = _dereq_(33); var ReactDOMComponentTree = _dereq_(34); var ReactDOMInput = _dereq_(39); var ReactDOMOption = _dereq_(40); var ReactDOMSelect = _dereq_(41); var ReactDOMTextarea = _dereq_(47); var ReactInstrumentation = _dereq_(62); var ReactMultiChild = _dereq_(65); var ReactServerRenderingTransaction = _dereq_(74); var emptyFunction = _dereq_(141); var escapeTextContentForBrowser = _dereq_(104); var invariant = _dereq_(149); var isEventSupported = _dereq_(121); var inputValueTracking = _dereq_(119); var validateDOMNesting = _dereq_(130); var warning = _dereq_(156); var didWarnShadyDOM = false; var Flags = ReactDOMComponentFlags; var getNode = ReactDOMComponentTree.getNodeFromInstance; var listenTo = ReactBrowserEventEmitter.listenTo; var registrationNameModules = EventPluginRegistry.registrationNameModules; // For quickly matching children type, to test if can be treated as content. var CONTENT_TYPES = { 'string': true, 'number': true }; var STYLE = 'style'; var HTML = '__html'; var RESERVED_PROPS = { children: null, dangerouslySetInnerHTML: null, suppressContentEditableWarning: null }; // Node type for document fragments (Node.DOCUMENT_FRAGMENT_NODE). var DOC_FRAGMENT_TYPE = 11; function getDeclarationErrorAddendum(internalInstance) { if (internalInstance) { var owner = internalInstance._currentElement._owner || null; if (owner) { var name = owner.getName(); if (name) { return ' This DOM node was rendered by `' + name + '`.'; } } } return ''; } /** * @param {object} component * @param {?object} props */ function assertValidProps(component, props) { if (!props) { return; } // Note the use of `==` which checks for null or undefined. if (voidElementTags[component._tag]) { !(props.children == null && props.dangerouslySetInnerHTML == null) ? "development" !== 'production' ? invariant(false, '%s is a void element tag and must neither have `children` nor use `dangerouslySetInnerHTML`.%s', component._tag, getDeclarationErrorAddendum(component)) : _prodInvariant('137', component._tag, getDeclarationErrorAddendum(component)) : void 0; } if (props.dangerouslySetInnerHTML != null) { !(props.children == null) ? "development" !== 'production' ? invariant(false, 'Can only set one of `children` or `props.dangerouslySetInnerHTML`.') : _prodInvariant('60') : void 0; !(typeof props.dangerouslySetInnerHTML === 'object' && HTML in props.dangerouslySetInnerHTML) ? "development" !== 'production' ? invariant(false, '`props.dangerouslySetInnerHTML` must be in the form `{__html: ...}`. Please visit https://fb.me/react-invariant-dangerously-set-inner-html for more information.') : _prodInvariant('61') : void 0; } if ("development" !== 'production') { "development" !== 'production' ? warning(props.innerHTML == null, 'Directly setting property `innerHTML` is not permitted. ' + 'For more information, lookup documentation on `dangerouslySetInnerHTML`.') : void 0; "development" !== 'production' ? warning(props.suppressContentEditableWarning || !props.contentEditable || props.children == null, 'A component is `contentEditable` and contains `children` managed by ' + 'React. It is now your responsibility to guarantee that none of ' + 'those nodes are unexpectedly modified or duplicated. This is ' + 'probably not intentional.') : void 0; "development" !== 'production' ? warning(props.onFocusIn == null && props.onFocusOut == null, 'React uses onFocus and onBlur instead of onFocusIn and onFocusOut. ' + 'All React events are normalized to bubble, so onFocusIn and onFocusOut ' + 'are not needed/supported by React.') : void 0; } !(props.style == null || typeof props.style === 'object') ? "development" !== 'production' ? invariant(false, 'The `style` prop expects a mapping from style properties to values, not a string. For example, style={{marginRight: spacing + \'em\'}} when using JSX.%s', getDeclarationErrorAddendum(component)) : _prodInvariant('62', getDeclarationErrorAddendum(component)) : void 0; } function ensureListeningTo(inst, registrationName, transaction) { if (transaction instanceof ReactServerRenderingTransaction) { return; } if ("development" !== 'production') { // IE8 has no API for event capturing and the `onScroll` event doesn't // bubble. "development" !== 'production' ? warning(registrationName !== 'onScroll' || isEventSupported('scroll', true), 'This browser doesn\'t support the `onScroll` event') : void 0; } var containerInfo = inst._hostContainerInfo; var isDocumentFragment = containerInfo._node && containerInfo._node.nodeType === DOC_FRAGMENT_TYPE; var doc = isDocumentFragment ? containerInfo._node : containerInfo._ownerDocument; listenTo(registrationName, doc); } function inputPostMount() { var inst = this; ReactDOMInput.postMountWrapper(inst); } function textareaPostMount() { var inst = this; ReactDOMTextarea.postMountWrapper(inst); } function optionPostMount() { var inst = this; ReactDOMOption.postMountWrapper(inst); } var setAndValidateContentChildDev = emptyFunction; if ("development" !== 'production') { setAndValidateContentChildDev = function (content) { var hasExistingContent = this._contentDebugID != null; var debugID = this._debugID; // This ID represents the inlined child that has no backing instance: var contentDebugID = -debugID; if (content == null) { if (hasExistingContent) { ReactInstrumentation.debugTool.onUnmountComponent(this._contentDebugID); } this._contentDebugID = null; return; } validateDOMNesting(null, String(content), this, this._ancestorInfo); this._contentDebugID = contentDebugID; if (hasExistingContent) { ReactInstrumentation.debugTool.onBeforeUpdateComponent(contentDebugID, content); ReactInstrumentation.debugTool.onUpdateComponent(contentDebugID); } else { ReactInstrumentation.debugTool.onBeforeMountComponent(contentDebugID, content, debugID); ReactInstrumentation.debugTool.onMountComponent(contentDebugID); ReactInstrumentation.debugTool.onSetChildren(debugID, [contentDebugID]); } }; } // There are so many media events, it makes sense to just // maintain a list rather than create a `trapBubbledEvent` for each var mediaEvents = { topAbort: 'abort', topCanPlay: 'canplay', topCanPlayThrough: 'canplaythrough', topDurationChange: 'durationchange', topEmptied: 'emptied', topEncrypted: 'encrypted', topEnded: 'ended', topError: 'error', topLoadedData: 'loadeddata', topLoadedMetadata: 'loadedmetadata', topLoadStart: 'loadstart', topPause: 'pause', topPlay: 'play', topPlaying: 'playing', topProgress: 'progress', topRateChange: 'ratechange', topSeeked: 'seeked', topSeeking: 'seeking', topStalled: 'stalled', topSuspend: 'suspend', topTimeUpdate: 'timeupdate', topVolumeChange: 'volumechange', topWaiting: 'waiting' }; function trackInputValue() { inputValueTracking.track(this); } function trapClickOnNonInteractiveElement() { // Mobile Safari does not fire properly bubble click events on // non-interactive elements, which means delegated click listeners do not // fire. The workaround for this bug involves attaching an empty click // listener on the target node. // http://www.quirksmode.org/blog/archives/2010/09/click_event_del.html // Just set it using the onclick property so that we don't have to manage any // bookkeeping for it. Not sure if we need to clear it when the listener is // removed. // TODO: Only do this for the relevant Safaris maybe? var node = getNode(this); node.onclick = emptyFunction; } function trapBubbledEventsLocal() { var inst = this; // If a component renders to null or if another component fatals and causes // the state of the tree to be corrupted, `node` here can be null. !inst._rootNodeID ? "development" !== 'production' ? invariant(false, 'Must be mounted to trap events') : _prodInvariant('63') : void 0; var node = getNode(inst); !node ? "development" !== 'production' ? invariant(false, 'trapBubbledEvent(...): Requires node to be rendered.') : _prodInvariant('64') : void 0; switch (inst._tag) { case 'iframe': case 'object': inst._wrapperState.listeners = [ReactBrowserEventEmitter.trapBubbledEvent('topLoad', 'load', node)]; break; case 'video': case 'audio': inst._wrapperState.listeners = []; // Create listener for each media event for (var event in mediaEvents) { if (mediaEvents.hasOwnProperty(event)) { inst._wrapperState.listeners.push(ReactBrowserEventEmitter.trapBubbledEvent(event, mediaEvents[event], node)); } } break; case 'source': inst._wrapperState.listeners = [ReactBrowserEventEmitter.trapBubbledEvent('topError', 'error', node)]; break; case 'img': inst._wrapperState.listeners = [ReactBrowserEventEmitter.trapBubbledEvent('topError', 'error', node), ReactBrowserEventEmitter.trapBubbledEvent('topLoad', 'load', node)]; break; case 'form': inst._wrapperState.listeners = [ReactBrowserEventEmitter.trapBubbledEvent('topReset', 'reset', node), ReactBrowserEventEmitter.trapBubbledEvent('topSubmit', 'submit', node)]; break; case 'input': case 'select': case 'textarea': inst._wrapperState.listeners = [ReactBrowserEventEmitter.trapBubbledEvent('topInvalid', 'invalid', node)]; break; } } function postUpdateSelectWrapper() { ReactDOMSelect.postUpdateWrapper(this); } // For HTML, certain tags should omit their close tag. We keep a whitelist for // those special-case tags. var omittedCloseTags = { 'area': true, 'base': true, 'br': true, 'col': true, 'embed': true, 'hr': true, 'img': true, 'input': true, 'keygen': true, 'link': true, 'meta': true, 'param': true, 'source': true, 'track': true, 'wbr': true }; var newlineEatingTags = { 'listing': true, 'pre': true, 'textarea': true }; // For HTML, certain tags cannot have children. This has the same purpose as // `omittedCloseTags` except that `menuitem` should still have its closing tag. var voidElementTags = _assign({ 'menuitem': true }, omittedCloseTags); // We accept any tag to be rendered but since this gets injected into arbitrary // HTML, we want to make sure that it's a safe tag. // http://www.w3.org/TR/REC-xml/#NT-Name var VALID_TAG_REGEX = /^[a-zA-Z][a-zA-Z:_\.\-\d]*$/; // Simplified subset var validatedTagCache = {}; var hasOwnProperty = {}.hasOwnProperty; function validateDangerousTag(tag) { if (!hasOwnProperty.call(validatedTagCache, tag)) { !VALID_TAG_REGEX.test(tag) ? "development" !== 'production' ? invariant(false, 'Invalid tag: %s', tag) : _prodInvariant('65', tag) : void 0; validatedTagCache[tag] = true; } } function isCustomComponent(tagName, props) { return tagName.indexOf('-') >= 0 || props.is != null; } var globalIdCounter = 1; /** * Creates a new React class that is idempotent and capable of containing other * React components. It accepts event listeners and DOM properties that are * valid according to `DOMProperty`. * * - Event listeners: `onClick`, `onMouseDown`, etc. * - DOM properties: `className`, `name`, `title`, etc. * * The `style` property functions differently from the DOM API. It accepts an * object mapping of style properties to values. * * @constructor ReactDOMComponent * @extends ReactMultiChild */ function ReactDOMComponent(element) { var tag = element.type; this._currentElement = element; this._tag = tag.toLowerCase(); this._namespaceURI = null; this._renderedChildren = null; this._hostNode = null; this._hostParent = null; this._rootNodeID = 0; this._domID = 0; this._hostContainerInfo = null; this._wrapperState = null; this._topLevelWrapper = null; this._flags = 0; if ("development" !== 'production') { this._ancestorInfo = null; setAndValidateContentChildDev.call(this, null); } } ReactDOMComponent.displayName = 'ReactDOMComponent'; ReactDOMComponent.Mixin = { /** * Generates root tag markup then recurses. This method has side effects and * is not idempotent. * * @internal * @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction * @param {?ReactDOMComponent} the parent component instance * @param {?object} info about the host container * @param {object} context * @return {string} The computed markup. */ mountComponent: function (transaction, hostParent, hostContainerInfo, context) { this._rootNodeID = globalIdCounter++; this._domID = hostContainerInfo._idCounter++; this._hostParent = hostParent; this._hostContainerInfo = hostContainerInfo; var props = this._currentElement.props; switch (this._tag) { case 'audio': case 'form': case 'iframe': case 'img': case 'link': case 'object': case 'source': case 'video': this._wrapperState = { listeners: null }; transaction.getReactMountReady().enqueue(trapBubbledEventsLocal, this); break; case 'input': ReactDOMInput.mountWrapper(this, props, hostParent); props = ReactDOMInput.getHostProps(this, props); transaction.getReactMountReady().enqueue(trackInputValue, this); transaction.getReactMountReady().enqueue(trapBubbledEventsLocal, this); // For controlled components we always need to ensure we're listening // to onChange. Even if there is no listener. ensureListeningTo(this, 'onChange', transaction); break; case 'option': ReactDOMOption.mountWrapper(this, props, hostParent); props = ReactDOMOption.getHostProps(this, props); break; case 'select': ReactDOMSelect.mountWrapper(this, props, hostParent); props = ReactDOMSelect.getHostProps(this, props); transaction.getReactMountReady().enqueue(trapBubbledEventsLocal, this); // For controlled components we always need to ensure we're listening // to onChange. Even if there is no listener. ensureListeningTo(this, 'onChange', transaction); break; case 'textarea': ReactDOMTextarea.mountWrapper(this, props, hostParent); props = ReactDOMTextarea.getHostProps(this, props); transaction.getReactMountReady().enqueue(trackInputValue, this); transaction.getReactMountReady().enqueue(trapBubbledEventsLocal, this); // For controlled components we always need to ensure we're listening // to onChange. Even if there is no listener. ensureListeningTo(this, 'onChange', transaction); break; } assertValidProps(this, props); // We create tags in the namespace of their parent container, except HTML // tags get no namespace. var namespaceURI; var parentTag; if (hostParent != null) { namespaceURI = hostParent._namespaceURI; parentTag = hostParent._tag; } else if (hostContainerInfo._tag) { namespaceURI = hostContainerInfo._namespaceURI; parentTag = hostContainerInfo._tag; } if (namespaceURI == null || namespaceURI === DOMNamespaces.svg && parentTag === 'foreignobject') { namespaceURI = DOMNamespaces.html; } if (namespaceURI === DOMNamespaces.html) { if ("development" !== 'production') { "development" !== 'production' ? warning(isCustomComponent(this._tag, props) || this._tag === this._currentElement.type, '<%s /> is using uppercase HTML. Always use lowercase HTML tags ' + 'in React.', this._currentElement.type) : void 0; } if (this._tag === 'svg') { namespaceURI = DOMNamespaces.svg; } else if (this._tag === 'math') { namespaceURI = DOMNamespaces.mathml; } } this._namespaceURI = namespaceURI; if ("development" !== 'production') { var parentInfo; if (hostParent != null) { parentInfo = hostParent._ancestorInfo; } else if (hostContainerInfo._tag) { parentInfo = hostContainerInfo._ancestorInfo; } if (parentInfo) { // parentInfo should always be present except for the top-level // component when server rendering validateDOMNesting(this._tag, null, this, parentInfo); } this._ancestorInfo = validateDOMNesting.updatedAncestorInfo(parentInfo, this._tag, this); } var mountImage; var type = this._currentElement.type; if (transaction.useCreateElement) { var ownerDocument = hostContainerInfo._ownerDocument; var el; if (namespaceURI === DOMNamespaces.html) { if (this._tag === 'script') { // Create the script via .innerHTML so its "parser-inserted" flag is // set to true and it does not execute var div = ownerDocument.createElement('div'); div.innerHTML = '<' + type + '></' + type + '>'; el = div.removeChild(div.firstChild); } else if (props.is) { el = ownerDocument.createElement(type, props.is); } else { // Separate else branch instead of using `props.is || undefined` above becuase of a Firefox bug. // See discussion in https://github.com/facebook/react/pull/6896 // and discussion in https://bugzilla.mozilla.org/show_bug.cgi?id=1276240 el = ownerDocument.createElement(type); } } else { el = ownerDocument.createElementNS(namespaceURI, type); } var isCustomComponentTag = isCustomComponent(this._tag, props); if ("development" !== 'production' && isCustomComponentTag && !didWarnShadyDOM && el.shadyRoot) { var owner = this._currentElement._owner; var name = owner && owner.getName() || 'A component'; "development" !== 'production' ? warning(false, '%s is using shady DOM. Using shady DOM with React can ' + 'cause things to break subtly.', name) : void 0; didWarnShadyDOM = true; } ReactDOMComponentTree.precacheNode(this, el); this._flags |= Flags.hasCachedChildNodes; if (!this._hostParent) { DOMPropertyOperations.setAttributeForRoot(el); } this._updateDOMProperties(null, props, transaction, isCustomComponentTag); var lazyTree = DOMLazyTree(el); this._createInitialChildren(transaction, props, context, lazyTree); mountImage = lazyTree; } else { validateDangerousTag(this._tag); var tagOpen = this._createOpenTagMarkupAndPutListeners(transaction, props); var tagContent = this._createContentMarkup(transaction, props, context); if (!tagContent && omittedCloseTags[this._tag]) { mountImage = tagOpen + '/>'; } else { mountImage = tagOpen + '>' + tagContent + '</' + type + '>'; } } switch (this._tag) { case 'input': transaction.getReactMountReady().enqueue(inputPostMount, this); if (props.autoFocus) { transaction.getReactMountReady().enqueue(AutoFocusUtils.focusDOMComponent, this); } break; case 'textarea': transaction.getReactMountReady().enqueue(textareaPostMount, this); if (props.autoFocus) { transaction.getReactMountReady().enqueue(AutoFocusUtils.focusDOMComponent, this); } break; case 'select': if (props.autoFocus) { transaction.getReactMountReady().enqueue(AutoFocusUtils.focusDOMComponent, this); } break; case 'button': if (props.autoFocus) { transaction.getReactMountReady().enqueue(AutoFocusUtils.focusDOMComponent, this); } break; case 'option': transaction.getReactMountReady().enqueue(optionPostMount, this); break; default: if (typeof props.onClick === 'function') { transaction.getReactMountReady().enqueue(trapClickOnNonInteractiveElement, this); } break; } return mountImage; }, /** * Creates markup for the open tag and all attributes. * * This method has side effects because events get registered. * * Iterating over object properties is faster than iterating over arrays. * @see http://jsperf.com/obj-vs-arr-iteration * * @private * @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction * @param {object} props * @return {string} Markup of opening tag. */ _createOpenTagMarkupAndPutListeners: function (transaction, props) { var ret = '<' + this._currentElement.type; for (var propKey in props) { if (!props.hasOwnProperty(propKey)) { continue; } var propValue = props[propKey]; if (propValue == null) { continue; } if (registrationNameModules.hasOwnProperty(propKey)) { if (propValue) { ensureListeningTo(this, propKey, transaction); } } else { if (propKey === STYLE) { if (propValue) { if ("development" !== 'production') { Object.freeze(propValue); } } propValue = CSSPropertyOperations.createMarkupForStyles(propValue, this); } var markup = null; if (this._tag != null && isCustomComponent(this._tag, props)) { if (!RESERVED_PROPS.hasOwnProperty(propKey)) { markup = DOMPropertyOperations.createMarkupForCustomAttribute(propKey, propValue); } } else { markup = DOMPropertyOperations.createMarkupForProperty(propKey, propValue); } if (markup) { ret += ' ' + markup; } } } // For static pages, no need to put React ID and checksum. Saves lots of // bytes. if (transaction.renderToStaticMarkup) { return ret; } if (!this._hostParent) { ret += ' ' + DOMPropertyOperations.createMarkupForRoot(); } ret += ' ' + DOMPropertyOperations.createMarkupForID(this._domID); return ret; }, /** * Creates markup for the content between the tags. * * @private * @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction * @param {object} props * @param {object} context * @return {string} Content markup. */ _createContentMarkup: function (transaction, props, context) { var ret = ''; // Intentional use of != to avoid catching zero/false. var innerHTML = props.dangerouslySetInnerHTML; if (innerHTML != null) { if (innerHTML.__html != null) { ret = innerHTML.__html; } } else { var contentToUse = CONTENT_TYPES[typeof props.children] ? props.children : null; var childrenToUse = contentToUse != null ? null : props.children; if (contentToUse != null) { // TODO: Validate that text is allowed as a child of this node ret = escapeTextContentForBrowser(contentToUse); if ("development" !== 'production') { setAndValidateContentChildDev.call(this, contentToUse); } } else if (childrenToUse != null) { var mountImages = this.mountChildren(childrenToUse, transaction, context); ret = mountImages.join(''); } } if (newlineEatingTags[this._tag] && ret.charAt(0) === '\n') { // text/html ignores the first character in these tags if it's a newline // Prefer to break application/xml over text/html (for now) by adding // a newline specifically to get eaten by the parser. (Alternately for // textareas, replacing "^\n" with "\r\n" doesn't get eaten, and the first // \r is normalized out by HTMLTextAreaElement#value.) // See: <http://www.w3.org/TR/html-polyglot/#newlines-in-textarea-and-pre> // See: <http://www.w3.org/TR/html5/syntax.html#element-restrictions> // See: <http://www.w3.org/TR/html5/syntax.html#newlines> // See: Parsing of "textarea" "listing" and "pre" elements // from <http://www.w3.org/TR/html5/syntax.html#parsing-main-inbody> return '\n' + ret; } else { return ret; } }, _createInitialChildren: function (transaction, props, context, lazyTree) { // Intentional use of != to avoid catching zero/false. var innerHTML = props.dangerouslySetInnerHTML; if (innerHTML != null) { var innerHTMLContent = innerHTML.__html; if (innerHTMLContent != null && innerHTMLContent !== '') { DOMLazyTree.queueHTML(lazyTree, innerHTMLContent); } } else { var contentToUse = CONTENT_TYPES[typeof props.children] ? props.children : null; var childrenToUse = contentToUse != null ? null : props.children; // TODO: Validate that text is allowed as a child of this node if (contentToUse != null) { // Avoid setting textContent when the text is empty. In IE11 setting // textContent on a text area will cause the placeholder to not // show within the textarea until it has been focused and blurred again. // https://github.com/facebook/react/issues/6731#issuecomment-254874553 if (contentToUse !== '') { if ("development" !== 'production') { setAndValidateContentChildDev.call(this, contentToUse); } DOMLazyTree.queueText(lazyTree, contentToUse); } } else if (childrenToUse != null) { var mountImages = this.mountChildren(childrenToUse, transaction, context); for (var i = 0; i < mountImages.length; i++) { DOMLazyTree.queueChild(lazyTree, mountImages[i]); } } } }, /** * Receives a next element and updates the component. * * @internal * @param {ReactElement} nextElement * @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction * @param {object} context */ receiveComponent: function (nextElement, transaction, context) { var prevElement = this._currentElement; this._currentElement = nextElement; this.updateComponent(transaction, prevElement, nextElement, context); }, /** * Updates a DOM component after it has already been allocated and * attached to the DOM. Reconciles the root DOM node, then recurses. * * @param {ReactReconcileTransaction} transaction * @param {ReactElement} prevElement * @param {ReactElement} nextElement * @internal * @overridable */ updateComponent: function (transaction, prevElement, nextElement, context) { var lastProps = prevElement.props; var nextProps = this._currentElement.props; switch (this._tag) { case 'input': lastProps = ReactDOMInput.getHostProps(this, lastProps); nextProps = ReactDOMInput.getHostProps(this, nextProps); break; case 'option': lastProps = ReactDOMOption.getHostProps(this, lastProps); nextProps = ReactDOMOption.getHostProps(this, nextProps); break; case 'select': lastProps = ReactDOMSelect.getHostProps(this, lastProps); nextProps = ReactDOMSelect.getHostProps(this, nextProps); break; case 'textarea': lastProps = ReactDOMTextarea.getHostProps(this, lastProps); nextProps = ReactDOMTextarea.getHostProps(this, nextProps); break; default: if (typeof lastProps.onClick !== 'function' && typeof nextProps.onClick === 'function') { transaction.getReactMountReady().enqueue(trapClickOnNonInteractiveElement, this); } break; } assertValidProps(this, nextProps); var isCustomComponentTag = isCustomComponent(this._tag, nextProps); this._updateDOMProperties(lastProps, nextProps, transaction, isCustomComponentTag); this._updateDOMChildren(lastProps, nextProps, transaction, context); switch (this._tag) { case 'input': // Update the wrapper around inputs *after* updating props. This has to // happen after `_updateDOMProperties`. Otherwise HTML5 input validations // raise warnings and prevent the new value from being assigned. ReactDOMInput.updateWrapper(this); break; case 'textarea': ReactDOMTextarea.updateWrapper(this); break; case 'select': // <select> value update needs to occur after <option> children // reconciliation transaction.getReactMountReady().enqueue(postUpdateSelectWrapper, this); break; } }, /** * Reconciles the properties by detecting differences in property values and * updating the DOM as necessary. This function is probably the single most * critical path for performance optimization. * * TODO: Benchmark whether checking for changed values in memory actually * improves performance (especially statically positioned elements). * TODO: Benchmark the effects of putting this at the top since 99% of props * do not change for a given reconciliation. * TODO: Benchmark areas that can be improved with caching. * * @private * @param {object} lastProps * @param {object} nextProps * @param {?DOMElement} node */ _updateDOMProperties: function (lastProps, nextProps, transaction, isCustomComponentTag) { var propKey; var styleName; var styleUpdates; for (propKey in lastProps) { if (nextProps.hasOwnProperty(propKey) || !lastProps.hasOwnProperty(propKey) || lastProps[propKey] == null) { continue; } if (propKey === STYLE) { var lastStyle = lastProps[STYLE]; for (styleName in lastStyle) { if (lastStyle.hasOwnProperty(styleName)) { styleUpdates = styleUpdates || {}; styleUpdates[styleName] = ''; } } } else if (registrationNameModules.hasOwnProperty(propKey)) { // Do nothing for event names. } else if (isCustomComponent(this._tag, lastProps)) { if (!RESERVED_PROPS.hasOwnProperty(propKey)) { DOMPropertyOperations.deleteValueForAttribute(getNode(this), propKey); } } else if (DOMProperty.properties[propKey] || DOMProperty.isCustomAttribute(propKey)) { DOMPropertyOperations.deleteValueForProperty(getNode(this), propKey); } } for (propKey in nextProps) { var nextProp = nextProps[propKey]; var lastProp = lastProps != null ? lastProps[propKey] : undefined; if (!nextProps.hasOwnProperty(propKey) || nextProp === lastProp || nextProp == null && lastProp == null) { continue; } if (propKey === STYLE) { if (nextProp) { if ("development" !== 'production') { Object.freeze(nextProp); } } if (lastProp) { // Unset styles on `lastProp` but not on `nextProp`. for (styleName in lastProp) { if (lastProp.hasOwnProperty(styleName) && (!nextProp || !nextProp.hasOwnProperty(styleName))) { styleUpdates = styleUpdates || {}; styleUpdates[styleName] = ''; } } // Update styles that changed since `lastProp`. for (styleName in nextProp) { if (nextProp.hasOwnProperty(styleName) && lastProp[styleName] !== nextProp[styleName]) { styleUpdates = styleUpdates || {}; styleUpdates[styleName] = nextProp[styleName]; } } } else { // Relies on `updateStylesByID` not mutating `styleUpdates`. styleUpdates = nextProp; } } else if (registrationNameModules.hasOwnProperty(propKey)) { if (nextProp) { ensureListeningTo(this, propKey, transaction); } } else if (isCustomComponentTag) { if (!RESERVED_PROPS.hasOwnProperty(propKey)) { DOMPropertyOperations.setValueForAttribute(getNode(this), propKey, nextProp); } } else if (DOMProperty.properties[propKey] || DOMProperty.isCustomAttribute(propKey)) { var node = getNode(this); // If we're updating to null or undefined, we should remove the property // from the DOM node instead of inadvertently setting to a string. This // brings us in line with the same behavior we have on initial render. if (nextProp != null) { DOMPropertyOperations.setValueForProperty(node, propKey, nextProp); } else { DOMPropertyOperations.deleteValueForProperty(node, propKey); } } } if (styleUpdates) { if ("development" !== 'production') { ReactInstrumentation.debugTool.onHostOperation({ instanceID: this._debugID, type: 'update styles', payload: styleUpdates }); } CSSPropertyOperations.setValueForStyles(getNode(this), styleUpdates, this); } }, /** * Reconciles the children with the various properties that affect the * children content. * * @param {object} lastProps * @param {object} nextProps * @param {ReactReconcileTransaction} transaction * @param {object} context */ _updateDOMChildren: function (lastProps, nextProps, transaction, context) { var lastContent = CONTENT_TYPES[typeof lastProps.children] ? lastProps.children : null; var nextContent = CONTENT_TYPES[typeof nextProps.children] ? nextProps.children : null; var lastHtml = lastProps.dangerouslySetInnerHTML && lastProps.dangerouslySetInnerHTML.__html; var nextHtml = nextProps.dangerouslySetInnerHTML && nextProps.dangerouslySetInnerHTML.__html; // Note the use of `!=` which checks for null or undefined. var lastChildren = lastContent != null ? null : lastProps.children; var nextChildren = nextContent != null ? null : nextProps.children; // If we're switching from children to content/html or vice versa, remove // the old content var lastHasContentOrHtml = lastContent != null || lastHtml != null; var nextHasContentOrHtml = nextContent != null || nextHtml != null; if (lastChildren != null && nextChildren == null) { this.updateChildren(null, transaction, context); } else if (lastHasContentOrHtml && !nextHasContentOrHtml) { this.updateTextContent(''); if ("development" !== 'production') { ReactInstrumentation.debugTool.onSetChildren(this._debugID, []); } } if (nextContent != null) { if (lastContent !== nextContent) { this.updateTextContent('' + nextContent); if ("development" !== 'production') { setAndValidateContentChildDev.call(this, nextContent); } } } else if (nextHtml != null) { if (lastHtml !== nextHtml) { this.updateMarkup('' + nextHtml); } if ("development" !== 'production') { ReactInstrumentation.debugTool.onSetChildren(this._debugID, []); } } else if (nextChildren != null) { if ("development" !== 'production') { setAndValidateContentChildDev.call(this, null); } this.updateChildren(nextChildren, transaction, context); } }, getHostNode: function () { return getNode(this); }, /** * Destroys all event registrations for this instance. Does not remove from * the DOM. That must be done by the parent. * * @internal */ unmountComponent: function (safely, skipLifecycle) { switch (this._tag) { case 'audio': case 'form': case 'iframe': case 'img': case 'link': case 'object': case 'source': case 'video': var listeners = this._wrapperState.listeners; if (listeners) { for (var i = 0; i < listeners.length; i++) { listeners[i].remove(); } } break; case 'input': case 'textarea': inputValueTracking.stopTracking(this); break; case 'html': case 'head': case 'body': /** * Components like <html> <head> and <body> can't be removed or added * easily in a cross-browser way, however it's valuable to be able to * take advantage of React's reconciliation for styling and <title> * management. So we just document it and throw in dangerous cases. */ !false ? "development" !== 'production' ? invariant(false, '<%s> tried to unmount. Because of cross-browser quirks it is impossible to unmount some top-level components (eg <html>, <head>, and <body>) reliably and efficiently. To fix this, have a single top-level component that never unmounts render these elements.', this._tag) : _prodInvariant('66', this._tag) : void 0; break; } this.unmountChildren(safely, skipLifecycle); ReactDOMComponentTree.uncacheNode(this); this._rootNodeID = 0; this._domID = 0; this._wrapperState = null; if ("development" !== 'production') { setAndValidateContentChildDev.call(this, null); } }, restoreControlledState: function () { switch (this._tag) { case 'input': ReactDOMInput.restoreControlledState(this); return; case 'textarea': ReactDOMTextarea.restoreControlledState(this); return; case 'select': ReactDOMSelect.restoreControlledState(this); return; } }, getPublicInstance: function () { return getNode(this); } }; _assign(ReactDOMComponent.prototype, ReactDOMComponent.Mixin, ReactMultiChild); module.exports = ReactDOMComponent; },{"10":10,"104":104,"11":11,"119":119,"12":12,"121":121,"124":124,"13":13,"130":130,"141":141,"149":149,"156":156,"157":157,"17":17,"2":2,"24":24,"33":33,"34":34,"39":39,"40":40,"41":41,"47":47,"5":5,"62":62,"65":65,"74":74}],33:[function(_dereq_,module,exports){ /** * Copyright 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'; var ReactDOMComponentFlags = { hasCachedChildNodes: 1 << 0 }; module.exports = ReactDOMComponentFlags; },{}],34:[function(_dereq_,module,exports){ /** * 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. * */ 'use strict'; var _prodInvariant = _dereq_(124); var DOMProperty = _dereq_(12); var ReactDOMComponentFlags = _dereq_(33); var _require = _dereq_(77), HostComponent = _require.HostComponent, HostText = _require.HostText; var invariant = _dereq_(149); var ATTR_NAME = DOMProperty.ID_ATTRIBUTE_NAME; var Flags = ReactDOMComponentFlags; var internalInstanceKey = '__reactInternalInstance$' + Math.random().toString(36).slice(2); /** * Check if a given node should be cached. */ function shouldPrecacheNode(node, nodeID) { return node.nodeType === 1 && node.getAttribute(ATTR_NAME) === String(nodeID) || node.nodeType === 8 && node.nodeValue === ' react-text: ' + nodeID + ' ' || node.nodeType === 8 && node.nodeValue === ' react-empty: ' + nodeID + ' '; } /** * Drill down (through composites and empty components) until we get a host or * host text component. * * This is pretty polymorphic but unavoidable with the current structure we have * for `_renderedChildren`. */ function getRenderedHostOrTextFromComponent(component) { var rendered; while (rendered = component._renderedComponent) { component = rendered; } return component; } /** * Populate `_hostNode` on the rendered host/text component with the given * DOM node. The passed `inst` can be a composite. */ function precacheNode(inst, node) { var hostInst = getRenderedHostOrTextFromComponent(inst); hostInst._hostNode = node; node[internalInstanceKey] = hostInst; } function precacheFiberNode(hostInst, node) { node[internalInstanceKey] = hostInst; } function uncacheNode(inst) { var node = inst._hostNode; if (node) { delete node[internalInstanceKey]; inst._hostNode = null; } } /** * Populate `_hostNode` on each child of `inst`, assuming that the children * match up with the DOM (element) children of `node`. * * We cache entire levels at once to avoid an n^2 problem where we access the * children of a node sequentially and have to walk from the start to our target * node every time. * * Since we update `_renderedChildren` and the actual DOM at (slightly) * different times, we could race here and see a newer `_renderedChildren` than * the DOM nodes we see. To avoid this, ReactMultiChild calls * `prepareToManageChildren` before we change `_renderedChildren`, at which * time the container's child nodes are always cached (until it unmounts). */ function precacheChildNodes(inst, node) { if (inst._flags & Flags.hasCachedChildNodes) { return; } var children = inst._renderedChildren; var childNode = node.firstChild; outer: for (var name in children) { if (!children.hasOwnProperty(name)) { continue; } var childInst = children[name]; var childID = getRenderedHostOrTextFromComponent(childInst)._domID; if (childID === 0) { // We're currently unmounting this child in ReactMultiChild; skip it. continue; } // We assume the child nodes are in the same order as the child instances. for (; childNode !== null; childNode = childNode.nextSibling) { if (shouldPrecacheNode(childNode, childID)) { precacheNode(childInst, childNode); continue outer; } } // We reached the end of the DOM children without finding an ID match. !false ? "development" !== 'production' ? invariant(false, 'Unable to find element with ID %s.', childID) : _prodInvariant('32', childID) : void 0; } inst._flags |= Flags.hasCachedChildNodes; } /** * Given a DOM node, return the closest ReactDOMComponent or * ReactDOMTextComponent instance ancestor. */ function getClosestInstanceFromNode(node) { if (node[internalInstanceKey]) { return node[internalInstanceKey]; } // Walk up the tree until we find an ancestor whose instance we have cached. var parents = []; while (!node[internalInstanceKey]) { parents.push(node); if (node.parentNode) { node = node.parentNode; } else { // Top of the tree. This node must not be part of a React tree (or is // unmounted, potentially). return null; } } var closest; var inst = node[internalInstanceKey]; if (inst.tag === HostComponent || inst.tag === HostText) { // In Fiber, this will always be the deepest root. return inst; } for (; node && (inst = node[internalInstanceKey]); node = parents.pop()) { closest = inst; if (parents.length) { precacheChildNodes(inst, node); } } return closest; } /** * Given a DOM node, return the ReactDOMComponent or ReactDOMTextComponent * instance, or null if the node was not rendered by this React. */ function getInstanceFromNode(node) { var inst = node[internalInstanceKey]; if (inst) { if (inst.tag === HostComponent || inst.tag === HostText) { return inst; } else if (inst._hostNode === node) { return inst; } else { return null; } } inst = getClosestInstanceFromNode(node); if (inst != null && inst._hostNode === node) { return inst; } else { return null; } } /** * Given a ReactDOMComponent or ReactDOMTextComponent, return the corresponding * DOM node. */ function getNodeFromInstance(inst) { if (inst.tag === HostComponent || inst.tag === HostText) { // In Fiber this, is just the state node right now. We assume it will be // a host component or host text. return inst.stateNode; } // Without this first invariant, passing a non-DOM-component triggers the next // invariant for a missing parent, which is super confusing. !(inst._hostNode !== undefined) ? "development" !== 'production' ? invariant(false, 'getNodeFromInstance: Invalid argument.') : _prodInvariant('33') : void 0; if (inst._hostNode) { return inst._hostNode; } // Walk up the tree until we find an ancestor whose DOM node we have cached. var parents = []; while (!inst._hostNode) { parents.push(inst); !inst._hostParent ? "development" !== 'production' ? invariant(false, 'React DOM tree root should always have a node reference.') : _prodInvariant('34') : void 0; inst = inst._hostParent; } // Now parents contains each ancestor that does *not* have a cached native // node, and `inst` is the deepest ancestor that does. for (; parents.length; inst = parents.pop()) { precacheChildNodes(inst, inst._hostNode); } return inst._hostNode; } var ReactDOMComponentTree = { getClosestInstanceFromNode: getClosestInstanceFromNode, getInstanceFromNode: getInstanceFromNode, getNodeFromInstance: getNodeFromInstance, precacheChildNodes: precacheChildNodes, precacheNode: precacheNode, uncacheNode: uncacheNode, precacheFiberNode: precacheFiberNode }; module.exports = ReactDOMComponentTree; },{"12":12,"124":124,"149":149,"33":33,"77":77}],35:[function(_dereq_,module,exports){ /** * 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. * */ 'use strict'; var validateDOMNesting = _dereq_(130); var DOC_NODE_TYPE = 9; function ReactDOMContainerInfo(topLevelWrapper, node) { var info = { _topLevelWrapper: topLevelWrapper, _idCounter: 1, _ownerDocument: node ? node.nodeType === DOC_NODE_TYPE ? node : node.ownerDocument : null, _node: node, _tag: node ? node.nodeName.toLowerCase() : null, _namespaceURI: node ? node.namespaceURI : null }; if ("development" !== 'production') { info._ancestorInfo = node ? validateDOMNesting.updatedAncestorInfo(null, info._tag, null) : null; } return info; } module.exports = ReactDOMContainerInfo; },{"130":130}],36:[function(_dereq_,module,exports){ /** * Copyright 2014-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'; var _assign = _dereq_(157); var DOMLazyTree = _dereq_(10); var ReactDOMComponentTree = _dereq_(34); var ReactDOMEmptyComponent = function (instantiate) { // ReactCompositeComponent uses this: this._currentElement = null; // ReactDOMComponentTree uses these: this._hostNode = null; this._hostParent = null; this._hostContainerInfo = null; this._domID = 0; }; _assign(ReactDOMEmptyComponent.prototype, { mountComponent: function (transaction, hostParent, hostContainerInfo, context) { var domID = hostContainerInfo._idCounter++; this._domID = domID; this._hostParent = hostParent; this._hostContainerInfo = hostContainerInfo; var nodeValue = ' react-empty: ' + this._domID + ' '; if (transaction.useCreateElement) { var ownerDocument = hostContainerInfo._ownerDocument; var node = ownerDocument.createComment(nodeValue); ReactDOMComponentTree.precacheNode(this, node); return DOMLazyTree(node); } else { if (transaction.renderToStaticMarkup) { // Normally we'd insert a comment node, but since this is a situation // where React won't take over (static pages), we can simply return // nothing. return ''; } return '<!--' + nodeValue + '-->'; } }, receiveComponent: function () {}, getHostNode: function () { return ReactDOMComponentTree.getNodeFromInstance(this); }, unmountComponent: function () { ReactDOMComponentTree.uncacheNode(this); } }); module.exports = ReactDOMEmptyComponent; },{"10":10,"157":157,"34":34}],37:[function(_dereq_,module,exports){ /** * 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. * */ 'use strict'; var DOMChildrenOperations = _dereq_(8); var ReactDOMComponentTree = _dereq_(34); /** * Operations used to process updates to DOM nodes. */ var ReactDOMIDOperations = { /** * Updates a component's children by processing a series of updates. * * @param {array<object>} updates List of update configurations. * @internal */ dangerouslyProcessChildrenUpdates: function (parentInst, updates) { var node = ReactDOMComponentTree.getNodeFromInstance(parentInst); DOMChildrenOperations.processUpdates(node, updates); } }; module.exports = ReactDOMIDOperations; },{"34":34,"8":8}],38:[function(_dereq_,module,exports){ /** * 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. * */ 'use strict'; var ARIADOMPropertyConfig = _dereq_(1); var BeforeInputEventPlugin = _dereq_(3); var DOMProperty = _dereq_(12); var ChangeEventPlugin = _dereq_(7); var DOMEventPluginOrder = _dereq_(9); var EnterLeaveEventPlugin = _dereq_(15); var EventPluginHub = _dereq_(16); var EventPluginUtils = _dereq_(18); var HTMLDOMPropertyConfig = _dereq_(21); var ReactBrowserEventEmitter = _dereq_(24); var ReactDOMComponentTree = _dereq_(34); var ReactEventListener = _dereq_(55); var SVGDOMPropertyConfig = _dereq_(81); var SelectEventPlugin = _dereq_(82); var SimpleEventPlugin = _dereq_(83); var alreadyInjected = false; function inject() { if (alreadyInjected) { // TODO: This is currently true because these injections are shared between // the client and the server package. They should be built independently // and not share any injection state. Then this problem will be solved. return; } alreadyInjected = true; ReactBrowserEventEmitter.injection.injectReactEventListener(ReactEventListener); /** * Inject modules for resolving DOM hierarchy and plugin ordering. */ EventPluginHub.injection.injectEventPluginOrder(DOMEventPluginOrder); EventPluginUtils.injection.injectComponentTree(ReactDOMComponentTree); /** * Some important event plugins included by default (without having to require * them). */ EventPluginHub.injection.injectEventPluginsByName({ SimpleEventPlugin: SimpleEventPlugin, EnterLeaveEventPlugin: EnterLeaveEventPlugin, ChangeEventPlugin: ChangeEventPlugin, SelectEventPlugin: SelectEventPlugin, BeforeInputEventPlugin: BeforeInputEventPlugin }); DOMProperty.injection.injectDOMPropertyConfig(ARIADOMPropertyConfig); DOMProperty.injection.injectDOMPropertyConfig(HTMLDOMPropertyConfig); DOMProperty.injection.injectDOMPropertyConfig(SVGDOMPropertyConfig); } module.exports = { inject: inject }; },{"1":1,"12":12,"15":15,"16":16,"18":18,"21":21,"24":24,"3":3,"34":34,"55":55,"7":7,"81":81,"82":82,"83":83,"9":9}],39:[function(_dereq_,module,exports){ /** * 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. * */ 'use strict'; var _prodInvariant = _dereq_(124), _assign = _dereq_(157); var DOMPropertyOperations = _dereq_(13); var ReactControlledValuePropTypes = _dereq_(31); var ReactDOMComponentTree = _dereq_(34); var invariant = _dereq_(149); var warning = _dereq_(156); var didWarnValueDefaultValue = false; var didWarnCheckedDefaultChecked = false; var didWarnControlledToUncontrolled = false; var didWarnUncontrolledToControlled = false; function isControlled(props) { var usesChecked = props.type === 'checkbox' || props.type === 'radio'; return usesChecked ? props.checked != null : props.value != null; } /** * Implements an <input> host component that allows setting these optional * props: `checked`, `value`, `defaultChecked`, and `defaultValue`. * * If `checked` or `value` are not supplied (or null/undefined), user actions * that affect the checked state or value will trigger updates to the element. * * If they are supplied (and not null/undefined), the rendered element will not * trigger updates to the element. Instead, the props must change in order for * the rendered element to be updated. * * The rendered element will be initialized as unchecked (or `defaultChecked`) * with an empty value (or `defaultValue`). * * @see http://www.w3.org/TR/2012/WD-html5-20121025/the-input-element.html */ var ReactDOMInput = { getHostProps: function (inst, props) { var value = props.value; var checked = props.checked; var hostProps = _assign({ // Make sure we set .type before any other properties (setting .value // before .type means .value is lost in IE11 and below) type: undefined, // Make sure we set .step before .value (setting .value before .step // means .value is rounded on mount, based upon step precision) step: undefined, // Make sure we set .min & .max before .value (to ensure proper order // in corner cases such as min or max deriving from value, e.g. Issue #7170) min: undefined, max: undefined }, props, { defaultChecked: undefined, defaultValue: undefined, value: value != null ? value : inst._wrapperState.initialValue, checked: checked != null ? checked : inst._wrapperState.initialChecked }); return hostProps; }, mountWrapper: function (inst, props) { if ("development" !== 'production') { var owner = inst._currentElement._owner; ReactControlledValuePropTypes.checkPropTypes('input', props, owner ? owner.getName() : null); if (props.checked !== undefined && props.defaultChecked !== undefined && !didWarnCheckedDefaultChecked) { "development" !== 'production' ? warning(false, '%s contains an input of type %s with both checked and defaultChecked props. ' + 'Input elements must be either controlled or uncontrolled ' + '(specify either the checked prop, or the defaultChecked prop, but not ' + 'both). Decide between using a controlled or uncontrolled input ' + 'element and remove one of these props. More info: ' + 'https://fb.me/react-controlled-components', owner && owner.getName() || 'A component', props.type) : void 0; didWarnCheckedDefaultChecked = true; } if (props.value !== undefined && props.defaultValue !== undefined && !didWarnValueDefaultValue) { "development" !== 'production' ? warning(false, '%s contains an input of type %s with both value and defaultValue props. ' + 'Input elements must be either controlled or uncontrolled ' + '(specify either the value prop, or the defaultValue prop, but not ' + 'both). Decide between using a controlled or uncontrolled input ' + 'element and remove one of these props. More info: ' + 'https://fb.me/react-controlled-components', owner && owner.getName() || 'A component', props.type) : void 0; didWarnValueDefaultValue = true; } } var defaultValue = props.defaultValue; inst._wrapperState = { initialChecked: props.checked != null ? props.checked : props.defaultChecked, initialValue: props.value != null ? props.value : defaultValue, listeners: null }; if ("development" !== 'production') { inst._wrapperState.controlled = isControlled(props); } }, updateWrapper: function (inst) { var props = inst._currentElement.props; if ("development" !== 'production') { var controlled = isControlled(props); var owner = inst._currentElement._owner; if (!inst._wrapperState.controlled && controlled && !didWarnUncontrolledToControlled) { "development" !== 'production' ? warning(false, '%s is changing an uncontrolled input of type %s to be controlled. ' + 'Input elements should not switch from uncontrolled to controlled (or vice versa). ' + 'Decide between using a controlled or uncontrolled input ' + 'element for the lifetime of the component. More info: https://fb.me/react-controlled-components', owner && owner.getName() || 'A component', props.type) : void 0; didWarnUncontrolledToControlled = true; } if (inst._wrapperState.controlled && !controlled && !didWarnControlledToUncontrolled) { "development" !== 'production' ? warning(false, '%s is changing a controlled input of type %s to be uncontrolled. ' + 'Input elements should not switch from controlled to uncontrolled (or vice versa). ' + 'Decide between using a controlled or uncontrolled input ' + 'element for the lifetime of the component. More info: https://fb.me/react-controlled-components', owner && owner.getName() || 'A component', props.type) : void 0; didWarnControlledToUncontrolled = true; } } var checked = props.checked; if (checked != null) { DOMPropertyOperations.setValueForProperty(ReactDOMComponentTree.getNodeFromInstance(inst), 'checked', checked || false); } var node = ReactDOMComponentTree.getNodeFromInstance(inst); var value = props.value; if (value != null) { // Cast `value` to a string to ensure the value is set correctly. While // browsers typically do this as necessary, jsdom doesn't. var newValue = '' + value; // To avoid side effects (such as losing text selection), only set value if changed if (newValue !== node.value) { node.value = newValue; } } else { if (props.value == null && props.defaultValue != null) { // In Chrome, assigning defaultValue to certain input types triggers input validation. // For number inputs, the display value loses trailing decimal points. For email inputs, // Chrome raises "The specified value <x> is not a valid email address". // // Here we check to see if the defaultValue has actually changed, avoiding these problems // when the user is inputting text // // https://github.com/facebook/react/issues/7253 if (node.defaultValue !== '' + props.defaultValue) { node.defaultValue = '' + props.defaultValue; } } if (props.checked == null && props.defaultChecked != null) { node.defaultChecked = !!props.defaultChecked; } } }, postMountWrapper: function (inst) { var props = inst._currentElement.props; // This is in postMount because we need access to the DOM node, which is not // available until after the component has mounted. var node = ReactDOMComponentTree.getNodeFromInstance(inst); // Detach value from defaultValue. We won't do anything if we're working on // submit or reset inputs as those values & defaultValues are linked. They // are not resetable nodes so this operation doesn't matter and actually // removes browser-default values (eg "Submit Query") when no value is // provided. switch (props.type) { case 'submit': case 'reset': break; case 'color': case 'date': case 'datetime': case 'datetime-local': case 'month': case 'time': case 'week': // This fixes the no-show issue on iOS Safari and Android Chrome: // https://github.com/facebook/react/issues/7233 node.value = ''; node.value = node.defaultValue; break; default: node.value = node.value; break; } // Normally, we'd just do `node.checked = node.checked` upon initial mount, less this bug // this is needed to work around a chrome bug where setting defaultChecked // will sometimes influence the value of checked (even after detachment). // Reference: https://bugs.chromium.org/p/chromium/issues/detail?id=608416 // We need to temporarily unset name to avoid disrupting radio button groups. var name = node.name; if (name !== '') { node.name = ''; } node.defaultChecked = !node.defaultChecked; node.defaultChecked = !node.defaultChecked; if (name !== '') { node.name = name; } }, restoreControlledState: function (inst) { if (inst._rootNodeID) { // DOM component is still mounted; update ReactDOMInput.updateWrapper(inst); } var props = inst._currentElement.props; updateNamedCousins(inst, props); } }; function updateNamedCousins(thisInstance, props) { var name = props.name; if (props.type === 'radio' && name != null) { var rootNode = ReactDOMComponentTree.getNodeFromInstance(thisInstance); var queryRoot = rootNode; while (queryRoot.parentNode) { queryRoot = queryRoot.parentNode; } // If `rootNode.form` was non-null, then we could try `form.elements`, // but that sometimes behaves strangely in IE8. We could also try using // `form.getElementsByName`, but that will only return direct children // and won't include inputs that use the HTML5 `form=` attribute. Since // the input might not even be in a form. It might not even be in the // document. Let's just use the local `querySelectorAll` to ensure we don't // miss anything. var group = queryRoot.querySelectorAll('input[name=' + JSON.stringify('' + name) + '][type="radio"]'); for (var i = 0; i < group.length; i++) { var otherNode = group[i]; if (otherNode === rootNode || otherNode.form !== rootNode.form) { continue; } // This will throw if radio buttons rendered by different copies of React // and the same name are rendered into the same form (same as #1939). // That's probably okay; we don't support it just as we don't support // mixing React radio buttons with non-React ones. var otherInstance = ReactDOMComponentTree.getInstanceFromNode(otherNode); !otherInstance ? "development" !== 'production' ? invariant(false, 'ReactDOMInput: Mixing React and non-React radio inputs with the same `name` is not supported.') : _prodInvariant('90') : void 0; // If this is a controlled radio button group, forcing the input that // was previously checked to update will cause it to be come re-checked // as appropriate. if (otherInstance._rootNodeID) { ReactDOMInput.updateWrapper(otherInstance); } } } } module.exports = ReactDOMInput; },{"124":124,"13":13,"149":149,"156":156,"157":157,"31":31,"34":34}],40:[function(_dereq_,module,exports){ /** * 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. * */ 'use strict'; var _assign = _dereq_(157); var React = _dereq_(133); var ReactDOMComponentTree = _dereq_(34); var ReactDOMSelect = _dereq_(41); var warning = _dereq_(156); var didWarnInvalidOptionChildren = false; function flattenChildren(children) { var content = ''; // Flatten children and warn if they aren't strings or numbers; // invalid types are ignored. React.Children.forEach(children, function (child) { if (child == null) { return; } if (typeof child === 'string' || typeof child === 'number') { content += child; } else if (!didWarnInvalidOptionChildren) { didWarnInvalidOptionChildren = true; "development" !== 'production' ? warning(false, 'Only strings and numbers are supported as <option> children.') : void 0; } }); return content; } /** * Implements an <option> host component that warns when `selected` is set. */ var ReactDOMOption = { mountWrapper: function (inst, props, hostParent) { // TODO (yungsters): Remove support for `selected` in <option>. if ("development" !== 'production') { "development" !== 'production' ? warning(props.selected == null, 'Use the `defaultValue` or `value` props on <select> instead of ' + 'setting `selected` on <option>.') : void 0; } // Look up whether this option is 'selected' var selectValue = null; if (hostParent != null) { var selectParent = hostParent; if (selectParent._tag === 'optgroup') { selectParent = selectParent._hostParent; } if (selectParent != null && selectParent._tag === 'select') { selectValue = ReactDOMSelect.getSelectValueContext(selectParent); } } // If the value is null (e.g., no specified value or after initial mount) // or missing (e.g., for <datalist>), we don't change props.selected var selected = null; if (selectValue != null) { var value; if (props.value != null) { value = props.value + ''; } else { value = flattenChildren(props.children); } selected = false; if (Array.isArray(selectValue)) { // multiple for (var i = 0; i < selectValue.length; i++) { if ('' + selectValue[i] === value) { selected = true; break; } } } else { selected = '' + selectValue === value; } } inst._wrapperState = { selected: selected }; }, postMountWrapper: function (inst) { // value="" should make a value attribute (#6219) var props = inst._currentElement.props; if (props.value != null) { var node = ReactDOMComponentTree.getNodeFromInstance(inst); node.setAttribute('value', props.value); } }, getHostProps: function (inst, props) { var hostProps = _assign({ selected: undefined, children: undefined }, props); // Read state only from initial mount because <select> updates value // manually; we need the initial state only for server rendering if (inst._wrapperState.selected != null) { hostProps.selected = inst._wrapperState.selected; } var content = flattenChildren(props.children); if (content) { hostProps.children = content; } return hostProps; } }; module.exports = ReactDOMOption; },{"133":133,"156":156,"157":157,"34":34,"41":41}],41:[function(_dereq_,module,exports){ /** * 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. * */ 'use strict'; var _assign = _dereq_(157); var ReactControlledValuePropTypes = _dereq_(31); var ReactDOMComponentTree = _dereq_(34); var warning = _dereq_(156); var didWarnValueDefaultValue = false; function getDeclarationErrorAddendum(owner) { if (owner) { var name = owner.getName(); if (name) { return ' Check the render method of `' + name + '`.'; } } return ''; } var valuePropNames = ['value', 'defaultValue']; /** * Validation function for `value` and `defaultValue`. * @private */ function checkSelectPropTypes(inst, props) { var owner = inst._currentElement._owner; ReactControlledValuePropTypes.checkPropTypes('select', props, owner ? owner.getName() : null); for (var i = 0; i < valuePropNames.length; i++) { var propName = valuePropNames[i]; if (props[propName] == null) { continue; } var isArray = Array.isArray(props[propName]); if (props.multiple && !isArray) { "development" !== 'production' ? warning(false, 'The `%s` prop supplied to <select> must be an array if ' + '`multiple` is true.%s', propName, getDeclarationErrorAddendum(owner)) : void 0; } else if (!props.multiple && isArray) { "development" !== 'production' ? warning(false, 'The `%s` prop supplied to <select> must be a scalar ' + 'value if `multiple` is false.%s', propName, getDeclarationErrorAddendum(owner)) : void 0; } } } /** * @param {ReactDOMComponent} inst * @param {boolean} multiple * @param {*} propValue A stringable (with `multiple`, a list of stringables). * @private */ function updateOptions(inst, multiple, propValue) { var options = ReactDOMComponentTree.getNodeFromInstance(inst).options; if (multiple) { var selectedValue = {}; for (var i = 0; i < propValue.length; i++) { selectedValue['' + propValue[i]] = true; } for (var _i = 0; _i < options.length; _i++) { var selected = selectedValue.hasOwnProperty(options[_i].value); if (options[_i].selected !== selected) { options[_i].selected = selected; } } } else { // Do not set `select.value` as exact behavior isn't consistent across all // browsers for all cases. var _selectedValue = '' + propValue; for (var _i2 = 0; _i2 < options.length; _i2++) { if (options[_i2].value === _selectedValue) { options[_i2].selected = true; return; } } if (options.length) { options[0].selected = true; } } } /** * Implements a <select> host component that allows optionally setting the * props `value` and `defaultValue`. If `multiple` is false, the prop must be a * stringable. If `multiple` is true, the prop must be an array of stringables. * * If `value` is not supplied (or null/undefined), user actions that change the * selected option will trigger updates to the rendered options. * * If it is supplied (and not null/undefined), the rendered options will not * update in response to user actions. Instead, the `value` prop must change in * order for the rendered options to update. * * If `defaultValue` is provided, any options with the supplied values will be * selected. */ var ReactDOMSelect = { getHostProps: function (inst, props) { return _assign({}, props, { value: undefined }); }, mountWrapper: function (inst, props) { if ("development" !== 'production') { checkSelectPropTypes(inst, props); } var value = props.value; inst._wrapperState = { initialValue: value != null ? value : props.defaultValue, listeners: null, wasMultiple: Boolean(props.multiple) }; if (props.value !== undefined && props.defaultValue !== undefined && !didWarnValueDefaultValue) { "development" !== 'production' ? warning(false, 'Select elements must be either controlled or uncontrolled ' + '(specify either the value prop, or the defaultValue prop, but not ' + 'both). Decide between using a controlled or uncontrolled select ' + 'element and remove one of these props. More info: ' + 'https://fb.me/react-controlled-components') : void 0; didWarnValueDefaultValue = true; } }, getSelectValueContext: function (inst) { // ReactDOMOption looks at this initial value so the initial generated // markup has correct `selected` attributes return inst._wrapperState.initialValue; }, postUpdateWrapper: function (inst) { var props = inst._currentElement.props; // After the initial mount, we control selected-ness manually so don't pass // this value down inst._wrapperState.initialValue = undefined; var wasMultiple = inst._wrapperState.wasMultiple; inst._wrapperState.wasMultiple = Boolean(props.multiple); var value = props.value; if (value != null) { updateOptions(inst, Boolean(props.multiple), value); } else if (wasMultiple !== Boolean(props.multiple)) { // For simplicity, reapply `defaultValue` if `multiple` is toggled. if (props.defaultValue != null) { updateOptions(inst, Boolean(props.multiple), props.defaultValue); } else { // Revert the select back to its default unselected state. updateOptions(inst, Boolean(props.multiple), props.multiple ? [] : ''); } } }, restoreControlledState: function (inst) { if (inst._rootNodeID) { var props = inst._currentElement.props; var value = props.value; if (value != null) { updateOptions(inst, Boolean(props.multiple), value); } } } }; module.exports = ReactDOMSelect; },{"156":156,"157":157,"31":31,"34":34}],42:[function(_dereq_,module,exports){ /** * 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. * */ 'use strict'; var ExecutionEnvironment = _dereq_(135); var getNodeForCharacterOffset = _dereq_(116); var getTextContentAccessor = _dereq_(117); /** * While `isCollapsed` is available on the Selection object and `collapsed` * is available on the Range object, IE11 sometimes gets them wrong. * If the anchor/focus nodes and offsets are the same, the range is collapsed. */ function isCollapsed(anchorNode, anchorOffset, focusNode, focusOffset) { return anchorNode === focusNode && anchorOffset === focusOffset; } /** * Get the appropriate anchor and focus node/offset pairs for IE. * * The catch here is that IE's selection API doesn't provide information * about whether the selection is forward or backward, so we have to * behave as though it's always forward. * * IE text differs from modern selection in that it behaves as though * block elements end with a new line. This means character offsets will * differ between the two APIs. * * @param {DOMElement} node * @return {object} */ function getIEOffsets(node) { var selection = document.selection; var selectedRange = selection.createRange(); var selectedLength = selectedRange.text.length; // Duplicate selection so we can move range without breaking user selection. var fromStart = selectedRange.duplicate(); fromStart.moveToElementText(node); fromStart.setEndPoint('EndToStart', selectedRange); var startOffset = fromStart.text.length; var endOffset = startOffset + selectedLength; return { start: startOffset, end: endOffset }; } /** * @param {DOMElement} node * @return {?object} */ function getModernOffsets(node) { var selection = window.getSelection && window.getSelection(); if (!selection || selection.rangeCount === 0) { return null; } var anchorNode = selection.anchorNode; var anchorOffset = selection.anchorOffset; var focusNode = selection.focusNode; var focusOffset = selection.focusOffset; var currentRange = selection.getRangeAt(0); // In Firefox, range.startContainer and range.endContainer can be "anonymous // divs", e.g. the up/down buttons on an <input type="number">. Anonymous // divs do not seem to expose properties, triggering a "Permission denied // error" if any of its properties are accessed. The only seemingly possible // way to avoid erroring is to access a property that typically works for // non-anonymous divs and catch any error that may otherwise arise. See // https://bugzilla.mozilla.org/show_bug.cgi?id=208427 try { /* eslint-disable no-unused-expressions */ currentRange.startContainer.nodeType; currentRange.endContainer.nodeType; /* eslint-enable no-unused-expressions */ } catch (e) { return null; } // If the node and offset values are the same, the selection is collapsed. // `Selection.isCollapsed` is available natively, but IE sometimes gets // this value wrong. var isSelectionCollapsed = isCollapsed(selection.anchorNode, selection.anchorOffset, selection.focusNode, selection.focusOffset); var rangeLength = isSelectionCollapsed ? 0 : currentRange.toString().length; var tempRange = currentRange.cloneRange(); tempRange.selectNodeContents(node); tempRange.setEnd(currentRange.startContainer, currentRange.startOffset); var isTempRangeCollapsed = isCollapsed(tempRange.startContainer, tempRange.startOffset, tempRange.endContainer, tempRange.endOffset); var start = isTempRangeCollapsed ? 0 : tempRange.toString().length; var end = start + rangeLength; // Detect whether the selection is backward. var detectionRange = document.createRange(); detectionRange.setStart(anchorNode, anchorOffset); detectionRange.setEnd(focusNode, focusOffset); var isBackward = detectionRange.collapsed; return { start: isBackward ? end : start, end: isBackward ? start : end }; } /** * @param {DOMElement|DOMTextNode} node * @param {object} offsets */ function setIEOffsets(node, offsets) { var range = document.selection.createRange().duplicate(); var start, end; if (offsets.end === undefined) { start = offsets.start; end = start; } else if (offsets.start > offsets.end) { start = offsets.end; end = offsets.start; } else { start = offsets.start; end = offsets.end; } range.moveToElementText(node); range.moveStart('character', start); range.setEndPoint('EndToStart', range); range.moveEnd('character', end - start); range.select(); } /** * In modern non-IE browsers, we can support both forward and backward * selections. * * Note: IE10+ supports the Selection object, but it does not support * the `extend` method, which means that even in modern IE, it's not possible * to programmatically create a backward selection. Thus, for all IE * versions, we use the old IE API to create our selections. * * @param {DOMElement|DOMTextNode} node * @param {object} offsets */ function setModernOffsets(node, offsets) { if (!window.getSelection) { return; } var selection = window.getSelection(); var length = node[getTextContentAccessor()].length; var start = Math.min(offsets.start, length); var end = offsets.end === undefined ? start : Math.min(offsets.end, length); // IE 11 uses modern selection, but doesn't support the extend method. // Flip backward selections, so we can set with a single range. if (!selection.extend && start > end) { var temp = end; end = start; start = temp; } var startMarker = getNodeForCharacterOffset(node, start); var endMarker = getNodeForCharacterOffset(node, end); if (startMarker && endMarker) { var range = document.createRange(); range.setStart(startMarker.node, startMarker.offset); selection.removeAllRanges(); if (start > end) { selection.addRange(range); selection.extend(endMarker.node, endMarker.offset); } else { range.setEnd(endMarker.node, endMarker.offset); selection.addRange(range); } } } var useIEOffsets = ExecutionEnvironment.canUseDOM && 'selection' in document && !('getSelection' in window); var ReactDOMSelection = { /** * @param {DOMElement} node */ getOffsets: useIEOffsets ? getIEOffsets : getModernOffsets, /** * @param {DOMElement|DOMTextNode} node * @param {object} offsets */ setOffsets: useIEOffsets ? setIEOffsets : setModernOffsets }; module.exports = ReactDOMSelection; },{"116":116,"117":117,"135":135}],43:[function(_dereq_,module,exports){ /** * 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. * */ 'use strict'; var ReactDOMInjection = _dereq_(38); var ReactDOMStackInjection = _dereq_(45); var ReactServerRendering = _dereq_(73); var ReactVersion = _dereq_(80); ReactDOMInjection.inject(); ReactDOMStackInjection.inject(); var ReactDOMServer = { renderToString: ReactServerRendering.renderToString, renderToStaticMarkup: ReactServerRendering.renderToStaticMarkup, version: ReactVersion }; module.exports = ReactDOMServer; },{"38":38,"45":45,"73":73,"80":80}],44:[function(_dereq_,module,exports){ /** * 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. * */ 'use strict'; var ReactDOMServer = _dereq_(43); module.exports = ReactDOMServer; },{"43":43}],45:[function(_dereq_,module,exports){ /** * 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. * */ 'use strict'; var ReactComponentEnvironment = _dereq_(27); var ReactComponentBrowserEnvironment = _dereq_(26); var ReactDOMComponent = _dereq_(32); var ReactDOMComponentTree = _dereq_(34); var ReactDOMEmptyComponent = _dereq_(36); var ReactDOMTextComponent = _dereq_(46); var ReactDefaultBatchingStrategy = _dereq_(50); var ReactEmptyComponent = _dereq_(52); var ReactGenericBatching = _dereq_(57); var ReactHostComponent = _dereq_(58); var ReactReconcileTransaction = _dereq_(69); var ReactUpdates = _dereq_(79); var findDOMNode = _dereq_(105); var getHostComponentFromComposite = _dereq_(113); var alreadyInjected = false; function inject() { if (alreadyInjected) { // TODO: This is currently true because these injections are shared between // the client and the server package. They should be built independently // and not share any injection state. Then this problem will be solved. return; } alreadyInjected = true; ReactGenericBatching.injection.injectStackBatchedUpdates(ReactUpdates.batchedUpdates); ReactHostComponent.injection.injectGenericComponentClass(ReactDOMComponent); ReactHostComponent.injection.injectTextComponentClass(ReactDOMTextComponent); ReactEmptyComponent.injection.injectEmptyComponentFactory(function (instantiate) { return new ReactDOMEmptyComponent(instantiate); }); ReactUpdates.injection.injectReconcileTransaction(ReactReconcileTransaction); ReactUpdates.injection.injectBatchingStrategy(ReactDefaultBatchingStrategy); ReactComponentEnvironment.injection.injectEnvironment(ReactComponentBrowserEnvironment); findDOMNode._injectStack(function (inst) { inst = getHostComponentFromComposite(inst); return inst ? ReactDOMComponentTree.getNodeFromInstance(inst) : null; }); } module.exports = { inject: inject }; },{"105":105,"113":113,"26":26,"27":27,"32":32,"34":34,"36":36,"46":46,"50":50,"52":52,"57":57,"58":58,"69":69,"79":79}],46:[function(_dereq_,module,exports){ /** * 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. * */ 'use strict'; var _prodInvariant = _dereq_(124), _assign = _dereq_(157); var DOMChildrenOperations = _dereq_(8); var DOMLazyTree = _dereq_(10); var ReactDOMComponentTree = _dereq_(34); var escapeTextContentForBrowser = _dereq_(104); var invariant = _dereq_(149); var validateDOMNesting = _dereq_(130); /** * Text nodes violate a couple assumptions that React makes about components: * * - When mounting text into the DOM, adjacent text nodes are merged. * - Text nodes cannot be assigned a React root ID. * * This component is used to wrap strings between comment nodes so that they * can undergo the same reconciliation that is applied to elements. * * TODO: Investigate representing React components in the DOM with text nodes. * * @class ReactDOMTextComponent * @extends ReactComponent * @internal */ var ReactDOMTextComponent = function (text) { // TODO: This is really a ReactText (ReactNode), not a ReactElement this._currentElement = text; this._stringText = '' + text; // ReactDOMComponentTree uses these: this._hostNode = null; this._hostParent = null; // Properties this._domID = 0; this._mountIndex = 0; this._closingComment = null; this._commentNodes = null; }; _assign(ReactDOMTextComponent.prototype, { /** * Creates the markup for this text node. This node is not intended to have * any features besides containing text content. * * @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction * @return {string} Markup for this text node. * @internal */ mountComponent: function (transaction, hostParent, hostContainerInfo, context) { if ("development" !== 'production') { var parentInfo; if (hostParent != null) { parentInfo = hostParent._ancestorInfo; } else if (hostContainerInfo != null) { parentInfo = hostContainerInfo._ancestorInfo; } if (parentInfo) { // parentInfo should always be present except for the top-level // component when server rendering validateDOMNesting(null, this._stringText, this, parentInfo); } } var domID = hostContainerInfo._idCounter++; var openingValue = ' react-text: ' + domID + ' '; var closingValue = ' /react-text '; this._domID = domID; this._hostParent = hostParent; if (transaction.useCreateElement) { var ownerDocument = hostContainerInfo._ownerDocument; var openingComment = ownerDocument.createComment(openingValue); var closingComment = ownerDocument.createComment(closingValue); var lazyTree = DOMLazyTree(ownerDocument.createDocumentFragment()); DOMLazyTree.queueChild(lazyTree, DOMLazyTree(openingComment)); if (this._stringText) { DOMLazyTree.queueChild(lazyTree, DOMLazyTree(ownerDocument.createTextNode(this._stringText))); } DOMLazyTree.queueChild(lazyTree, DOMLazyTree(closingComment)); ReactDOMComponentTree.precacheNode(this, openingComment); this._closingComment = closingComment; return lazyTree; } else { var escapedText = escapeTextContentForBrowser(this._stringText); if (transaction.renderToStaticMarkup) { // Normally we'd wrap this between comment nodes for the reasons stated // above, but since this is a situation where React won't take over // (static pages), we can simply return the text as it is. return escapedText; } return '<!--' + openingValue + '-->' + escapedText + '<!--' + closingValue + '-->'; } }, /** * Updates this component by updating the text content. * * @param {ReactText} nextText The next text content * @param {ReactReconcileTransaction} transaction * @internal */ receiveComponent: function (nextText, transaction) { if (nextText !== this._currentElement) { this._currentElement = nextText; var nextStringText = '' + nextText; if (nextStringText !== this._stringText) { // TODO: Save this as pending props and use performUpdateIfNecessary // and/or updateComponent to do the actual update for consistency with // other component types? this._stringText = nextStringText; var commentNodes = this.getHostNode(); DOMChildrenOperations.replaceDelimitedText(commentNodes[0], commentNodes[1], nextStringText); } } }, getHostNode: function () { var hostNode = this._commentNodes; if (hostNode) { return hostNode; } if (!this._closingComment) { var openingComment = ReactDOMComponentTree.getNodeFromInstance(this); var node = openingComment.nextSibling; while (true) { !(node != null) ? "development" !== 'production' ? invariant(false, 'Missing closing comment for text component %s', this._domID) : _prodInvariant('67', this._domID) : void 0; if (node.nodeType === 8 && node.nodeValue === ' /react-text ') { this._closingComment = node; break; } node = node.nextSibling; } } hostNode = [this._hostNode, this._closingComment]; this._commentNodes = hostNode; return hostNode; }, unmountComponent: function () { this._closingComment = null; this._commentNodes = null; ReactDOMComponentTree.uncacheNode(this); } }); module.exports = ReactDOMTextComponent; },{"10":10,"104":104,"124":124,"130":130,"149":149,"157":157,"34":34,"8":8}],47:[function(_dereq_,module,exports){ /** * 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. * */ 'use strict'; var _prodInvariant = _dereq_(124), _assign = _dereq_(157); var ReactControlledValuePropTypes = _dereq_(31); var ReactDOMComponentTree = _dereq_(34); var invariant = _dereq_(149); var warning = _dereq_(156); var didWarnValDefaultVal = false; /** * Implements a <textarea> host component that allows setting `value`, and * `defaultValue`. This differs from the traditional DOM API because value is * usually set as PCDATA children. * * If `value` is not supplied (or null/undefined), user actions that affect the * value will trigger updates to the element. * * If `value` is supplied (and not null/undefined), the rendered element will * not trigger updates to the element. Instead, the `value` prop must change in * order for the rendered element to be updated. * * The rendered element will be initialized with an empty value, the prop * `defaultValue` if specified, or the children content (deprecated). */ var ReactDOMTextarea = { getHostProps: function (inst, props) { !(props.dangerouslySetInnerHTML == null) ? "development" !== 'production' ? invariant(false, '`dangerouslySetInnerHTML` does not make sense on <textarea>.') : _prodInvariant('91') : void 0; // Always set children to the same thing. In IE9, the selection range will // get reset if `textContent` is mutated. We could add a check in setTextContent // to only set the value if/when the value differs from the node value (which would // completely solve this IE9 bug), but Sebastian+Ben seemed to like this solution. // The value can be a boolean or object so that's why it's forced to be a string. var hostProps = _assign({}, props, { value: undefined, defaultValue: undefined, children: '' + inst._wrapperState.initialValue }); return hostProps; }, mountWrapper: function (inst, props) { if ("development" !== 'production') { var owner = inst._currentElement._owner; ReactControlledValuePropTypes.checkPropTypes('textarea', props, owner ? owner.getName() : null); if (props.value !== undefined && props.defaultValue !== undefined && !didWarnValDefaultVal) { "development" !== 'production' ? warning(false, 'Textarea elements must be either controlled or uncontrolled ' + '(specify either the value prop, or the defaultValue prop, but not ' + 'both). Decide between using a controlled or uncontrolled textarea ' + 'and remove one of these props. More info: ' + 'https://fb.me/react-controlled-components') : void 0; didWarnValDefaultVal = true; } } var value = props.value; var initialValue = value; // Only bother fetching default value if we're going to use it if (value == null) { var defaultValue = props.defaultValue; // TODO (yungsters): Remove support for children content in <textarea>. var children = props.children; if (children != null) { if ("development" !== 'production') { "development" !== 'production' ? warning(false, 'Use the `defaultValue` or `value` props instead of setting ' + 'children on <textarea>.') : void 0; } !(defaultValue == null) ? "development" !== 'production' ? invariant(false, 'If you supply `defaultValue` on a <textarea>, do not pass children.') : _prodInvariant('92') : void 0; if (Array.isArray(children)) { !(children.length <= 1) ? "development" !== 'production' ? invariant(false, '<textarea> can only have at most one child.') : _prodInvariant('93') : void 0; children = children[0]; } defaultValue = '' + children; } if (defaultValue == null) { defaultValue = ''; } initialValue = defaultValue; } inst._wrapperState = { initialValue: '' + initialValue, listeners: null }; }, updateWrapper: function (inst) { var props = inst._currentElement.props; var node = ReactDOMComponentTree.getNodeFromInstance(inst); var value = props.value; if (value != null) { // Cast `value` to a string to ensure the value is set correctly. While // browsers typically do this as necessary, jsdom doesn't. var newValue = '' + value; // To avoid side effects (such as losing text selection), only set value if changed if (newValue !== node.value) { node.value = newValue; } if (props.defaultValue == null) { node.defaultValue = newValue; } } if (props.defaultValue != null) { node.defaultValue = props.defaultValue; } }, postMountWrapper: function (inst) { // This is in postMount because we need access to the DOM node, which is not // available until after the component has mounted. var node = ReactDOMComponentTree.getNodeFromInstance(inst); var textContent = node.textContent; // Only set node.value if textContent is equal to the expected // initial value. In IE10/IE11 there is a bug where the placeholder attribute // will populate textContent as well. // https://developer.microsoft.com/microsoft-edge/platform/issues/101525/ if (textContent === inst._wrapperState.initialValue) { node.value = textContent; } }, restoreControlledState: function (inst) { if (inst._rootNodeID) { // DOM component is still mounted; update ReactDOMTextarea.updateWrapper(inst); } } }; module.exports = ReactDOMTextarea; },{"124":124,"149":149,"156":156,"157":157,"31":31,"34":34}],48:[function(_dereq_,module,exports){ /** * 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. * * */ 'use strict'; if ("development" !== 'production') { var getComponentName = _dereq_(108); var _require = _dereq_(131), getStackAddendumByWorkInProgressFiber = _require.getStackAddendumByWorkInProgressFiber; } function getCurrentFiberOwnerName() { if ("development" !== 'production') { var fiber = ReactDebugCurrentFiber.current; if (fiber == null) { return null; } if (fiber._debugOwner != null) { return getComponentName(fiber._debugOwner); } } return null; } function getCurrentFiberStackAddendum() { if ("development" !== 'production') { var fiber = ReactDebugCurrentFiber.current; if (fiber == null) { return null; } // Safe because if current fiber exists, we are reconciling, // and it is guaranteed to be the work-in-progress version. return getStackAddendumByWorkInProgressFiber(fiber); } return null; } var ReactDebugCurrentFiber = { current: null, getCurrentFiberOwnerName: getCurrentFiberOwnerName, getCurrentFiberStackAddendum: getCurrentFiberStackAddendum }; module.exports = ReactDebugCurrentFiber; },{"108":108,"131":131}],49:[function(_dereq_,module,exports){ /** * Copyright 2016-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'; var ReactInvalidSetStateWarningHook = _dereq_(63); var ReactHostOperationHistoryHook = _dereq_(59); var ReactComponentTreeHook = _dereq_(131); var ExecutionEnvironment = _dereq_(135); var performanceNow = _dereq_(154); var warning = _dereq_(156); // Trust the developer to only use this with a __DEV__ check var ReactDebugTool = null; if ("development" !== 'production') { var hooks; var didHookThrowForEvent; var isProfiling; var flushHistory; var lifeCycleTimerStack; var currentFlushNesting; var currentFlushMeasurements; var currentFlushStartTime; var currentTimerDebugID; var currentTimerStartTime; var currentTimerNestedFlushDuration; var currentTimerType; var lifeCycleTimerHasWarned; var lastMarkTimeStamp; var canUsePerformanceMeasure; var url; (function () { hooks = []; didHookThrowForEvent = {}; var callHook = function (event, fn, context, arg1, arg2, arg3, arg4, arg5) { try { fn.call(context, arg1, arg2, arg3, arg4, arg5); } catch (e) { "development" !== 'production' ? warning(didHookThrowForEvent[event], 'Exception thrown by hook while handling %s: %s', event, e + '\n' + e.stack) : void 0; didHookThrowForEvent[event] = true; } }; var emitEvent = function (event, arg1, arg2, arg3, arg4, arg5) { for (var i = 0; i < hooks.length; i++) { var hook = hooks[i]; var fn = hook[event]; if (fn) { callHook(event, fn, hook, arg1, arg2, arg3, arg4, arg5); } } }; isProfiling = false; flushHistory = []; lifeCycleTimerStack = []; currentFlushNesting = 0; currentFlushMeasurements = []; currentFlushStartTime = 0; currentTimerDebugID = null; currentTimerStartTime = 0; currentTimerNestedFlushDuration = 0; currentTimerType = null; lifeCycleTimerHasWarned = false; var clearHistory = function () { ReactComponentTreeHook.purgeUnmountedComponents(); ReactHostOperationHistoryHook.clearHistory(); }; var getTreeSnapshot = function (registeredIDs) { return registeredIDs.reduce(function (tree, id) { var ownerID = ReactComponentTreeHook.getOwnerID(id); var parentID = ReactComponentTreeHook.getParentID(id); tree[id] = { displayName: ReactComponentTreeHook.getDisplayName(id), text: ReactComponentTreeHook.getText(id), updateCount: ReactComponentTreeHook.getUpdateCount(id), childIDs: ReactComponentTreeHook.getChildIDs(id), // Text nodes don't have owners but this is close enough. ownerID: ownerID || parentID && ReactComponentTreeHook.getOwnerID(parentID) || 0, parentID: parentID }; return tree; }, {}); }; var resetMeasurements = function () { var previousStartTime = currentFlushStartTime; var previousMeasurements = currentFlushMeasurements; var previousOperations = ReactHostOperationHistoryHook.getHistory(); if (currentFlushNesting === 0) { currentFlushStartTime = 0; currentFlushMeasurements = []; clearHistory(); return; } if (previousMeasurements.length || previousOperations.length) { var registeredIDs = ReactComponentTreeHook.getRegisteredIDs(); flushHistory.push({ duration: performanceNow() - previousStartTime, measurements: previousMeasurements || [], operations: previousOperations || [], treeSnapshot: getTreeSnapshot(registeredIDs) }); } clearHistory(); currentFlushStartTime = performanceNow(); currentFlushMeasurements = []; }; var checkDebugID = function (debugID) { var allowRoot = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; if (allowRoot && debugID === 0) { return; } if (!debugID) { "development" !== 'production' ? warning(false, 'ReactDebugTool: debugID may not be empty.') : void 0; } }; var beginLifeCycleTimer = function (debugID, timerType) { if (currentFlushNesting === 0) { return; } if (currentTimerType && !lifeCycleTimerHasWarned) { "development" !== 'production' ? warning(false, 'There is an internal error in the React performance measurement code. ' + 'Did not expect %s timer to start while %s timer is still in ' + 'progress for %s instance.', timerType, currentTimerType || 'no', debugID === currentTimerDebugID ? 'the same' : 'another') : void 0; lifeCycleTimerHasWarned = true; } currentTimerStartTime = performanceNow(); currentTimerNestedFlushDuration = 0; currentTimerDebugID = debugID; currentTimerType = timerType; }; var endLifeCycleTimer = function (debugID, timerType) { if (currentFlushNesting === 0) { return; } if (currentTimerType !== timerType && !lifeCycleTimerHasWarned) { "development" !== 'production' ? warning(false, 'There is an internal error in the React performance measurement code. ' + 'We did not expect %s timer to stop while %s timer is still in ' + 'progress for %s instance. Please report this as a bug in React.', timerType, currentTimerType || 'no', debugID === currentTimerDebugID ? 'the same' : 'another') : void 0; lifeCycleTimerHasWarned = true; } if (isProfiling) { currentFlushMeasurements.push({ timerType: timerType, instanceID: debugID, duration: performanceNow() - currentTimerStartTime - currentTimerNestedFlushDuration }); } currentTimerStartTime = 0; currentTimerNestedFlushDuration = 0; currentTimerDebugID = null; currentTimerType = null; }; var pauseCurrentLifeCycleTimer = function () { var currentTimer = { startTime: currentTimerStartTime, nestedFlushStartTime: performanceNow(), debugID: currentTimerDebugID, timerType: currentTimerType }; lifeCycleTimerStack.push(currentTimer); currentTimerStartTime = 0; currentTimerNestedFlushDuration = 0; currentTimerDebugID = null; currentTimerType = null; }; var resumeCurrentLifeCycleTimer = function () { var _lifeCycleTimerStack$ = lifeCycleTimerStack.pop(), startTime = _lifeCycleTimerStack$.startTime, nestedFlushStartTime = _lifeCycleTimerStack$.nestedFlushStartTime, debugID = _lifeCycleTimerStack$.debugID, timerType = _lifeCycleTimerStack$.timerType; var nestedFlushDuration = performanceNow() - nestedFlushStartTime; currentTimerStartTime = startTime; currentTimerNestedFlushDuration += nestedFlushDuration; currentTimerDebugID = debugID; currentTimerType = timerType; }; lastMarkTimeStamp = 0; canUsePerformanceMeasure = typeof performance !== 'undefined' && typeof performance.mark === 'function' && typeof performance.clearMarks === 'function' && typeof performance.measure === 'function' && typeof performance.clearMeasures === 'function'; var shouldMark = function (debugID) { if (!isProfiling || !canUsePerformanceMeasure) { return false; } var element = ReactComponentTreeHook.getElement(debugID); if (element == null || typeof element !== 'object') { return false; } var isHostElement = typeof element.type === 'string'; if (isHostElement) { return false; } return true; }; var markBegin = function (debugID, markType) { if (!shouldMark(debugID)) { return; } var markName = debugID + '::' + markType; lastMarkTimeStamp = performanceNow(); performance.mark(markName); }; var markEnd = function (debugID, markType) { if (!shouldMark(debugID)) { return; } var markName = debugID + '::' + markType; var displayName = ReactComponentTreeHook.getDisplayName(debugID) || 'Unknown'; // Chrome has an issue of dropping markers recorded too fast: // https://bugs.chromium.org/p/chromium/issues/detail?id=640652 // To work around this, we will not report very small measurements. // I determined the magic number by tweaking it back and forth. // 0.05ms was enough to prevent the issue, but I set it to 0.1ms to be safe. // When the bug is fixed, we can `measure()` unconditionally if we want to. var timeStamp = performanceNow(); if (timeStamp - lastMarkTimeStamp > 0.1) { var measurementName = displayName + ' [' + markType + ']'; performance.measure(measurementName, markName); } performance.clearMarks(markName); performance.clearMeasures(measurementName); }; ReactDebugTool = { addHook: function (hook) { hooks.push(hook); }, removeHook: function (hook) { for (var i = 0; i < hooks.length; i++) { if (hooks[i] === hook) { hooks.splice(i, 1); i--; } } }, isProfiling: function () { return isProfiling; }, beginProfiling: function () { if (isProfiling) { return; } isProfiling = true; flushHistory.length = 0; resetMeasurements(); ReactDebugTool.addHook(ReactHostOperationHistoryHook); }, endProfiling: function () { if (!isProfiling) { return; } isProfiling = false; resetMeasurements(); ReactDebugTool.removeHook(ReactHostOperationHistoryHook); }, getFlushHistory: function () { return flushHistory; }, onBeginFlush: function () { currentFlushNesting++; resetMeasurements(); pauseCurrentLifeCycleTimer(); emitEvent('onBeginFlush'); }, onEndFlush: function () { resetMeasurements(); currentFlushNesting--; resumeCurrentLifeCycleTimer(); emitEvent('onEndFlush'); }, onBeginLifeCycleTimer: function (debugID, timerType) { checkDebugID(debugID); emitEvent('onBeginLifeCycleTimer', debugID, timerType); markBegin(debugID, timerType); beginLifeCycleTimer(debugID, timerType); }, onEndLifeCycleTimer: function (debugID, timerType) { checkDebugID(debugID); endLifeCycleTimer(debugID, timerType); markEnd(debugID, timerType); emitEvent('onEndLifeCycleTimer', debugID, timerType); }, onBeginProcessingChildContext: function () { emitEvent('onBeginProcessingChildContext'); }, onEndProcessingChildContext: function () { emitEvent('onEndProcessingChildContext'); }, onHostOperation: function (operation) { checkDebugID(operation.instanceID); emitEvent('onHostOperation', operation); }, onSetState: function () { emitEvent('onSetState'); }, onSetChildren: function (debugID, childDebugIDs) { checkDebugID(debugID); childDebugIDs.forEach(checkDebugID); emitEvent('onSetChildren', debugID, childDebugIDs); }, onBeforeMountComponent: function (debugID, element, parentDebugID) { checkDebugID(debugID); checkDebugID(parentDebugID, true); emitEvent('onBeforeMountComponent', debugID, element, parentDebugID); markBegin(debugID, 'mount'); }, onMountComponent: function (debugID) { checkDebugID(debugID); markEnd(debugID, 'mount'); emitEvent('onMountComponent', debugID); }, onBeforeUpdateComponent: function (debugID, element) { checkDebugID(debugID); emitEvent('onBeforeUpdateComponent', debugID, element); markBegin(debugID, 'update'); }, onUpdateComponent: function (debugID) { checkDebugID(debugID); markEnd(debugID, 'update'); emitEvent('onUpdateComponent', debugID); }, onBeforeUnmountComponent: function (debugID) { checkDebugID(debugID); emitEvent('onBeforeUnmountComponent', debugID); markBegin(debugID, 'unmount'); }, onUnmountComponent: function (debugID) { checkDebugID(debugID); markEnd(debugID, 'unmount'); emitEvent('onUnmountComponent', debugID); }, onTestEvent: function () { emitEvent('onTestEvent'); } }; ReactDebugTool.addHook(ReactInvalidSetStateWarningHook); ReactDebugTool.addHook(ReactComponentTreeHook); url = ExecutionEnvironment.canUseDOM && window.location.href || ''; if (/[?&]react_perf\b/.test(url)) { ReactDebugTool.beginProfiling(); } })(); } module.exports = ReactDebugTool; },{"131":131,"135":135,"154":154,"156":156,"59":59,"63":63}],50:[function(_dereq_,module,exports){ /** * 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. * */ 'use strict'; var _assign = _dereq_(157); var ReactUpdates = _dereq_(79); var Transaction = _dereq_(97); var emptyFunction = _dereq_(141); var RESET_BATCHED_UPDATES = { initialize: emptyFunction, close: function () { ReactDefaultBatchingStrategy.isBatchingUpdates = false; } }; var FLUSH_BATCHED_UPDATES = { initialize: emptyFunction, close: ReactUpdates.flushBatchedUpdates.bind(ReactUpdates) }; var TRANSACTION_WRAPPERS = [FLUSH_BATCHED_UPDATES, RESET_BATCHED_UPDATES]; function ReactDefaultBatchingStrategyTransaction() { this.reinitializeTransaction(); } _assign(ReactDefaultBatchingStrategyTransaction.prototype, Transaction, { getTransactionWrappers: function () { return TRANSACTION_WRAPPERS; } }); var transaction = new ReactDefaultBatchingStrategyTransaction(); var ReactDefaultBatchingStrategy = { isBatchingUpdates: false, /** * Call the provided function in a context within which calls to `setState` * and friends are batched such that components aren't updated unnecessarily. */ batchedUpdates: function (callback, a, b, c, d, e) { var alreadyBatchingUpdates = ReactDefaultBatchingStrategy.isBatchingUpdates; ReactDefaultBatchingStrategy.isBatchingUpdates = true; // The code is written this way to avoid extra allocations if (alreadyBatchingUpdates) { return callback(a, b, c, d, e); } else { return transaction.perform(callback, null, a, b, c, d, e); } } }; module.exports = ReactDefaultBatchingStrategy; },{"141":141,"157":157,"79":79,"97":97}],51:[function(_dereq_,module,exports){ /** * Copyright 2014-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'; // The Symbol used to tag the ReactElement type. If there is no native Symbol // nor polyfill, then a plain number is used for performance. var REACT_ELEMENT_TYPE = typeof Symbol === 'function' && Symbol['for'] && Symbol['for']('react.element') || 0xeac7; module.exports = REACT_ELEMENT_TYPE; },{}],52:[function(_dereq_,module,exports){ /** * Copyright 2014-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'; var emptyComponentFactory; var ReactEmptyComponentInjection = { injectEmptyComponentFactory: function (factory) { emptyComponentFactory = factory; } }; var ReactEmptyComponent = { create: function (instantiate) { return emptyComponentFactory(instantiate); } }; ReactEmptyComponent.injection = ReactEmptyComponentInjection; module.exports = ReactEmptyComponent; },{}],53:[function(_dereq_,module,exports){ /** * 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. * * */ 'use strict'; var caughtError = null; /** * Call a function while guarding against errors that happens within it. * * @param {String} name of the guard to use for logging or debugging * @param {Function} func The function to invoke * @param {*} a Argument */ function invokeGuardedCallback(name, func, a) { try { func(a); } catch (x) { if (caughtError === null) { caughtError = x; } } } var ReactErrorUtils = { invokeGuardedCallback: invokeGuardedCallback, /** * Invoked by ReactTestUtils.Simulate so that any errors thrown by the event * handler are sure to be rethrown by rethrowCaughtError. */ invokeGuardedCallbackWithCatch: invokeGuardedCallback, /** * During execution of guarded functions we will capture the first error which * we will rethrow to be handled by the top level error handler. */ rethrowCaughtError: function () { if (caughtError) { var error = caughtError; caughtError = null; throw error; } } }; if ("development" !== 'production') { /** * To help development we can get better devtools integration by simulating a * real browser event. */ if (typeof window !== 'undefined' && typeof window.dispatchEvent === 'function' && typeof document !== 'undefined' && typeof document.createEvent === 'function') { var fakeNode = document.createElement('react'); ReactErrorUtils.invokeGuardedCallback = function (name, func, a) { var boundFunc = function () { func(a); }; var evtType = 'react-' + name; fakeNode.addEventListener(evtType, boundFunc, false); var evt = document.createEvent('Event'); evt.initEvent(evtType, false, false); fakeNode.dispatchEvent(evt); fakeNode.removeEventListener(evtType, boundFunc, false); }; } } module.exports = ReactErrorUtils; },{}],54:[function(_dereq_,module,exports){ /** * 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. * */ 'use strict'; var EventPluginHub = _dereq_(16); function runEventQueueInBatch(events) { EventPluginHub.enqueueEvents(events); EventPluginHub.processEventQueue(false); } var ReactEventEmitterMixin = { /** * Streams a fired top-level event to `EventPluginHub` where plugins have the * opportunity to create `ReactEvent`s to be dispatched. */ handleTopLevel: function (topLevelType, targetInst, nativeEvent, nativeEventTarget) { var events = EventPluginHub.extractEvents(topLevelType, targetInst, nativeEvent, nativeEventTarget); runEventQueueInBatch(events); } }; module.exports = ReactEventEmitterMixin; },{"16":16}],55:[function(_dereq_,module,exports){ /** * 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. * */ 'use strict'; var _assign = _dereq_(157); var EventListener = _dereq_(134); var ExecutionEnvironment = _dereq_(135); var PooledClass = _dereq_(23); var ReactDOMComponentTree = _dereq_(34); var ReactGenericBatching = _dereq_(57); var ReactTypeOfWork = _dereq_(77); var getEventTarget = _dereq_(112); var getUnboundedScrollPosition = _dereq_(146); var HostRoot = ReactTypeOfWork.HostRoot; /** * Find the deepest React component completely containing the root of the * passed-in instance (for use when entire React trees are nested within each * other). If React trees are not nested, returns null. */ function findRootContainerNode(inst) { // TODO: It may be a good idea to cache this to prevent unnecessary DOM // traversal, but caching is difficult to do correctly without using a // mutation observer to listen for all DOM changes. if (typeof inst.tag === 'number') { while (inst['return']) { inst = inst['return']; } if (inst.tag !== HostRoot) { // This can happen if we're in a detached tree. return null; } return inst.stateNode.containerInfo; } else { while (inst._hostParent) { inst = inst._hostParent; } var rootNode = ReactDOMComponentTree.getNodeFromInstance(inst); return rootNode.parentNode; } } // Used to store ancestor hierarchy in top level callback function TopLevelCallbackBookKeeping(topLevelType, nativeEvent, targetInst) { this.topLevelType = topLevelType; this.nativeEvent = nativeEvent; this.targetInst = targetInst; this.ancestors = []; } _assign(TopLevelCallbackBookKeeping.prototype, { destructor: function () { this.topLevelType = null; this.nativeEvent = null; this.targetInst = null; this.ancestors.length = 0; } }); PooledClass.addPoolingTo(TopLevelCallbackBookKeeping, PooledClass.threeArgumentPooler); function handleTopLevelImpl(bookKeeping) { var targetInst = bookKeeping.targetInst; // Loop through the hierarchy, in case there's any nested components. // It's important that we build the array of ancestors before calling any // event handlers, because event handlers can modify the DOM, leading to // inconsistencies with ReactMount's node cache. See #1105. var ancestor = targetInst; do { if (!ancestor) { bookKeeping.ancestors.push(ancestor); break; } var root = findRootContainerNode(ancestor); if (!root) { break; } bookKeeping.ancestors.push(ancestor); ancestor = ReactDOMComponentTree.getClosestInstanceFromNode(root); } while (ancestor); for (var i = 0; i < bookKeeping.ancestors.length; i++) { targetInst = bookKeeping.ancestors[i]; ReactEventListener._handleTopLevel(bookKeeping.topLevelType, targetInst, bookKeeping.nativeEvent, getEventTarget(bookKeeping.nativeEvent)); } } function scrollValueMonitor(cb) { var scrollPosition = getUnboundedScrollPosition(window); cb(scrollPosition); } var ReactEventListener = { _enabled: true, _handleTopLevel: null, WINDOW_HANDLE: ExecutionEnvironment.canUseDOM ? window : null, setHandleTopLevel: function (handleTopLevel) { ReactEventListener._handleTopLevel = handleTopLevel; }, setEnabled: function (enabled) { ReactEventListener._enabled = !!enabled; }, isEnabled: function () { return ReactEventListener._enabled; }, /** * Traps top-level events by using event bubbling. * * @param {string} topLevelType Record from `EventConstants`. * @param {string} handlerBaseName Event name (e.g. "click"). * @param {object} element Element on which to attach listener. * @return {?object} An object with a remove function which will forcefully * remove the listener. * @internal */ trapBubbledEvent: function (topLevelType, handlerBaseName, element) { if (!element) { return null; } return EventListener.listen(element, handlerBaseName, ReactEventListener.dispatchEvent.bind(null, topLevelType)); }, /** * Traps a top-level event by using event capturing. * * @param {string} topLevelType Record from `EventConstants`. * @param {string} handlerBaseName Event name (e.g. "click"). * @param {object} element Element on which to attach listener. * @return {?object} An object with a remove function which will forcefully * remove the listener. * @internal */ trapCapturedEvent: function (topLevelType, handlerBaseName, element) { if (!element) { return null; } return EventListener.capture(element, handlerBaseName, ReactEventListener.dispatchEvent.bind(null, topLevelType)); }, monitorScrollValue: function (refresh) { var callback = scrollValueMonitor.bind(null, refresh); EventListener.listen(window, 'scroll', callback); }, dispatchEvent: function (topLevelType, nativeEvent) { if (!ReactEventListener._enabled) { return; } var nativeEventTarget = getEventTarget(nativeEvent); var targetInst = ReactDOMComponentTree.getClosestInstanceFromNode(nativeEventTarget); var bookKeeping = TopLevelCallbackBookKeeping.getPooled(topLevelType, nativeEvent, targetInst); try { // Event queue being processed in the same cycle allows // `preventDefault`. ReactGenericBatching.batchedUpdates(handleTopLevelImpl, bookKeeping); } finally { TopLevelCallbackBookKeeping.release(bookKeeping); } } }; module.exports = ReactEventListener; },{"112":112,"134":134,"135":135,"146":146,"157":157,"23":23,"34":34,"57":57,"77":77}],56:[function(_dereq_,module,exports){ /** * 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. * * */ 'use strict'; var ReactFeatureFlags = { // When true, call console.time() before and .timeEnd() after each top-level // render (both initial renders and updates). Useful when looking at prod-mode // timeline profiles in Chrome, for example. logTopLevelRenders: false, prepareNewChildrenBeforeUnmountInStack: true }; module.exports = ReactFeatureFlags; },{}],57:[function(_dereq_,module,exports){ /** * 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. * */ 'use strict'; var ReactControlledComponent = _dereq_(30); // Used as a way to call batchedUpdates when we don't know if we're in a Fiber // or Stack context. Such as when we're dispatching events or if third party // libraries need to call batchedUpdates. Eventually, this API will go away when // everything is batched by default. We'll then have a similar API to opt-out of // scheduled work and instead do synchronous work. // Defaults var stackBatchedUpdates = function (fn, a, b, c, d, e) { return fn(a, b, c, d, e); }; var fiberBatchedUpdates = function (fn, bookkeeping) { return fn(bookkeeping); }; function performFiberBatchedUpdates(fn, bookkeeping) { // If we have Fiber loaded, we need to wrap this in a batching call so that // Fiber can apply its default priority for this call. return fiberBatchedUpdates(fn, bookkeeping); } function batchedUpdates(fn, bookkeeping) { // We first perform work with the stack batching strategy, by passing our // indirection to it. return stackBatchedUpdates(performFiberBatchedUpdates, fn, bookkeeping); } var isNestingBatched = false; function batchedUpdatesWithControlledComponents(fn, bookkeeping) { if (isNestingBatched) { // If we are currently inside another batch, we need to wait until it // fully completes before restoring state. Therefore, we add the target to // a queue of work. return batchedUpdates(fn, bookkeeping); } isNestingBatched = true; try { return batchedUpdates(fn, bookkeeping); } finally { // Here we wait until all updates have propagated, which is important // when using controlled components within layers: // https://github.com/facebook/react/issues/1698 // Then we restore state of any controlled component. isNestingBatched = false; ReactControlledComponent.restoreStateIfNeeded(); } } var ReactGenericBatchingInjection = { injectStackBatchedUpdates: function (_batchedUpdates) { stackBatchedUpdates = _batchedUpdates; }, injectFiberBatchedUpdates: function (_batchedUpdates) { fiberBatchedUpdates = _batchedUpdates; } }; var ReactGenericBatching = { batchedUpdates: batchedUpdatesWithControlledComponents, injection: ReactGenericBatchingInjection }; module.exports = ReactGenericBatching; },{"30":30}],58:[function(_dereq_,module,exports){ /** * Copyright 2014-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'; var _prodInvariant = _dereq_(124); var invariant = _dereq_(149); var genericComponentClass = null; var textComponentClass = null; var ReactHostComponentInjection = { // This accepts a class that receives the tag string. This is a catch all // that can render any kind of tag. injectGenericComponentClass: function (componentClass) { genericComponentClass = componentClass; }, // This accepts a text component class that takes the text string to be // rendered as props. injectTextComponentClass: function (componentClass) { textComponentClass = componentClass; } }; /** * Get a host internal component class for a specific tag. * * @param {ReactElement} element The element to create. * @return {function} The internal class constructor function. */ function createInternalComponent(element) { !genericComponentClass ? "development" !== 'production' ? invariant(false, 'There is no registered component for the tag %s', element.type) : _prodInvariant('111', element.type) : void 0; return new genericComponentClass(element); } /** * @param {ReactText} text * @return {ReactComponent} */ function createInstanceForText(text) { return new textComponentClass(text); } /** * @param {ReactComponent} component * @return {boolean} */ function isTextComponent(component) { return component instanceof textComponentClass; } var ReactHostComponent = { createInternalComponent: createInternalComponent, createInstanceForText: createInstanceForText, isTextComponent: isTextComponent, injection: ReactHostComponentInjection }; module.exports = ReactHostComponent; },{"124":124,"149":149}],59:[function(_dereq_,module,exports){ /** * Copyright 2016-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'; // Trust the developer to only use this with a __DEV__ check var ReactHostOperationHistoryHook = null; if ("development" !== 'production') { var history = []; ReactHostOperationHistoryHook = { onHostOperation: function (operation) { history.push(operation); }, clearHistory: function () { if (ReactHostOperationHistoryHook._preventClearing) { // Should only be used for tests. return; } history = []; }, getHistory: function () { return history; } }; } module.exports = ReactHostOperationHistoryHook; },{}],60:[function(_dereq_,module,exports){ /** * 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. * */ 'use strict'; var ReactDOMSelection = _dereq_(42); var containsNode = _dereq_(138); var focusNode = _dereq_(143); var getActiveElement = _dereq_(144); function isInDocument(node) { return containsNode(document.documentElement, node); } /** * @ReactInputSelection: React input selection module. Based on Selection.js, * but modified to be suitable for react and has a couple of bug fixes (doesn't * assume buttons have range selections allowed). * Input selection module for React. */ var ReactInputSelection = { hasSelectionCapabilities: function (elem) { var nodeName = elem && elem.nodeName && elem.nodeName.toLowerCase(); return nodeName && (nodeName === 'input' && elem.type === 'text' || nodeName === 'textarea' || elem.contentEditable === 'true'); }, getSelectionInformation: function () { var focusedElem = getActiveElement(); return { focusedElem: focusedElem, selectionRange: ReactInputSelection.hasSelectionCapabilities(focusedElem) ? ReactInputSelection.getSelection(focusedElem) : null }; }, /** * @restoreSelection: If any selection information was potentially lost, * restore it. This is useful when performing operations that could remove dom * nodes and place them back in, resulting in focus being lost. */ restoreSelection: function (priorSelectionInformation) { var curFocusedElem = getActiveElement(); var priorFocusedElem = priorSelectionInformation.focusedElem; var priorSelectionRange = priorSelectionInformation.selectionRange; if (curFocusedElem !== priorFocusedElem && isInDocument(priorFocusedElem)) { if (ReactInputSelection.hasSelectionCapabilities(priorFocusedElem)) { ReactInputSelection.setSelection(priorFocusedElem, priorSelectionRange); } // Focusing a node can change the scroll position, which is undesirable var ancestors = []; var ancestor = priorFocusedElem; while (ancestor = ancestor.parentNode) { if (ancestor.nodeType === 1) { ancestors.push({ element: ancestor, left: ancestor.scrollLeft, top: ancestor.scrollTop }); } } focusNode(priorFocusedElem); for (var i = 0; i < ancestors.length; i++) { var info = ancestors[i]; info.element.scrollLeft = info.left; info.element.scrollTop = info.top; } } }, /** * @getSelection: Gets the selection bounds of a focused textarea, input or * contentEditable node. * -@input: Look up selection bounds of this input * -@return {start: selectionStart, end: selectionEnd} */ getSelection: function (input) { var selection; if ('selectionStart' in input) { // Modern browser with input or textarea. selection = { start: input.selectionStart, end: input.selectionEnd }; } else if (document.selection && input.nodeName && input.nodeName.toLowerCase() === 'input') { // IE8 input. var range = document.selection.createRange(); // There can only be one selection per document in IE, so it must // be in our element. if (range.parentElement() === input) { selection = { start: -range.moveStart('character', -input.value.length), end: -range.moveEnd('character', -input.value.length) }; } } else { // Content editable or old IE textarea. selection = ReactDOMSelection.getOffsets(input); } return selection || { start: 0, end: 0 }; }, /** * @setSelection: Sets the selection bounds of a textarea or input and focuses * the input. * -@input Set selection bounds of this input or textarea * -@offsets Object of same form that is returned from get* */ setSelection: function (input, offsets) { var start = offsets.start; var end = offsets.end; if (end === undefined) { end = start; } if ('selectionStart' in input) { input.selectionStart = start; input.selectionEnd = Math.min(end, input.value.length); } else if (document.selection && input.nodeName && input.nodeName.toLowerCase() === 'input') { var range = input.createTextRange(); range.collapse(true); range.moveStart('character', start); range.moveEnd('character', end - start); range.select(); } else { ReactDOMSelection.setOffsets(input, offsets); } } }; module.exports = ReactInputSelection; },{"138":138,"143":143,"144":144,"42":42}],61:[function(_dereq_,module,exports){ /** * 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. * */ 'use strict'; /** * `ReactInstanceMap` maintains a mapping from a public facing stateful * instance (key) and the internal representation (value). This allows public * methods to accept the user facing instance as an argument and map them back * to internal methods. */ // TODO: Replace this with ES6: var ReactInstanceMap = new Map(); var ReactInstanceMap = { /** * This API should be called `delete` but we'd have to make sure to always * transform these to strings for IE support. When this transform is fully * supported we can rename it. */ remove: function (key) { key._reactInternalInstance = undefined; }, get: function (key) { return key._reactInternalInstance; }, has: function (key) { return key._reactInternalInstance !== undefined; }, set: function (key, value) { key._reactInternalInstance = value; } }; module.exports = ReactInstanceMap; },{}],62:[function(_dereq_,module,exports){ /** * Copyright 2016-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'; // Trust the developer to only use ReactInstrumentation with a __DEV__ check var debugTool = null; if ("development" !== 'production') { var ReactDebugTool = _dereq_(49); debugTool = ReactDebugTool; } module.exports = { debugTool: debugTool }; },{"49":49}],63:[function(_dereq_,module,exports){ /** * Copyright 2016-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'; var warning = _dereq_(156); var ReactInvalidSetStateWarningHook = {}; if ("development" !== 'production') { var processingChildContext = false; var warnInvalidSetState = function () { "development" !== 'production' ? warning(!processingChildContext, 'setState(...): Cannot call setState() inside getChildContext()') : void 0; }; ReactInvalidSetStateWarningHook = { onBeginProcessingChildContext: function () { processingChildContext = true; }, onEndProcessingChildContext: function () { processingChildContext = false; }, onSetState: function () { warnInvalidSetState(); } }; } module.exports = ReactInvalidSetStateWarningHook; },{"156":156}],64:[function(_dereq_,module,exports){ /** * 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. * */ 'use strict'; var adler32 = _dereq_(100); var TAG_END = /\/?>/; var COMMENT_START = /^<\!\-\-/; var ReactMarkupChecksum = { CHECKSUM_ATTR_NAME: 'data-react-checksum', /** * @param {string} markup Markup string * @return {string} Markup string with checksum attribute attached */ addChecksumToMarkup: function (markup) { var checksum = adler32(markup); // Add checksum (handle both parent tags, comments and self-closing tags) if (COMMENT_START.test(markup)) { return markup; } else { return markup.replace(TAG_END, ' ' + ReactMarkupChecksum.CHECKSUM_ATTR_NAME + '="' + checksum + '"$&'); } }, /** * @param {string} markup to use * @param {DOMElement} element root React element * @returns {boolean} whether or not the markup is the same */ canReuseMarkup: function (markup, element) { var existingChecksum = element.getAttribute(ReactMarkupChecksum.CHECKSUM_ATTR_NAME); existingChecksum = existingChecksum && parseInt(existingChecksum, 10); var markupChecksum = adler32(markup); return markupChecksum === existingChecksum; } }; module.exports = ReactMarkupChecksum; },{"100":100}],65:[function(_dereq_,module,exports){ /** * 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. * */ 'use strict'; var _prodInvariant = _dereq_(124); var ReactComponentEnvironment = _dereq_(27); var ReactInstanceMap = _dereq_(61); var ReactInstrumentation = _dereq_(62); var ReactCurrentOwner = _dereq_(132); var ReactReconciler = _dereq_(70); var ReactChildReconciler = _dereq_(25); var emptyFunction = _dereq_(141); var flattenChildren = _dereq_(106); var invariant = _dereq_(149); /** * Make an update for markup to be rendered and inserted at a supplied index. * * @param {string} markup Markup that renders into an element. * @param {number} toIndex Destination index. * @private */ function makeInsertMarkup(markup, afterNode, toIndex) { // NOTE: Null values reduce hidden classes. return { type: 'INSERT_MARKUP', content: markup, fromIndex: null, fromNode: null, toIndex: toIndex, afterNode: afterNode }; } /** * Make an update for moving an existing element to another index. * * @param {number} fromIndex Source index of the existing element. * @param {number} toIndex Destination index of the element. * @private */ function makeMove(child, afterNode, toIndex) { // NOTE: Null values reduce hidden classes. return { type: 'MOVE_EXISTING', content: null, fromIndex: child._mountIndex, fromNode: ReactReconciler.getHostNode(child), toIndex: toIndex, afterNode: afterNode }; } /** * Make an update for removing an element at an index. * * @param {number} fromIndex Index of the element to remove. * @private */ function makeRemove(child, node) { // NOTE: Null values reduce hidden classes. return { type: 'REMOVE_NODE', content: null, fromIndex: child._mountIndex, fromNode: node, toIndex: null, afterNode: null }; } /** * Make an update for setting the markup of a node. * * @param {string} markup Markup that renders into an element. * @private */ function makeSetMarkup(markup) { // NOTE: Null values reduce hidden classes. return { type: 'SET_MARKUP', content: markup, fromIndex: null, fromNode: null, toIndex: null, afterNode: null }; } /** * Make an update for setting the text content. * * @param {string} textContent Text content to set. * @private */ function makeTextContent(textContent) { // NOTE: Null values reduce hidden classes. return { type: 'TEXT_CONTENT', content: textContent, fromIndex: null, fromNode: null, toIndex: null, afterNode: null }; } /** * Push an update, if any, onto the queue. Creates a new queue if none is * passed and always returns the queue. Mutative. */ function enqueue(queue, update) { if (update) { queue = queue || []; queue.push(update); } return queue; } /** * Processes any enqueued updates. * * @private */ function processQueue(inst, updateQueue) { ReactComponentEnvironment.processChildrenUpdates(inst, updateQueue); } var setChildrenForInstrumentation = emptyFunction; if ("development" !== 'production') { var getDebugID = function (inst) { if (!inst._debugID) { // Check for ART-like instances. TODO: This is silly/gross. var internal; if (internal = ReactInstanceMap.get(inst)) { inst = internal; } } return inst._debugID; }; setChildrenForInstrumentation = function (children) { var debugID = getDebugID(this); // TODO: React Native empty components are also multichild. // This means they still get into this method but don't have _debugID. if (debugID !== 0) { ReactInstrumentation.debugTool.onSetChildren(debugID, children ? Object.keys(children).map(function (key) { return children[key]._debugID; }) : []); } }; } /** * Provides common functionality for components that must reconcile multiple * children. This is used by `ReactDOMComponent` to mount, update, and * unmount child components. */ var ReactMultiChild = { _reconcilerInstantiateChildren: function (nestedChildren, transaction, context) { if ("development" !== 'production') { var selfDebugID = getDebugID(this); if (this._currentElement) { try { ReactCurrentOwner.current = this._currentElement._owner; return ReactChildReconciler.instantiateChildren(nestedChildren, transaction, context, selfDebugID); } finally { ReactCurrentOwner.current = null; } } } return ReactChildReconciler.instantiateChildren(nestedChildren, transaction, context); }, _reconcilerUpdateChildren: function (prevChildren, nextNestedChildrenElements, mountImages, removedNodes, transaction, context) { var nextChildren; var selfDebugID = 0; if ("development" !== 'production') { selfDebugID = getDebugID(this); if (this._currentElement) { try { ReactCurrentOwner.current = this._currentElement._owner; nextChildren = flattenChildren(nextNestedChildrenElements, selfDebugID); } finally { ReactCurrentOwner.current = null; } ReactChildReconciler.updateChildren(prevChildren, nextChildren, mountImages, removedNodes, transaction, this, this._hostContainerInfo, context, selfDebugID); return nextChildren; } } nextChildren = flattenChildren(nextNestedChildrenElements, selfDebugID); ReactChildReconciler.updateChildren(prevChildren, nextChildren, mountImages, removedNodes, transaction, this, this._hostContainerInfo, context, selfDebugID); return nextChildren; }, /** * Generates a "mount image" for each of the supplied children. In the case * of `ReactDOMComponent`, a mount image is a string of markup. * * @param {?object} nestedChildren Nested child maps. * @return {array} An array of mounted representations. * @internal */ mountChildren: function (nestedChildren, transaction, context) { var children = this._reconcilerInstantiateChildren(nestedChildren, transaction, context); this._renderedChildren = children; var mountImages = []; var index = 0; for (var name in children) { if (children.hasOwnProperty(name)) { var child = children[name]; var selfDebugID = 0; if ("development" !== 'production') { selfDebugID = getDebugID(this); } var mountImage = ReactReconciler.mountComponent(child, transaction, this, this._hostContainerInfo, context, selfDebugID); child._mountIndex = index++; mountImages.push(mountImage); } } if ("development" !== 'production') { setChildrenForInstrumentation.call(this, children); } return mountImages; }, /** * Replaces any rendered children with a text content string. * * @param {string} nextContent String of content. * @internal */ updateTextContent: function (nextContent) { var prevChildren = this._renderedChildren; // Remove any rendered children. ReactChildReconciler.unmountChildren(prevChildren, false, /* safely */ false /* skipLifecycle */ ); for (var name in prevChildren) { if (prevChildren.hasOwnProperty(name)) { !false ? "development" !== 'production' ? invariant(false, 'updateTextContent called on non-empty component.') : _prodInvariant('118') : void 0; } } // Set new text content. var updates = [makeTextContent(nextContent)]; processQueue(this, updates); }, /** * Replaces any rendered children with a markup string. * * @param {string} nextMarkup String of markup. * @internal */ updateMarkup: function (nextMarkup) { var prevChildren = this._renderedChildren; // Remove any rendered children. ReactChildReconciler.unmountChildren(prevChildren, false, /* safely */ false /* skipLifecycle */ ); for (var name in prevChildren) { if (prevChildren.hasOwnProperty(name)) { !false ? "development" !== 'production' ? invariant(false, 'updateTextContent called on non-empty component.') : _prodInvariant('118') : void 0; } } var updates = [makeSetMarkup(nextMarkup)]; processQueue(this, updates); }, /** * Updates the rendered children with new children. * * @param {?object} nextNestedChildrenElements Nested child element maps. * @param {ReactReconcileTransaction} transaction * @internal */ updateChildren: function (nextNestedChildrenElements, transaction, context) { // Hook used by React ART this._updateChildren(nextNestedChildrenElements, transaction, context); }, /** * @param {?object} nextNestedChildrenElements Nested child element maps. * @param {ReactReconcileTransaction} transaction * @final * @protected */ _updateChildren: function (nextNestedChildrenElements, transaction, context) { var prevChildren = this._renderedChildren; var removedNodes = {}; var mountImages = []; var nextChildren = this._reconcilerUpdateChildren(prevChildren, nextNestedChildrenElements, mountImages, removedNodes, transaction, context); if (!nextChildren && !prevChildren) { return; } var updates = null; var name; // `nextIndex` will increment for each child in `nextChildren`, but // `lastIndex` will be the last index visited in `prevChildren`. var nextIndex = 0; var lastIndex = 0; // `nextMountIndex` will increment for each newly mounted child. var nextMountIndex = 0; var lastPlacedNode = null; for (name in nextChildren) { if (!nextChildren.hasOwnProperty(name)) { continue; } var prevChild = prevChildren && prevChildren[name]; var nextChild = nextChildren[name]; if (prevChild === nextChild) { updates = enqueue(updates, this.moveChild(prevChild, lastPlacedNode, nextIndex, lastIndex)); lastIndex = Math.max(prevChild._mountIndex, lastIndex); prevChild._mountIndex = nextIndex; } else { if (prevChild) { // Update `lastIndex` before `_mountIndex` gets unset by unmounting. lastIndex = Math.max(prevChild._mountIndex, lastIndex); // The `removedNodes` loop below will actually remove the child. } // The child must be instantiated before it's mounted. updates = enqueue(updates, this._mountChildAtIndex(nextChild, mountImages[nextMountIndex], lastPlacedNode, nextIndex, transaction, context)); nextMountIndex++; } nextIndex++; lastPlacedNode = ReactReconciler.getHostNode(nextChild); } // Remove children that are no longer present. for (name in removedNodes) { if (removedNodes.hasOwnProperty(name)) { updates = enqueue(updates, this._unmountChild(prevChildren[name], removedNodes[name])); } } if (updates) { processQueue(this, updates); } this._renderedChildren = nextChildren; if ("development" !== 'production') { setChildrenForInstrumentation.call(this, nextChildren); } }, /** * Unmounts all rendered children. This should be used to clean up children * when this component is unmounted. It does not actually perform any * backend operations. * * @internal */ unmountChildren: function (safely, skipLifecycle) { var renderedChildren = this._renderedChildren; ReactChildReconciler.unmountChildren(renderedChildren, safely, skipLifecycle); this._renderedChildren = null; }, /** * Moves a child component to the supplied index. * * @param {ReactComponent} child Component to move. * @param {number} toIndex Destination index of the element. * @param {number} lastIndex Last index visited of the siblings of `child`. * @protected */ moveChild: function (child, afterNode, toIndex, lastIndex) { // If the index of `child` is less than `lastIndex`, then it needs to // be moved. Otherwise, we do not need to move it because a child will be // inserted or moved before `child`. if (child._mountIndex < lastIndex) { return makeMove(child, afterNode, toIndex); } }, /** * Creates a child component. * * @param {ReactComponent} child Component to create. * @param {string} mountImage Markup to insert. * @protected */ createChild: function (child, afterNode, mountImage) { return makeInsertMarkup(mountImage, afterNode, child._mountIndex); }, /** * Removes a child component. * * @param {ReactComponent} child Child to remove. * @protected */ removeChild: function (child, node) { return makeRemove(child, node); }, /** * Mounts a child with the supplied name. * * NOTE: This is part of `updateChildren` and is here for readability. * * @param {ReactComponent} child Component to mount. * @param {string} name Name of the child. * @param {number} index Index at which to insert the child. * @param {ReactReconcileTransaction} transaction * @private */ _mountChildAtIndex: function (child, mountImage, afterNode, index, transaction, context) { child._mountIndex = index; return this.createChild(child, afterNode, mountImage); }, /** * Unmounts a rendered child. * * NOTE: This is part of `updateChildren` and is here for readability. * * @param {ReactComponent} child Component to unmount. * @private */ _unmountChild: function (child, node) { var update = this.removeChild(child, node); child._mountIndex = null; return update; } }; module.exports = ReactMultiChild; },{"106":106,"124":124,"132":132,"141":141,"149":149,"25":25,"27":27,"61":61,"62":62,"70":70}],66:[function(_dereq_,module,exports){ /** * 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. * * */ 'use strict'; var _prodInvariant = _dereq_(124); var React = _dereq_(133); var invariant = _dereq_(149); var ReactNodeTypes = { HOST: 0, COMPOSITE: 1, EMPTY: 2, getType: function (node) { if (node === null || node === false) { return ReactNodeTypes.EMPTY; } else if (React.isValidElement(node)) { if (typeof node.type === 'function') { return ReactNodeTypes.COMPOSITE; } else { return ReactNodeTypes.HOST; } } !false ? "development" !== 'production' ? invariant(false, 'Unexpected node: %s', node) : _prodInvariant('26', node) : void 0; } }; module.exports = ReactNodeTypes; },{"124":124,"133":133,"149":149}],67:[function(_dereq_,module,exports){ /** * 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. * * */ 'use strict'; var _prodInvariant = _dereq_(124); var _require = _dereq_(77), ClassComponent = _require.ClassComponent; var emptyObject = _dereq_(142); var invariant = _dereq_(149); /** * @param {?object} object * @return {boolean} True if `object` is a valid owner. * @final */ function isValidOwner(object) { return !!(object && typeof object.attachRef === 'function' && typeof object.detachRef === 'function'); } /** * ReactOwners are capable of storing references to owned components. * * All components are capable of //being// referenced by owner components, but * only ReactOwner components are capable of //referencing// owned components. * The named reference is known as a "ref". * * Refs are available when mounted and updated during reconciliation. * * var MyComponent = React.createClass({ * render: function() { * return ( * <div onClick={this.handleClick}> * <CustomComponent ref="custom" /> * </div> * ); * }, * handleClick: function() { * this.refs.custom.handleClick(); * }, * componentDidMount: function() { * this.refs.custom.initialize(); * } * }); * * Refs should rarely be used. When refs are used, they should only be done to * control data that is not handled by React's data flow. * * @class ReactOwner */ var ReactOwner = { /** * Adds a component by ref to an owner component. * * @param {ReactComponent} component Component to reference. * @param {string} ref Name by which to refer to the component. * @param {ReactOwner} owner Component on which to record the ref. * @final * @internal */ addComponentAsRefTo: function (component, ref, owner) { if (owner && owner.tag === ClassComponent) { var inst = owner.stateNode; var refs = inst.refs === emptyObject ? inst.refs = {} : inst.refs; refs[ref] = component.getPublicInstance(); } else { !isValidOwner(owner) ? "development" !== 'production' ? invariant(false, 'addComponentAsRefTo(...): Only a ReactOwner can have refs. You might be adding a ref to a component that was not created inside a component\'s `render` method, or you have multiple copies of React loaded (details: https://fb.me/react-refs-must-have-owner).') : _prodInvariant('119') : void 0; owner.attachRef(ref, component); } }, /** * Removes a component by ref from an owner component. * * @param {ReactComponent} component Component to dereference. * @param {string} ref Name of the ref to remove. * @param {ReactOwner} owner Component on which the ref is recorded. * @final * @internal */ removeComponentAsRefFrom: function (component, ref, owner) { if (owner && owner.tag === ClassComponent) { var inst = owner.stateNode; if (inst && inst.refs[ref] === component.getPublicInstance()) { delete inst.refs[ref]; } } else { !isValidOwner(owner) ? "development" !== 'production' ? invariant(false, 'removeComponentAsRefFrom(...): Only a ReactOwner can have refs. You might be removing a ref to a component that was not created inside a component\'s `render` method, or you have multiple copies of React loaded (details: https://fb.me/react-refs-must-have-owner).') : _prodInvariant('120') : void 0; var ownerPublicInstance = owner.getPublicInstance(); // Check that `component`'s owner is still alive and that `component` is still the current ref // because we do not want to detach the ref if another component stole it. if (ownerPublicInstance && ownerPublicInstance.refs[ref] === component.getPublicInstance()) { owner.detachRef(ref); } } } }; module.exports = ReactOwner; },{"124":124,"142":142,"149":149,"77":77}],68:[function(_dereq_,module,exports){ /** * 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. * * */ 'use strict'; var ReactPropTypeLocationNames = {}; if ("development" !== 'production') { ReactPropTypeLocationNames = { prop: 'prop', context: 'context', childContext: 'child context' }; } module.exports = ReactPropTypeLocationNames; },{}],69:[function(_dereq_,module,exports){ /** * 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. * */ 'use strict'; var _assign = _dereq_(157); var CallbackQueue = _dereq_(6); var PooledClass = _dereq_(23); var ReactBrowserEventEmitter = _dereq_(24); var ReactInputSelection = _dereq_(60); var ReactInstrumentation = _dereq_(62); var Transaction = _dereq_(97); var ReactUpdateQueue = _dereq_(78); /** * Ensures that, when possible, the selection range (currently selected text * input) is not disturbed by performing the transaction. */ var SELECTION_RESTORATION = { /** * @return {Selection} Selection information. */ initialize: ReactInputSelection.getSelectionInformation, /** * @param {Selection} sel Selection information returned from `initialize`. */ close: ReactInputSelection.restoreSelection }; /** * Suppresses events (blur/focus) that could be inadvertently dispatched due to * high level DOM manipulations (like temporarily removing a text input from the * DOM). */ var EVENT_SUPPRESSION = { /** * @return {boolean} The enabled status of `ReactBrowserEventEmitter` before * the reconciliation. */ initialize: function () { var currentlyEnabled = ReactBrowserEventEmitter.isEnabled(); ReactBrowserEventEmitter.setEnabled(false); return currentlyEnabled; }, /** * @param {boolean} previouslyEnabled Enabled status of * `ReactBrowserEventEmitter` before the reconciliation occurred. `close` * restores the previous value. */ close: function (previouslyEnabled) { ReactBrowserEventEmitter.setEnabled(previouslyEnabled); } }; /** * Provides a queue for collecting `componentDidMount` and * `componentDidUpdate` callbacks during the transaction. */ var ON_DOM_READY_QUEUEING = { /** * Initializes the internal `onDOMReady` queue. */ initialize: function () { this.reactMountReady.reset(); }, /** * After DOM is flushed, invoke all registered `onDOMReady` callbacks. */ close: function () { this.reactMountReady.notifyAll(); } }; /** * Executed within the scope of the `Transaction` instance. Consider these as * being member methods, but with an implied ordering while being isolated from * each other. */ var TRANSACTION_WRAPPERS = [SELECTION_RESTORATION, EVENT_SUPPRESSION, ON_DOM_READY_QUEUEING]; if ("development" !== 'production') { TRANSACTION_WRAPPERS.push({ initialize: ReactInstrumentation.debugTool.onBeginFlush, close: ReactInstrumentation.debugTool.onEndFlush }); } /** * Currently: * - The order that these are listed in the transaction is critical: * - Suppresses events. * - Restores selection range. * * Future: * - Restore document/overflow scroll positions that were unintentionally * modified via DOM insertions above the top viewport boundary. * - Implement/integrate with customized constraint based layout system and keep * track of which dimensions must be remeasured. * * @class ReactReconcileTransaction */ function ReactReconcileTransaction(useCreateElement) { this.reinitializeTransaction(); // Only server-side rendering really needs this option (see // `ReactServerRendering`), but server-side uses // `ReactServerRenderingTransaction` instead. This option is here so that it's // accessible and defaults to false when `ReactDOMComponent` and // `ReactDOMTextComponent` checks it in `mountComponent`.` this.renderToStaticMarkup = false; this.reactMountReady = CallbackQueue.getPooled(null); this.useCreateElement = useCreateElement; } var Mixin = { /** * @see Transaction * @abstract * @final * @return {array<object>} List of operation wrap procedures. * TODO: convert to array<TransactionWrapper> */ getTransactionWrappers: function () { return TRANSACTION_WRAPPERS; }, /** * @return {object} The queue to collect `onDOMReady` callbacks with. */ getReactMountReady: function () { return this.reactMountReady; }, /** * @return {object} The queue to collect React async events. */ getUpdateQueue: function () { return ReactUpdateQueue; }, /** * Save current transaction state -- if the return value from this method is * passed to `rollback`, the transaction will be reset to that state. */ checkpoint: function () { // reactMountReady is the our only stateful wrapper return this.reactMountReady.checkpoint(); }, rollback: function (checkpoint) { this.reactMountReady.rollback(checkpoint); }, /** * `PooledClass` looks for this, and will invoke this before allowing this * instance to be reused. */ destructor: function () { CallbackQueue.release(this.reactMountReady); this.reactMountReady = null; } }; _assign(ReactReconcileTransaction.prototype, Transaction, Mixin); PooledClass.addPoolingTo(ReactReconcileTransaction); module.exports = ReactReconcileTransaction; },{"157":157,"23":23,"24":24,"6":6,"60":60,"62":62,"78":78,"97":97}],70:[function(_dereq_,module,exports){ /** * 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. * */ 'use strict'; var ReactRef = _dereq_(71); var ReactInstrumentation = _dereq_(62); var warning = _dereq_(156); /** * Helper to call ReactRef.attachRefs with this composite component, split out * to avoid allocations in the transaction mount-ready queue. */ function attachRefs() { ReactRef.attachRefs(this, this._currentElement); } 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 ("development" !== 'production') { 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 ("development" !== 'production') { 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, skipLifecycle) { if ("development" !== 'production') { if (internalInstance._debugID !== 0) { ReactInstrumentation.debugTool.onBeforeUnmountComponent(internalInstance._debugID); } } ReactRef.detachRefs(internalInstance, internalInstance._currentElement); internalInstance.unmountComponent(safely, skipLifecycle); if ("development" !== 'production') { 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 ("development" !== 'production') { 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 ("development" !== 'production') { 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. "development" !== 'production' ? warning(internalInstance._updateBatchNumber == null || internalInstance._updateBatchNumber === updateBatchNumber + 1, 'performUpdateIfNecessary: Unexpected batch number (current %s, ' + 'pending %s)', updateBatchNumber, internalInstance._updateBatchNumber) : void 0; return; } if ("development" !== 'production') { if (internalInstance._debugID !== 0) { ReactInstrumentation.debugTool.onBeforeUpdateComponent(internalInstance._debugID, internalInstance._currentElement); } } internalInstance.performUpdateIfNecessary(transaction); if ("development" !== 'production') { if (internalInstance._debugID !== 0) { ReactInstrumentation.debugTool.onUpdateComponent(internalInstance._debugID); } } } }; module.exports = ReactReconciler; },{"156":156,"62":62,"71":71}],71:[function(_dereq_,module,exports){ /** * 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. * * */ 'use strict'; var ReactOwner = _dereq_(67); var ReactRef = {}; if ("development" !== 'production') { var ReactCompositeComponentTypes = _dereq_(29); var ReactComponentTreeHook = _dereq_(131); var warning = _dereq_(156); } function attachRef(ref, component, owner) { if ("development" !== 'production') { var info = ''; if (owner) { var ownerName = void 0; if (typeof owner.getName === 'function') { ownerName = owner.getName(); } if (ownerName) { info += ' Check the render method of `' + ownerName + '`.'; } } "development" !== 'production' ? warning(component._compositeType !== ReactCompositeComponentTypes.StatelessFunctional, 'Stateless function components cannot be given refs. ' + 'Attempts to access this ref will fail.%s%s', info, ReactComponentTreeHook.getStackAddendumByID(component._debugID)) : void 0; } if (typeof ref === 'function') { ref(component.getPublicInstance()); } else { // Legacy ref ReactOwner.addComponentAsRefTo(component, ref, owner); } } function detachRef(ref, component, owner) { if (typeof ref === 'function') { ref(null); } else { // Legacy ref ReactOwner.removeComponentAsRefFrom(component, ref, owner); } } ReactRef.attachRefs = function (instance, element) { if (element === null || typeof element !== 'object') { return; } var ref = element.ref; if (ref != null) { attachRef(ref, instance, element._owner); } }; ReactRef.shouldUpdateRefs = function (prevElement, nextElement) { // If either the owner or a `ref` has changed, make sure the newest owner // has stored a reference to `this`, and the previous owner (if different) // has forgotten the reference to `this`. We use the element instead // of the public this.props because the post processing cannot determine // a ref. The ref conceptually lives on the element. // TODO: Should this even be possible? The owner cannot change because // it's forbidden by shouldUpdateReactComponent. The ref can change // if you swap the keys of but not the refs. Reconsider where this check // is made. It probably belongs where the key checking and // instantiateReactComponent is done. var prevRef = null; var prevOwner = null; if (prevElement !== null && typeof prevElement === 'object') { prevRef = prevElement.ref; prevOwner = prevElement._owner; } var nextRef = null; var nextOwner = null; if (nextElement !== null && typeof nextElement === 'object') { nextRef = nextElement.ref; nextOwner = nextElement._owner; } return prevRef !== nextRef || // If owner changes but we have an unchanged function ref, don't update refs typeof nextRef === 'string' && nextOwner !== prevOwner; }; ReactRef.detachRefs = function (instance, element) { if (element === null || typeof element !== 'object') { return; } var ref = element.ref; if (ref != null) { detachRef(ref, instance, element._owner); } }; module.exports = ReactRef; },{"131":131,"156":156,"29":29,"67":67}],72:[function(_dereq_,module,exports){ /** * Copyright 2014-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'; var ReactServerBatchingStrategy = { isBatchingUpdates: false, batchedUpdates: function (callback) { // Don't do anything here. During the server rendering we don't want to // schedule any updates. We will simply ignore them. } }; module.exports = ReactServerBatchingStrategy; },{}],73:[function(_dereq_,module,exports){ /** * 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. * */ 'use strict'; var _prodInvariant = _dereq_(124); var React = _dereq_(133); var ReactDOMContainerInfo = _dereq_(35); var ReactInstrumentation = _dereq_(62); var ReactMarkupChecksum = _dereq_(64); var ReactReconciler = _dereq_(70); var ReactServerBatchingStrategy = _dereq_(72); var ReactServerRenderingTransaction = _dereq_(74); var ReactUpdates = _dereq_(79); var emptyObject = _dereq_(142); var instantiateReactComponent = _dereq_(120); var invariant = _dereq_(149); var pendingTransactions = 0; /** * @param {ReactElement} element * @return {string} the HTML markup */ function renderToStringImpl(element, makeStaticMarkup) { var transaction; var previousBatchingStrategy; try { previousBatchingStrategy = ReactUpdates.injection.getBatchingStrategy(); ReactUpdates.injection.injectBatchingStrategy(ReactServerBatchingStrategy); transaction = ReactServerRenderingTransaction.getPooled(makeStaticMarkup); pendingTransactions++; return transaction.perform(function () { var componentInstance = instantiateReactComponent(element, true); var markup = ReactReconciler.mountComponent(componentInstance, transaction, null, ReactDOMContainerInfo(), emptyObject, 0 /* parentDebugID */ ); if ("development" !== 'production') { ReactInstrumentation.debugTool.onUnmountComponent(componentInstance._debugID); } if (!makeStaticMarkup) { markup = ReactMarkupChecksum.addChecksumToMarkup(markup); } return markup; }, null); } finally { pendingTransactions--; ReactServerRenderingTransaction.release(transaction); // Revert to the DOM batching strategy since these two renderers // currently share these stateful modules. if (!pendingTransactions) { ReactUpdates.injection.injectBatchingStrategy(previousBatchingStrategy); } } } /** * Render a ReactElement to its initial HTML. This should only be used on the * server. * See https://facebook.github.io/react/docs/react-dom-server.html#rendertostring */ function renderToString(element) { !React.isValidElement(element) ? "development" !== 'production' ? invariant(false, 'renderToString(): You must pass a valid ReactElement.') : _prodInvariant('46') : void 0; return renderToStringImpl(element, false); } /** * Similar to renderToString, except this doesn't create extra DOM attributes * such as data-react-id that React uses internally. * See https://facebook.github.io/react/docs/react-dom-server.html#rendertostaticmarkup */ function renderToStaticMarkup(element) { !React.isValidElement(element) ? "development" !== 'production' ? invariant(false, 'renderToStaticMarkup(): You must pass a valid ReactElement.') : _prodInvariant('47') : void 0; return renderToStringImpl(element, true); } module.exports = { renderToString: renderToString, renderToStaticMarkup: renderToStaticMarkup }; },{"120":120,"124":124,"133":133,"142":142,"149":149,"35":35,"62":62,"64":64,"70":70,"72":72,"74":74,"79":79}],74:[function(_dereq_,module,exports){ /** * Copyright 2014-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'; var _assign = _dereq_(157); var PooledClass = _dereq_(23); var Transaction = _dereq_(97); var ReactInstrumentation = _dereq_(62); var ReactServerUpdateQueue = _dereq_(75); /** * Executed within the scope of the `Transaction` instance. Consider these as * being member methods, but with an implied ordering while being isolated from * each other. */ var TRANSACTION_WRAPPERS = []; if ("development" !== 'production') { TRANSACTION_WRAPPERS.push({ initialize: ReactInstrumentation.debugTool.onBeginFlush, close: ReactInstrumentation.debugTool.onEndFlush }); } var noopCallbackQueue = { enqueue: function () {} }; /** * @class ReactServerRenderingTransaction * @param {boolean} renderToStaticMarkup */ function ReactServerRenderingTransaction(renderToStaticMarkup) { this.reinitializeTransaction(); this.renderToStaticMarkup = renderToStaticMarkup; this.useCreateElement = false; this.updateQueue = new ReactServerUpdateQueue(this); } var Mixin = { /** * @see Transaction * @abstract * @final * @return {array} Empty list of operation wrap procedures. */ getTransactionWrappers: function () { return TRANSACTION_WRAPPERS; }, /** * @return {object} The queue to collect `onDOMReady` callbacks with. */ getReactMountReady: function () { return noopCallbackQueue; }, /** * @return {object} The queue to collect React async events. */ getUpdateQueue: function () { return this.updateQueue; }, /** * `PooledClass` looks for this, and will invoke this before allowing this * instance to be reused. */ destructor: function () {}, checkpoint: function () {}, rollback: function () {} }; _assign(ReactServerRenderingTransaction.prototype, Transaction, Mixin); PooledClass.addPoolingTo(ReactServerRenderingTransaction); module.exports = ReactServerRenderingTransaction; },{"157":157,"23":23,"62":62,"75":75,"97":97}],75:[function(_dereq_,module,exports){ /** * Copyright 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'; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var ReactUpdateQueue = _dereq_(78); var warning = _dereq_(156); function warnNoop(publicInstance, callerName) { if ("development" !== 'production') { var constructor = publicInstance.constructor; "development" !== 'production' ? warning(false, '%s(...): Can only update a mounting component. ' + 'This usually means you called %s() outside componentWillMount() on the server. ' + 'This is a no-op. Please check the code for the %s component.', callerName, callerName, constructor && (constructor.displayName || constructor.name) || 'ReactClass') : void 0; } } /** * This is the update queue used for server rendering. * It delegates to ReactUpdateQueue while server rendering is in progress and * switches to ReactNoopUpdateQueue after the transaction has completed. * @class ReactServerUpdateQueue * @param {Transaction} transaction */ var ReactServerUpdateQueue = function () { function ReactServerUpdateQueue(transaction) { _classCallCheck(this, ReactServerUpdateQueue); this.transaction = transaction; } /** * Checks whether or not this composite component is mounted. * @param {ReactClass} publicInstance The instance we want to test. * @return {boolean} True if mounted, false otherwise. * @protected * @final */ ReactServerUpdateQueue.prototype.isMounted = function isMounted(publicInstance) { return false; }; /** * Forces an update. This should only be invoked when it is known with * certainty that we are **not** in a DOM transaction. * * You may want to call this when you know that some deeper aspect of the * component's state has changed but `setState` was not called. * * This will not invoke `shouldComponentUpdate`, but it will invoke * `componentWillUpdate` and `componentDidUpdate`. * * @param {ReactClass} publicInstance The instance that should rerender. * @param {?function} callback Called after component is updated. * @param {?string} Name of the calling function in the public API. * @internal */ ReactServerUpdateQueue.prototype.enqueueForceUpdate = function enqueueForceUpdate(publicInstance, callback, callerName) { if (this.transaction.isInTransaction()) { ReactUpdateQueue.enqueueForceUpdate(publicInstance, callback, callerName); } else { warnNoop(publicInstance, 'forceUpdate'); } }; /** * Replaces all of the state. Always use this or `setState` to mutate state. * You should treat `this.state` as immutable. * * There is no guarantee that `this.state` will be immediately updated, so * accessing `this.state` after calling this method may return the old value. * * @param {ReactClass} publicInstance The instance that should rerender. * @param {object|function} completeState Next state. * @param {?function} callback Called after component is updated. * @param {?string} Name of the calling function in the public API. * @internal */ ReactServerUpdateQueue.prototype.enqueueReplaceState = function enqueueReplaceState(publicInstance, completeState, callback, callerName) { if (this.transaction.isInTransaction()) { ReactUpdateQueue.enqueueReplaceState(publicInstance, completeState, callback, callerName); } else { warnNoop(publicInstance, 'replaceState'); } }; /** * Sets a subset of the state. This only exists because _pendingState is * internal. This provides a merging strategy that is not available to deep * properties which is confusing. TODO: Expose pendingState or don't use it * during the merge. * * @param {ReactClass} publicInstance The instance that should rerender. * @param {object|function} partialState Next partial state to be merged with state. * @internal */ ReactServerUpdateQueue.prototype.enqueueSetState = function enqueueSetState(publicInstance, partialState, callback, callerName) { if (this.transaction.isInTransaction()) { ReactUpdateQueue.enqueueSetState(publicInstance, partialState, callback, callerName); } else { warnNoop(publicInstance, 'setState'); } }; return ReactServerUpdateQueue; }(); module.exports = ReactServerUpdateQueue; },{"156":156,"78":78}],76:[function(_dereq_,module,exports){ /** * Copyright 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'; var _require = _dereq_(77), HostComponent = _require.HostComponent; var _require2 = _dereq_(18), getNodeFromInstance = _require2.getNodeFromInstance, getInstanceFromNode = _require2.getInstanceFromNode; function getParent(inst) { if (inst._hostParent !== undefined) { return inst._hostParent; } if (typeof inst.tag === 'number') { do { inst = inst['return']; // TODO: If this is a HostRoot we might want to bail out. // That is depending on if we want nested subtrees (layers) to bubble // events to their parent. We could also go through parentNode on the // host node but that wouldn't work for React Native and doesn't let us // do the portal feature. } while (inst && inst.tag !== HostComponent); // Going through the Host Node will guarantee that we get the "current" // Fiber, instead of the alternate because that pointer is updated when // props update. // TODO: This is a bit hacky and possibly slow. We should ideally have // something in the reconciler that allow us to do this safely. if (inst) { return getInstanceFromNode(getNodeFromInstance(inst)); } } return null; } /** * Return the lowest common ancestor of A and B, or null if they are in * different trees. */ function getLowestCommonAncestor(instA, instB) { var depthA = 0; for (var tempA = instA; tempA; tempA = getParent(tempA)) { depthA++; } var depthB = 0; for (var tempB = instB; tempB; tempB = getParent(tempB)) { depthB++; } // If A is deeper, crawl up. while (depthA - depthB > 0) { instA = getParent(instA); depthA--; } // If B is deeper, crawl up. while (depthB - depthA > 0) { instB = getParent(instB); depthB--; } // Walk in lockstep until we find a match. var depth = depthA; while (depth--) { if (instA === instB) { return instA; } instA = getParent(instA); instB = getParent(instB); } return null; } /** * Return if A is an ancestor of B. */ function isAncestor(instA, instB) { while (instB) { if (instB === instA) { return true; } instB = getParent(instB); } return false; } /** * Return the parent instance of the passed-in instance. */ function getParentInstance(inst) { return getParent(inst); } /** * Simulates the traversal of a two-phase, capture/bubble event dispatch. */ function traverseTwoPhase(inst, fn, arg) { var path = []; while (inst) { path.push(inst); inst = getParent(inst); } var i; for (i = path.length; i-- > 0;) { fn(path[i], 'captured', arg); } for (i = 0; i < path.length; i++) { fn(path[i], 'bubbled', arg); } } /** * Traverses the ID hierarchy and invokes the supplied `cb` on any IDs that * should would receive a `mouseEnter` or `mouseLeave` event. * * Does not invoke the callback on the nearest common ancestor because nothing * "entered" or "left" that element. */ function traverseEnterLeave(from, to, fn, argFrom, argTo) { var common = from && to ? getLowestCommonAncestor(from, to) : null; var pathFrom = []; while (from && from !== common) { pathFrom.push(from); from = getParent(from); } var pathTo = []; while (to && to !== common) { pathTo.push(to); to = getParent(to); } var i; for (i = 0; i < pathFrom.length; i++) { fn(pathFrom[i], 'bubbled', argFrom); } for (i = pathTo.length; i-- > 0;) { fn(pathTo[i], 'captured', argTo); } } module.exports = { isAncestor: isAncestor, getLowestCommonAncestor: getLowestCommonAncestor, getParentInstance: getParentInstance, traverseTwoPhase: traverseTwoPhase, traverseEnterLeave: traverseEnterLeave }; },{"18":18,"77":77}],77:[function(_dereq_,module,exports){ /** * 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. * * */ 'use strict'; module.exports = { IndeterminateComponent: 0, // Before we know whether it is functional or class FunctionalComponent: 1, ClassComponent: 2, HostRoot: 3, // Root of a host tree. Could be nested inside another node. HostPortal: 4, // A subtree. Could be an entry point to a different renderer. HostComponent: 5, HostText: 6, CoroutineComponent: 7, CoroutineHandlerPhase: 8, YieldComponent: 9, Fragment: 10 }; },{}],78:[function(_dereq_,module,exports){ /** * Copyright 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'; var ReactCurrentOwner = _dereq_(132); var ReactInstanceMap = _dereq_(61); var ReactInstrumentation = _dereq_(62); var ReactUpdates = _dereq_(79); var warning = _dereq_(156); var validateCallback = _dereq_(129); function enqueueUpdate(internalInstance) { ReactUpdates.enqueueUpdate(internalInstance); } function getInternalInstanceReadyForUpdate(publicInstance, callerName) { var internalInstance = ReactInstanceMap.get(publicInstance); if (!internalInstance) { if ("development" !== 'production') { var ctor = publicInstance.constructor; // Only warn when we have a callerName. Otherwise we should be silent. // We're probably calling from enqueueCallback. We don't want to warn // there because we already warned for the corresponding lifecycle method. "development" !== 'production' ? warning(!callerName, '%s(...): Can only update a mounted or mounting component. ' + 'This usually means you called %s() on an unmounted component. ' + 'This is a no-op. Please check the code for the %s component.', callerName, callerName, ctor && (ctor.displayName || ctor.name) || 'ReactClass') : void 0; } return null; } if ("development" !== 'production') { "development" !== 'production' ? warning(ReactCurrentOwner.current == null, '%s(...): Cannot update during an existing state transition (such as ' + 'within `render` or another component\'s constructor). Render methods ' + 'should be a pure function of props and state; constructor ' + 'side-effects are an anti-pattern, but can be moved to ' + '`componentWillMount`.', callerName) : void 0; } return internalInstance; } /** * ReactUpdateQueue allows for state updates to be scheduled into a later * reconciliation step. */ var ReactUpdateQueue = { /** * Checks whether or not this composite component is mounted. * @param {ReactClass} publicInstance The instance we want to test. * @return {boolean} True if mounted, false otherwise. * @protected * @final */ isMounted: function (publicInstance) { if ("development" !== 'production') { var owner = ReactCurrentOwner.current; if (owner !== null) { "development" !== 'production' ? warning(owner._warnedAboutRefsInRender, '%s is accessing isMounted inside its render() function. ' + 'render() should be a pure function of props and state. It should ' + 'never access something that requires stale data from the previous ' + 'render, such as refs. Move this logic to componentDidMount and ' + 'componentDidUpdate instead.', owner.getName() || 'A component') : void 0; owner._warnedAboutRefsInRender = true; } } var internalInstance = ReactInstanceMap.get(publicInstance); if (internalInstance) { // During componentWillMount and render this will still be null but after // that will always render to something. At least for now. So we can use // this hack. return !!internalInstance._renderedComponent; } else { return false; } }, enqueueCallbackInternal: function (internalInstance, callback) { if (internalInstance._pendingCallbacks) { internalInstance._pendingCallbacks.push(callback); } else { internalInstance._pendingCallbacks = [callback]; } enqueueUpdate(internalInstance); }, /** * Forces an update. This should only be invoked when it is known with * certainty that we are **not** in a DOM transaction. * * You may want to call this when you know that some deeper aspect of the * component's state has changed but `setState` was not called. * * This will not invoke `shouldComponentUpdate`, but it will invoke * `componentWillUpdate` and `componentDidUpdate`. * * @param {ReactClass} publicInstance The instance that should rerender. * @param {?function} callback Called after component is updated. * @param {?string} Name of the calling function in the public API. * @internal */ enqueueForceUpdate: function (publicInstance, callback, callerName) { var internalInstance = getInternalInstanceReadyForUpdate(publicInstance, 'forceUpdate'); if (!internalInstance) { return; } if (callback) { validateCallback(callback, callerName); if (internalInstance._pendingCallbacks) { internalInstance._pendingCallbacks.push(callback); } else { internalInstance._pendingCallbacks = [callback]; } } internalInstance._pendingForceUpdate = true; enqueueUpdate(internalInstance); }, /** * Replaces all of the state. Always use this or `setState` to mutate state. * You should treat `this.state` as immutable. * * There is no guarantee that `this.state` will be immediately updated, so * accessing `this.state` after calling this method may return the old value. * * @param {ReactClass} publicInstance The instance that should rerender. * @param {object} completeState Next state. * @param {?function} callback Called after state is updated. * @param {?string} Name of the calling function in the public API. * @internal */ enqueueReplaceState: function (publicInstance, completeState, callback, callerName) { var internalInstance = getInternalInstanceReadyForUpdate(publicInstance, 'replaceState'); if (!internalInstance) { return; } internalInstance._pendingStateQueue = [completeState]; internalInstance._pendingReplaceState = true; if (callback) { validateCallback(callback, callerName); if (internalInstance._pendingCallbacks) { internalInstance._pendingCallbacks.push(callback); } else { internalInstance._pendingCallbacks = [callback]; } } enqueueUpdate(internalInstance); }, /** * Sets a subset of the state. This only exists because _pendingState is * internal. This provides a merging strategy that is not available to deep * properties which is confusing. TODO: Expose pendingState or don't use it * during the merge. * * @param {ReactClass} publicInstance The instance that should rerender. * @param {object} partialState Next partial state to be merged with state. * @param {?function} callback Called after state is updated. * @param {?string} Name of the calling function in the public API. * @internal */ enqueueSetState: function (publicInstance, partialState, callback, callerName) { if ("development" !== 'production') { ReactInstrumentation.debugTool.onSetState(); "development" !== 'production' ? warning(partialState != null, 'setState(...): You passed an undefined or null state object; ' + 'instead, use forceUpdate().') : void 0; } var internalInstance = getInternalInstanceReadyForUpdate(publicInstance, 'setState'); if (!internalInstance) { return; } var queue = internalInstance._pendingStateQueue || (internalInstance._pendingStateQueue = []); queue.push(partialState); if (callback) { validateCallback(callback, callerName); if (internalInstance._pendingCallbacks) { internalInstance._pendingCallbacks.push(callback); } else { internalInstance._pendingCallbacks = [callback]; } } enqueueUpdate(internalInstance); }, enqueueElementInternal: function (internalInstance, nextElement, nextContext) { internalInstance._pendingElement = nextElement; // TODO: introduce _pendingContext instead of setting it directly. internalInstance._context = nextContext; enqueueUpdate(internalInstance); } }; module.exports = ReactUpdateQueue; },{"129":129,"132":132,"156":156,"61":61,"62":62,"79":79}],79:[function(_dereq_,module,exports){ /** * 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. * */ 'use strict'; var _prodInvariant = _dereq_(124), _assign = _dereq_(157); var PooledClass = _dereq_(23); var ReactFeatureFlags = _dereq_(56); var ReactReconciler = _dereq_(70); var Transaction = _dereq_(97); var invariant = _dereq_(149); var dirtyComponents = []; var updateBatchNumber = 0; var batchingStrategy = null; function ensureInjected() { !(ReactUpdates.ReactReconcileTransaction && batchingStrategy) ? "development" !== 'production' ? invariant(false, 'ReactUpdates: must inject a reconcile transaction class and batching strategy') : _prodInvariant('123') : void 0; } var NESTED_UPDATES = { initialize: function () { this.dirtyComponentsLength = dirtyComponents.length; }, close: function () { if (this.dirtyComponentsLength !== dirtyComponents.length) { // Additional updates were enqueued by componentDidUpdate handlers or // similar; before our own UPDATE_QUEUEING wrapper closes, we want to run // these new updates so that if A's componentDidUpdate calls setState on // B, B will update before the callback A's updater provided when calling // setState. dirtyComponents.splice(0, this.dirtyComponentsLength); flushBatchedUpdates(); } else { dirtyComponents.length = 0; } } }; var TRANSACTION_WRAPPERS = [NESTED_UPDATES]; function ReactUpdatesFlushTransaction() { this.reinitializeTransaction(); this.dirtyComponentsLength = null; this.reconcileTransaction = ReactUpdates.ReactReconcileTransaction.getPooled( /* useCreateElement */true); } _assign(ReactUpdatesFlushTransaction.prototype, Transaction, { getTransactionWrappers: function () { return TRANSACTION_WRAPPERS; }, destructor: function () { this.dirtyComponentsLength = null; ReactUpdates.ReactReconcileTransaction.release(this.reconcileTransaction); this.reconcileTransaction = null; }, perform: function (method, scope, a) { // Essentially calls `this.reconcileTransaction.perform(method, scope, a)` // with this transaction's wrappers around it. return Transaction.perform.call(this, this.reconcileTransaction.perform, this.reconcileTransaction, method, scope, a); } }); PooledClass.addPoolingTo(ReactUpdatesFlushTransaction); function batchedUpdates(callback, a, b, c, d, e) { ensureInjected(); return batchingStrategy.batchedUpdates(callback, a, b, c, d, e); } /** * Array comparator for ReactComponents by mount ordering. * * @param {ReactComponent} c1 first component you're comparing * @param {ReactComponent} c2 second component you're comparing * @return {number} Return value usable by Array.prototype.sort(). */ function mountOrderComparator(c1, c2) { return c1._mountOrder - c2._mountOrder; } function runBatchedUpdates(transaction) { var len = transaction.dirtyComponentsLength; !(len === dirtyComponents.length) ? "development" !== 'production' ? invariant(false, 'Expected flush transaction\'s stored dirty-components length (%s) to match dirty-components array length (%s).', len, dirtyComponents.length) : _prodInvariant('124', len, dirtyComponents.length) : void 0; // Since reconciling a component higher in the owner hierarchy usually (not // always -- see shouldComponentUpdate()) will reconcile children, reconcile // them before their children by sorting the array. dirtyComponents.sort(mountOrderComparator); // Any updates enqueued while reconciling must be performed after this entire // batch. Otherwise, if dirtyComponents is [A, B] where A has children B and // C, B could update twice in a single batch if C's render enqueues an update // to B (since B would have already updated, we should skip it, and the only // way we can know to do so is by checking the batch counter). updateBatchNumber++; for (var i = 0; i < len; i++) { // If a component is unmounted before pending changes apply, it will still // be here, but we assume that it has cleared its _pendingCallbacks and // that performUpdateIfNecessary is a noop. var component = dirtyComponents[i]; var markerName; if (ReactFeatureFlags.logTopLevelRenders) { var namedComponent = component; // Duck type TopLevelWrapper. This is probably always true. if (component._currentElement.type.isReactTopLevelWrapper) { namedComponent = component._renderedComponent; } markerName = 'React update: ' + namedComponent.getName(); console.time(markerName); } ReactReconciler.performUpdateIfNecessary(component, transaction.reconcileTransaction, updateBatchNumber); if (markerName) { console.timeEnd(markerName); } } } var flushBatchedUpdates = function () { // ReactUpdatesFlushTransaction's wrappers will clear the dirtyComponents // array and perform any updates enqueued by mount-ready handlers (i.e., // componentDidUpdate) but we need to check here too in order to catch // updates enqueued by setState callbacks. while (dirtyComponents.length) { var transaction = ReactUpdatesFlushTransaction.getPooled(); transaction.perform(runBatchedUpdates, null, transaction); ReactUpdatesFlushTransaction.release(transaction); } }; /** * Mark a component as needing a rerender, adding an optional callback to a * list of functions which will be executed once the rerender occurs. */ function enqueueUpdate(component) { ensureInjected(); // Various parts of our code (such as ReactCompositeComponent's // _renderValidatedComponent) assume that calls to render aren't nested; // verify that that's the case. (This is called by each top-level update // function, like setState, forceUpdate, etc.; creation and // destruction of top-level components is guarded in ReactMount.) if (!batchingStrategy.isBatchingUpdates) { batchingStrategy.batchedUpdates(enqueueUpdate, component); return; } dirtyComponents.push(component); if (component._updateBatchNumber == null) { component._updateBatchNumber = updateBatchNumber + 1; } } var ReactUpdatesInjection = { injectReconcileTransaction: function (ReconcileTransaction) { !ReconcileTransaction ? "development" !== 'production' ? invariant(false, 'ReactUpdates: must provide a reconcile transaction class') : _prodInvariant('126') : void 0; ReactUpdates.ReactReconcileTransaction = ReconcileTransaction; }, injectBatchingStrategy: function (_batchingStrategy) { !_batchingStrategy ? "development" !== 'production' ? invariant(false, 'ReactUpdates: must provide a batching strategy') : _prodInvariant('127') : void 0; !(typeof _batchingStrategy.batchedUpdates === 'function') ? "development" !== 'production' ? invariant(false, 'ReactUpdates: must provide a batchedUpdates() function') : _prodInvariant('128') : void 0; !(typeof _batchingStrategy.isBatchingUpdates === 'boolean') ? "development" !== 'production' ? invariant(false, 'ReactUpdates: must provide an isBatchingUpdates boolean attribute') : _prodInvariant('129') : void 0; batchingStrategy = _batchingStrategy; }, getBatchingStrategy: function () { return batchingStrategy; } }; var ReactUpdates = { /** * React references `ReactReconcileTransaction` using this property in order * to allow dependency injection. * * @internal */ ReactReconcileTransaction: null, batchedUpdates: batchedUpdates, enqueueUpdate: enqueueUpdate, flushBatchedUpdates: flushBatchedUpdates, injection: ReactUpdatesInjection }; module.exports = ReactUpdates; },{"124":124,"149":149,"157":157,"23":23,"56":56,"70":70,"97":97}],80:[function(_dereq_,module,exports){ /** * 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. * */ 'use strict'; module.exports = '16.0.0-alpha'; },{}],81:[function(_dereq_,module,exports){ /** * 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. * */ 'use strict'; var NS = { xlink: 'http://www.w3.org/1999/xlink', xml: 'http://www.w3.org/XML/1998/namespace' }; // We use attributes for everything SVG so let's avoid some duplication and run // code instead. // The following are all specified in the HTML config already so we exclude here. // - class (as className) // - color // - height // - id // - lang // - max // - media // - method // - min // - name // - style // - target // - type // - width var ATTRS = { accentHeight: 'accent-height', accumulate: 0, additive: 0, alignmentBaseline: 'alignment-baseline', allowReorder: 'allowReorder', alphabetic: 0, amplitude: 0, arabicForm: 'arabic-form', ascent: 0, attributeName: 'attributeName', attributeType: 'attributeType', autoReverse: 'autoReverse', azimuth: 0, baseFrequency: 'baseFrequency', baseProfile: 'baseProfile', baselineShift: 'baseline-shift', bbox: 0, begin: 0, bias: 0, by: 0, calcMode: 'calcMode', capHeight: 'cap-height', clip: 0, clipPath: 'clip-path', clipRule: 'clip-rule', clipPathUnits: 'clipPathUnits', colorInterpolation: 'color-interpolation', colorInterpolationFilters: 'color-interpolation-filters', colorProfile: 'color-profile', colorRendering: 'color-rendering', contentScriptType: 'contentScriptType', contentStyleType: 'contentStyleType', cursor: 0, cx: 0, cy: 0, d: 0, decelerate: 0, descent: 0, diffuseConstant: 'diffuseConstant', direction: 0, display: 0, divisor: 0, dominantBaseline: 'dominant-baseline', dur: 0, dx: 0, dy: 0, edgeMode: 'edgeMode', elevation: 0, enableBackground: 'enable-background', end: 0, exponent: 0, externalResourcesRequired: 'externalResourcesRequired', fill: 0, fillOpacity: 'fill-opacity', fillRule: 'fill-rule', filter: 0, filterRes: 'filterRes', filterUnits: 'filterUnits', floodColor: 'flood-color', floodOpacity: 'flood-opacity', focusable: 0, fontFamily: 'font-family', fontSize: 'font-size', fontSizeAdjust: 'font-size-adjust', fontStretch: 'font-stretch', fontStyle: 'font-style', fontVariant: 'font-variant', fontWeight: 'font-weight', format: 0, from: 0, fx: 0, fy: 0, g1: 0, g2: 0, glyphName: 'glyph-name', glyphOrientationHorizontal: 'glyph-orientation-horizontal', glyphOrientationVertical: 'glyph-orientation-vertical', glyphRef: 'glyphRef', gradientTransform: 'gradientTransform', gradientUnits: 'gradientUnits', hanging: 0, horizAdvX: 'horiz-adv-x', horizOriginX: 'horiz-origin-x', ideographic: 0, imageRendering: 'image-rendering', 'in': 0, in2: 0, intercept: 0, k: 0, k1: 0, k2: 0, k3: 0, k4: 0, kernelMatrix: 'kernelMatrix', kernelUnitLength: 'kernelUnitLength', kerning: 0, keyPoints: 'keyPoints', keySplines: 'keySplines', keyTimes: 'keyTimes', lengthAdjust: 'lengthAdjust', letterSpacing: 'letter-spacing', lightingColor: 'lighting-color', limitingConeAngle: 'limitingConeAngle', local: 0, markerEnd: 'marker-end', markerMid: 'marker-mid', markerStart: 'marker-start', markerHeight: 'markerHeight', markerUnits: 'markerUnits', markerWidth: 'markerWidth', mask: 0, maskContentUnits: 'maskContentUnits', maskUnits: 'maskUnits', mathematical: 0, mode: 0, numOctaves: 'numOctaves', offset: 0, opacity: 0, operator: 0, order: 0, orient: 0, orientation: 0, origin: 0, overflow: 0, overlinePosition: 'overline-position', overlineThickness: 'overline-thickness', paintOrder: 'paint-order', panose1: 'panose-1', pathLength: 'pathLength', patternContentUnits: 'patternContentUnits', patternTransform: 'patternTransform', patternUnits: 'patternUnits', pointerEvents: 'pointer-events', points: 0, pointsAtX: 'pointsAtX', pointsAtY: 'pointsAtY', pointsAtZ: 'pointsAtZ', preserveAlpha: 'preserveAlpha', preserveAspectRatio: 'preserveAspectRatio', primitiveUnits: 'primitiveUnits', r: 0, radius: 0, refX: 'refX', refY: 'refY', renderingIntent: 'rendering-intent', repeatCount: 'repeatCount', repeatDur: 'repeatDur', requiredExtensions: 'requiredExtensions', requiredFeatures: 'requiredFeatures', restart: 0, result: 0, rotate: 0, rx: 0, ry: 0, scale: 0, seed: 0, shapeRendering: 'shape-rendering', slope: 0, spacing: 0, specularConstant: 'specularConstant', specularExponent: 'specularExponent', speed: 0, spreadMethod: 'spreadMethod', startOffset: 'startOffset', stdDeviation: 'stdDeviation', stemh: 0, stemv: 0, stitchTiles: 'stitchTiles', stopColor: 'stop-color', stopOpacity: 'stop-opacity', strikethroughPosition: 'strikethrough-position', strikethroughThickness: 'strikethrough-thickness', string: 0, stroke: 0, strokeDasharray: 'stroke-dasharray', strokeDashoffset: 'stroke-dashoffset', strokeLinecap: 'stroke-linecap', strokeLinejoin: 'stroke-linejoin', strokeMiterlimit: 'stroke-miterlimit', strokeOpacity: 'stroke-opacity', strokeWidth: 'stroke-width', surfaceScale: 'surfaceScale', systemLanguage: 'systemLanguage', tableValues: 'tableValues', targetX: 'targetX', targetY: 'targetY', textAnchor: 'text-anchor', textDecoration: 'text-decoration', textRendering: 'text-rendering', textLength: 'textLength', to: 0, transform: 0, u1: 0, u2: 0, underlinePosition: 'underline-position', underlineThickness: 'underline-thickness', unicode: 0, unicodeBidi: 'unicode-bidi', unicodeRange: 'unicode-range', unitsPerEm: 'units-per-em', vAlphabetic: 'v-alphabetic', vHanging: 'v-hanging', vIdeographic: 'v-ideographic', vMathematical: 'v-mathematical', values: 0, vectorEffect: 'vector-effect', version: 0, vertAdvY: 'vert-adv-y', vertOriginX: 'vert-origin-x', vertOriginY: 'vert-origin-y', viewBox: 'viewBox', viewTarget: 'viewTarget', visibility: 0, widths: 0, wordSpacing: 'word-spacing', writingMode: 'writing-mode', x: 0, xHeight: 'x-height', x1: 0, x2: 0, xChannelSelector: 'xChannelSelector', xlinkActuate: 'xlink:actuate', xlinkArcrole: 'xlink:arcrole', xlinkHref: 'xlink:href', xlinkRole: 'xlink:role', xlinkShow: 'xlink:show', xlinkTitle: 'xlink:title', xlinkType: 'xlink:type', xmlBase: 'xml:base', xmlns: 0, xmlnsXlink: 'xmlns:xlink', xmlLang: 'xml:lang', xmlSpace: 'xml:space', y: 0, y1: 0, y2: 0, yChannelSelector: 'yChannelSelector', z: 0, zoomAndPan: 'zoomAndPan' }; var SVGDOMPropertyConfig = { Properties: {}, DOMAttributeNamespaces: { xlinkActuate: NS.xlink, xlinkArcrole: NS.xlink, xlinkHref: NS.xlink, xlinkRole: NS.xlink, xlinkShow: NS.xlink, xlinkTitle: NS.xlink, xlinkType: NS.xlink, xmlBase: NS.xml, xmlLang: NS.xml, xmlSpace: NS.xml }, DOMAttributeNames: {} }; Object.keys(ATTRS).forEach(function (key) { SVGDOMPropertyConfig.Properties[key] = 0; if (ATTRS[key]) { SVGDOMPropertyConfig.DOMAttributeNames[key] = ATTRS[key]; } }); module.exports = SVGDOMPropertyConfig; },{}],82:[function(_dereq_,module,exports){ /** * 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. * */ 'use strict'; var EventPropagators = _dereq_(19); var ExecutionEnvironment = _dereq_(135); var ReactBrowserEventEmitter = _dereq_(24); var ReactDOMComponentTree = _dereq_(34); var ReactInputSelection = _dereq_(60); var SyntheticEvent = _dereq_(88); var getActiveElement = _dereq_(144); var isTextInputElement = _dereq_(122); var shallowEqual = _dereq_(155); var skipSelectionChangeEvent = ExecutionEnvironment.canUseDOM && 'documentMode' in document && document.documentMode <= 11; var eventTypes = { select: { phasedRegistrationNames: { bubbled: 'onSelect', captured: 'onSelectCapture' }, dependencies: ['topBlur', 'topContextMenu', 'topFocus', 'topKeyDown', 'topKeyUp', 'topMouseDown', 'topMouseUp', 'topSelectionChange'] } }; var activeElement = null; var activeElementInst = null; var lastSelection = null; var mouseDown = false; // Track whether all listeners exists for this plugin. If none exist, we do // not extract events. See #3639. var isListeningToAllDependencies = ReactBrowserEventEmitter.isListeningToAllDependencies; /** * Get an object which is a unique representation of the current selection. * * The return value will not be consistent across nodes or browsers, but * two identical selections on the same node will return identical objects. * * @param {DOMElement} node * @return {object} */ function getSelection(node) { if ('selectionStart' in node && ReactInputSelection.hasSelectionCapabilities(node)) { return { start: node.selectionStart, end: node.selectionEnd }; } else if (window.getSelection) { var selection = window.getSelection(); return { anchorNode: selection.anchorNode, anchorOffset: selection.anchorOffset, focusNode: selection.focusNode, focusOffset: selection.focusOffset }; } else if (document.selection) { var range = document.selection.createRange(); return { parentElement: range.parentElement(), text: range.text, top: range.boundingTop, left: range.boundingLeft }; } } /** * Poll selection to see whether it's changed. * * @param {object} nativeEvent * @return {?SyntheticEvent} */ function constructSelectEvent(nativeEvent, nativeEventTarget) { // Ensure we have the right element, and that the user is not dragging a // selection (this matches native `select` event behavior). In HTML5, select // fires only on input and textarea thus if there's no focused element we // won't dispatch. if (mouseDown || activeElement == null || activeElement !== getActiveElement()) { return null; } // Only fire when selection has actually changed. var currentSelection = getSelection(activeElement); if (!lastSelection || !shallowEqual(lastSelection, currentSelection)) { lastSelection = currentSelection; var syntheticEvent = SyntheticEvent.getPooled(eventTypes.select, activeElementInst, nativeEvent, nativeEventTarget); syntheticEvent.type = 'select'; syntheticEvent.target = activeElement; EventPropagators.accumulateTwoPhaseDispatches(syntheticEvent); return syntheticEvent; } return null; } /** * This plugin creates an `onSelect` event that normalizes select events * across form elements. * * Supported elements are: * - input (see `isTextInputElement`) * - textarea * - contentEditable * * This differs from native browser implementations in the following ways: * - Fires on contentEditable fields as well as inputs. * - Fires for collapsed selection. * - Fires after user input. */ var SelectEventPlugin = { eventTypes: eventTypes, extractEvents: function (topLevelType, targetInst, nativeEvent, nativeEventTarget) { var doc = nativeEventTarget.window === nativeEventTarget ? nativeEventTarget.document : nativeEventTarget.nodeType === 9 ? nativeEventTarget : nativeEventTarget.ownerDocument; if (!doc || !isListeningToAllDependencies('onSelect', doc)) { return null; } var targetNode = targetInst ? ReactDOMComponentTree.getNodeFromInstance(targetInst) : window; switch (topLevelType) { // Track the input node that has focus. case 'topFocus': if (isTextInputElement(targetNode) || targetNode.contentEditable === 'true') { activeElement = targetNode; activeElementInst = targetInst; lastSelection = null; } break; case 'topBlur': activeElement = null; activeElementInst = null; lastSelection = null; break; // Don't fire the event while the user is dragging. This matches the // semantics of the native select event. case 'topMouseDown': mouseDown = true; break; case 'topContextMenu': case 'topMouseUp': mouseDown = false; return constructSelectEvent(nativeEvent, nativeEventTarget); // Chrome and IE fire non-standard event when selection is changed (and // sometimes when it hasn't). IE's event fires out of order with respect // to key and input events on deletion, so we discard it. // // Firefox doesn't support selectionchange, so check selection status // after each key entry. The selection changes after keydown and before // keyup, but we check on keydown as well in the case of holding down a // key, when multiple keydown events are fired but only one keyup is. // This is also our approach for IE handling, for the reason above. case 'topSelectionChange': if (skipSelectionChangeEvent) { break; } // falls through case 'topKeyDown': case 'topKeyUp': return constructSelectEvent(nativeEvent, nativeEventTarget); } return null; } }; module.exports = SelectEventPlugin; },{"122":122,"135":135,"144":144,"155":155,"19":19,"24":24,"34":34,"60":60,"88":88}],83:[function(_dereq_,module,exports){ /** * 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. * * */ 'use strict'; var _prodInvariant = _dereq_(124); var EventPropagators = _dereq_(19); var SyntheticAnimationEvent = _dereq_(84); var SyntheticClipboardEvent = _dereq_(85); var SyntheticEvent = _dereq_(88); var SyntheticFocusEvent = _dereq_(89); var SyntheticKeyboardEvent = _dereq_(91); var SyntheticMouseEvent = _dereq_(92); var SyntheticDragEvent = _dereq_(87); var SyntheticTouchEvent = _dereq_(93); var SyntheticTransitionEvent = _dereq_(94); var SyntheticUIEvent = _dereq_(95); var SyntheticWheelEvent = _dereq_(96); var getEventCharCode = _dereq_(109); var invariant = _dereq_(149); /** * Turns * ['abort', ...] * into * eventTypes = { * 'abort': { * phasedRegistrationNames: { * bubbled: 'onAbort', * captured: 'onAbortCapture', * }, * dependencies: ['topAbort'], * }, * ... * }; * topLevelEventsToDispatchConfig = { * 'topAbort': { sameConfig } * }; */ var eventTypes = {}; var topLevelEventsToDispatchConfig = {}; ['abort', 'animationEnd', 'animationIteration', 'animationStart', 'blur', 'canPlay', 'canPlayThrough', 'click', 'contextMenu', 'copy', 'cut', 'doubleClick', 'drag', 'dragEnd', 'dragEnter', 'dragExit', 'dragLeave', 'dragOver', 'dragStart', 'drop', 'durationChange', 'emptied', 'encrypted', 'ended', 'error', 'focus', 'input', 'invalid', 'keyDown', 'keyPress', 'keyUp', 'load', 'loadedData', 'loadedMetadata', 'loadStart', 'mouseDown', 'mouseMove', 'mouseOut', 'mouseOver', 'mouseUp', 'paste', 'pause', 'play', 'playing', 'progress', 'rateChange', 'reset', 'scroll', 'seeked', 'seeking', 'stalled', 'submit', 'suspend', 'timeUpdate', 'touchCancel', 'touchEnd', 'touchMove', 'touchStart', 'transitionEnd', 'volumeChange', 'waiting', 'wheel'].forEach(function (event) { var capitalizedEvent = event[0].toUpperCase() + event.slice(1); var onEvent = 'on' + capitalizedEvent; var topEvent = 'top' + capitalizedEvent; var type = { phasedRegistrationNames: { bubbled: onEvent, captured: onEvent + 'Capture' }, dependencies: [topEvent] }; eventTypes[event] = type; topLevelEventsToDispatchConfig[topEvent] = type; }); var SimpleEventPlugin = { eventTypes: eventTypes, extractEvents: function (topLevelType, targetInst, nativeEvent, nativeEventTarget) { var dispatchConfig = topLevelEventsToDispatchConfig[topLevelType]; if (!dispatchConfig) { return null; } var EventConstructor; switch (topLevelType) { case 'topAbort': case 'topCanPlay': case 'topCanPlayThrough': case 'topDurationChange': case 'topEmptied': case 'topEncrypted': case 'topEnded': case 'topError': case 'topInput': case 'topInvalid': case 'topLoad': case 'topLoadedData': case 'topLoadedMetadata': case 'topLoadStart': case 'topPause': case 'topPlay': case 'topPlaying': case 'topProgress': case 'topRateChange': case 'topReset': case 'topSeeked': case 'topSeeking': case 'topStalled': case 'topSubmit': case 'topSuspend': case 'topTimeUpdate': case 'topVolumeChange': case 'topWaiting': // HTML Events // @see http://www.w3.org/TR/html5/index.html#events-0 EventConstructor = SyntheticEvent; break; case 'topKeyPress': // Firefox creates a keypress event for function keys too. This removes // the unwanted keypress events. Enter is however both printable and // non-printable. One would expect Tab to be as well (but it isn't). if (getEventCharCode(nativeEvent) === 0) { return null; } /* falls through */ case 'topKeyDown': case 'topKeyUp': EventConstructor = SyntheticKeyboardEvent; break; case 'topBlur': case 'topFocus': EventConstructor = SyntheticFocusEvent; break; case 'topClick': // Firefox creates a click event on right mouse clicks. This removes the // unwanted click events. if (nativeEvent.button === 2) { return null; } /* falls through */ case 'topDoubleClick': case 'topMouseDown': case 'topMouseMove': case 'topMouseUp': // TODO: Disabled elements should not respond to mouse events /* falls through */ case 'topMouseOut': case 'topMouseOver': case 'topContextMenu': EventConstructor = SyntheticMouseEvent; break; case 'topDrag': case 'topDragEnd': case 'topDragEnter': case 'topDragExit': case 'topDragLeave': case 'topDragOver': case 'topDragStart': case 'topDrop': EventConstructor = SyntheticDragEvent; break; case 'topTouchCancel': case 'topTouchEnd': case 'topTouchMove': case 'topTouchStart': EventConstructor = SyntheticTouchEvent; break; case 'topAnimationEnd': case 'topAnimationIteration': case 'topAnimationStart': EventConstructor = SyntheticAnimationEvent; break; case 'topTransitionEnd': EventConstructor = SyntheticTransitionEvent; break; case 'topScroll': EventConstructor = SyntheticUIEvent; break; case 'topWheel': EventConstructor = SyntheticWheelEvent; break; case 'topCopy': case 'topCut': case 'topPaste': EventConstructor = SyntheticClipboardEvent; break; } !EventConstructor ? "development" !== 'production' ? invariant(false, 'SimpleEventPlugin: Unhandled event type, `%s`.', topLevelType) : _prodInvariant('86', topLevelType) : void 0; var event = EventConstructor.getPooled(dispatchConfig, targetInst, nativeEvent, nativeEventTarget); EventPropagators.accumulateTwoPhaseDispatches(event); return event; } }; module.exports = SimpleEventPlugin; },{"109":109,"124":124,"149":149,"19":19,"84":84,"85":85,"87":87,"88":88,"89":89,"91":91,"92":92,"93":93,"94":94,"95":95,"96":96}],84:[function(_dereq_,module,exports){ /** * 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. * */ 'use strict'; var SyntheticEvent = _dereq_(88); /** * @interface Event * @see http://www.w3.org/TR/css3-animations/#AnimationEvent-interface * @see https://developer.mozilla.org/en-US/docs/Web/API/AnimationEvent */ var AnimationEventInterface = { animationName: null, elapsedTime: null, pseudoElement: null }; /** * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @extends {SyntheticEvent} */ function SyntheticAnimationEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { return SyntheticEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); } SyntheticEvent.augmentClass(SyntheticAnimationEvent, AnimationEventInterface); module.exports = SyntheticAnimationEvent; },{"88":88}],85:[function(_dereq_,module,exports){ /** * 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. * */ 'use strict'; var SyntheticEvent = _dereq_(88); /** * @interface Event * @see http://www.w3.org/TR/clipboard-apis/ */ var ClipboardEventInterface = { clipboardData: function (event) { return 'clipboardData' in event ? event.clipboardData : window.clipboardData; } }; /** * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @extends {SyntheticUIEvent} */ function SyntheticClipboardEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { return SyntheticEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); } SyntheticEvent.augmentClass(SyntheticClipboardEvent, ClipboardEventInterface); module.exports = SyntheticClipboardEvent; },{"88":88}],86:[function(_dereq_,module,exports){ /** * 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. * */ 'use strict'; var SyntheticEvent = _dereq_(88); /** * @interface Event * @see http://www.w3.org/TR/DOM-Level-3-Events/#events-compositionevents */ var CompositionEventInterface = { data: null }; /** * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @extends {SyntheticUIEvent} */ function SyntheticCompositionEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { return SyntheticEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); } SyntheticEvent.augmentClass(SyntheticCompositionEvent, CompositionEventInterface); module.exports = SyntheticCompositionEvent; },{"88":88}],87:[function(_dereq_,module,exports){ /** * 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. * */ 'use strict'; var SyntheticMouseEvent = _dereq_(92); /** * @interface DragEvent * @see http://www.w3.org/TR/DOM-Level-3-Events/ */ var DragEventInterface = { dataTransfer: null }; /** * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @extends {SyntheticUIEvent} */ function SyntheticDragEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { return SyntheticMouseEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); } SyntheticMouseEvent.augmentClass(SyntheticDragEvent, DragEventInterface); module.exports = SyntheticDragEvent; },{"92":92}],88:[function(_dereq_,module,exports){ /** * 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. * */ 'use strict'; var _assign = _dereq_(157); var PooledClass = _dereq_(23); var emptyFunction = _dereq_(141); var warning = _dereq_(156); var didWarnForAddedNewProperty = false; var isProxySupported = typeof Proxy === 'function'; var shouldBeReleasedProperties = ['dispatchConfig', '_targetInst', 'nativeEvent', 'isDefaultPrevented', 'isPropagationStopped', '_dispatchListeners', '_dispatchInstances']; /** * @interface Event * @see http://www.w3.org/TR/DOM-Level-3-Events/ */ var EventInterface = { type: null, target: null, // currentTarget is set when dispatching; no use in copying it here currentTarget: emptyFunction.thatReturnsNull, eventPhase: null, bubbles: null, cancelable: null, timeStamp: function (event) { return event.timeStamp || Date.now(); }, defaultPrevented: null, isTrusted: null }; /** * Synthetic events are dispatched by event plugins, typically in response to a * top-level event delegation handler. * * These systems should generally use pooling to reduce the frequency of garbage * collection. The system should check `isPersistent` to determine whether the * event should be released into the pool after being dispatched. Users that * need a persisted event should invoke `persist`. * * Synthetic events (and subclasses) implement the DOM Level 3 Events API by * normalizing browser quirks. Subclasses do not necessarily have to implement a * DOM interface; custom application-specific events can also subclass this. * * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {*} targetInst Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @param {DOMEventTarget} nativeEventTarget Target node. */ function SyntheticEvent(dispatchConfig, targetInst, nativeEvent, nativeEventTarget) { if ("development" !== 'production') { // these have a getter/setter for warnings delete this.nativeEvent; delete this.preventDefault; delete this.stopPropagation; } this.dispatchConfig = dispatchConfig; this._targetInst = targetInst; this.nativeEvent = nativeEvent; var Interface = this.constructor.Interface; for (var propName in Interface) { if (!Interface.hasOwnProperty(propName)) { continue; } if ("development" !== 'production') { delete this[propName]; // this has a getter/setter for warnings } var normalize = Interface[propName]; if (normalize) { this[propName] = normalize(nativeEvent); } else { if (propName === 'target') { this.target = nativeEventTarget; } else { this[propName] = nativeEvent[propName]; } } } var defaultPrevented = nativeEvent.defaultPrevented != null ? nativeEvent.defaultPrevented : nativeEvent.returnValue === false; if (defaultPrevented) { this.isDefaultPrevented = emptyFunction.thatReturnsTrue; } else { this.isDefaultPrevented = emptyFunction.thatReturnsFalse; } this.isPropagationStopped = emptyFunction.thatReturnsFalse; return this; } _assign(SyntheticEvent.prototype, { preventDefault: function () { this.defaultPrevented = true; var event = this.nativeEvent; if (!event) { return; } if (event.preventDefault) { event.preventDefault(); } else if (typeof event.returnValue !== 'unknown') { // eslint-disable-line valid-typeof event.returnValue = false; } this.isDefaultPrevented = emptyFunction.thatReturnsTrue; }, stopPropagation: function () { var event = this.nativeEvent; if (!event) { return; } if (event.stopPropagation) { event.stopPropagation(); } else if (typeof event.cancelBubble !== 'unknown') { // eslint-disable-line valid-typeof // The ChangeEventPlugin registers a "propertychange" event for // IE. This event does not support bubbling or cancelling, and // any references to cancelBubble throw "Member not found". A // typeof check of "unknown" circumvents this issue (and is also // IE specific). event.cancelBubble = true; } this.isPropagationStopped = emptyFunction.thatReturnsTrue; }, /** * We release all dispatched `SyntheticEvent`s after each event loop, adding * them back into the pool. This allows a way to hold onto a reference that * won't be added back into the pool. */ persist: function () { this.isPersistent = emptyFunction.thatReturnsTrue; }, /** * Checks if this event should be released back into the pool. * * @return {boolean} True if this should not be released, false otherwise. */ isPersistent: emptyFunction.thatReturnsFalse, /** * `PooledClass` looks for `destructor` on each instance it releases. */ destructor: function () { var Interface = this.constructor.Interface; for (var propName in Interface) { if ("development" !== 'production') { Object.defineProperty(this, propName, getPooledWarningPropertyDefinition(propName, Interface[propName])); } else { this[propName] = null; } } for (var i = 0; i < shouldBeReleasedProperties.length; i++) { this[shouldBeReleasedProperties[i]] = null; } if ("development" !== 'production') { Object.defineProperty(this, 'nativeEvent', getPooledWarningPropertyDefinition('nativeEvent', null)); Object.defineProperty(this, 'preventDefault', getPooledWarningPropertyDefinition('preventDefault', emptyFunction)); Object.defineProperty(this, 'stopPropagation', getPooledWarningPropertyDefinition('stopPropagation', emptyFunction)); } } }); SyntheticEvent.Interface = EventInterface; if ("development" !== 'production') { if (isProxySupported) { /*eslint-disable no-func-assign */ SyntheticEvent = new Proxy(SyntheticEvent, { construct: function (target, args) { return this.apply(target, Object.create(target.prototype), args); }, apply: function (constructor, that, args) { return new Proxy(constructor.apply(that, args), { set: function (target, prop, value) { if (prop !== 'isPersistent' && !target.constructor.Interface.hasOwnProperty(prop) && shouldBeReleasedProperties.indexOf(prop) === -1) { "development" !== 'production' ? warning(didWarnForAddedNewProperty || target.isPersistent(), 'This synthetic event is reused for performance reasons. If you\'re ' + 'seeing this, you\'re adding a new property in the synthetic event object. ' + 'The property is never released. See ' + 'https://fb.me/react-event-pooling for more information.') : void 0; didWarnForAddedNewProperty = true; } target[prop] = value; return true; } }); } }); /*eslint-enable no-func-assign */ } } /** * Helper to reduce boilerplate when creating subclasses. * * @param {function} Class * @param {?object} Interface */ SyntheticEvent.augmentClass = function (Class, Interface) { var Super = this; var E = function () {}; E.prototype = Super.prototype; var prototype = new E(); _assign(prototype, Class.prototype); Class.prototype = prototype; Class.prototype.constructor = Class; Class.Interface = _assign({}, Super.Interface, Interface); Class.augmentClass = Super.augmentClass; PooledClass.addPoolingTo(Class, PooledClass.fourArgumentPooler); }; PooledClass.addPoolingTo(SyntheticEvent, PooledClass.fourArgumentPooler); module.exports = SyntheticEvent; /** * Helper to nullify syntheticEvent instance properties when destructing * * @param {object} SyntheticEvent * @param {String} propName * @return {object} defineProperty object */ function getPooledWarningPropertyDefinition(propName, getVal) { var isFunction = typeof getVal === 'function'; return { configurable: true, set: set, get: get }; function set(val) { var action = isFunction ? 'setting the method' : 'setting the property'; warn(action, 'This is effectively a no-op'); return val; } function get() { var action = isFunction ? 'accessing the method' : 'accessing the property'; var result = isFunction ? 'This is a no-op function' : 'This is set to null'; warn(action, result); return getVal; } function warn(action, result) { var warningCondition = false; "development" !== 'production' ? warning(warningCondition, 'This synthetic event is reused for performance reasons. If you\'re seeing this, ' + 'you\'re %s `%s` on a released/nullified synthetic event. %s. ' + 'If you must keep the original synthetic event around, use event.persist(). ' + 'See https://fb.me/react-event-pooling for more information.', action, propName, result) : void 0; } } },{"141":141,"156":156,"157":157,"23":23}],89:[function(_dereq_,module,exports){ /** * 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. * */ 'use strict'; var SyntheticUIEvent = _dereq_(95); /** * @interface FocusEvent * @see http://www.w3.org/TR/DOM-Level-3-Events/ */ var FocusEventInterface = { relatedTarget: null }; /** * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @extends {SyntheticUIEvent} */ function SyntheticFocusEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { return SyntheticUIEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); } SyntheticUIEvent.augmentClass(SyntheticFocusEvent, FocusEventInterface); module.exports = SyntheticFocusEvent; },{"95":95}],90:[function(_dereq_,module,exports){ /** * 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. * */ 'use strict'; var SyntheticEvent = _dereq_(88); /** * @interface Event * @see http://www.w3.org/TR/2013/WD-DOM-Level-3-Events-20131105 * /#events-inputevents */ var InputEventInterface = { data: null }; /** * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @extends {SyntheticUIEvent} */ function SyntheticInputEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { return SyntheticEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); } SyntheticEvent.augmentClass(SyntheticInputEvent, InputEventInterface); module.exports = SyntheticInputEvent; },{"88":88}],91:[function(_dereq_,module,exports){ /** * 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. * */ 'use strict'; var SyntheticUIEvent = _dereq_(95); var getEventCharCode = _dereq_(109); var getEventKey = _dereq_(110); var getEventModifierState = _dereq_(111); /** * @interface KeyboardEvent * @see http://www.w3.org/TR/DOM-Level-3-Events/ */ var KeyboardEventInterface = { key: getEventKey, location: null, ctrlKey: null, shiftKey: null, altKey: null, metaKey: null, repeat: null, locale: null, getModifierState: getEventModifierState, // Legacy Interface charCode: function (event) { // `charCode` is the result of a KeyPress event and represents the value of // the actual printable character. // KeyPress is deprecated, but its replacement is not yet final and not // implemented in any major browser. Only KeyPress has charCode. if (event.type === 'keypress') { return getEventCharCode(event); } return 0; }, keyCode: function (event) { // `keyCode` is the result of a KeyDown/Up event and represents the value of // physical keyboard key. // The actual meaning of the value depends on the users' keyboard layout // which cannot be detected. Assuming that it is a US keyboard layout // provides a surprisingly accurate mapping for US and European users. // Due to this, it is left to the user to implement at this time. if (event.type === 'keydown' || event.type === 'keyup') { return event.keyCode; } return 0; }, which: function (event) { // `which` is an alias for either `keyCode` or `charCode` depending on the // type of the event. if (event.type === 'keypress') { return getEventCharCode(event); } if (event.type === 'keydown' || event.type === 'keyup') { return event.keyCode; } return 0; } }; /** * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @extends {SyntheticUIEvent} */ function SyntheticKeyboardEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { return SyntheticUIEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); } SyntheticUIEvent.augmentClass(SyntheticKeyboardEvent, KeyboardEventInterface); module.exports = SyntheticKeyboardEvent; },{"109":109,"110":110,"111":111,"95":95}],92:[function(_dereq_,module,exports){ /** * 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. * */ 'use strict'; var SyntheticUIEvent = _dereq_(95); var ViewportMetrics = _dereq_(98); var getEventModifierState = _dereq_(111); /** * @interface MouseEvent * @see http://www.w3.org/TR/DOM-Level-3-Events/ */ var MouseEventInterface = { screenX: null, screenY: null, clientX: null, clientY: null, ctrlKey: null, shiftKey: null, altKey: null, metaKey: null, getModifierState: getEventModifierState, button: function (event) { // Webkit, Firefox, IE9+ // which: 1 2 3 // button: 0 1 2 (standard) var button = event.button; if ('which' in event) { return button; } // IE<9 // which: undefined // button: 0 0 0 // button: 1 4 2 (onmouseup) return button === 2 ? 2 : button === 4 ? 1 : 0; }, buttons: null, relatedTarget: function (event) { return event.relatedTarget || (event.fromElement === event.srcElement ? event.toElement : event.fromElement); }, // "Proprietary" Interface. pageX: function (event) { return 'pageX' in event ? event.pageX : event.clientX + ViewportMetrics.currentScrollLeft; }, pageY: function (event) { return 'pageY' in event ? event.pageY : event.clientY + ViewportMetrics.currentScrollTop; } }; /** * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @extends {SyntheticUIEvent} */ function SyntheticMouseEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { return SyntheticUIEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); } SyntheticUIEvent.augmentClass(SyntheticMouseEvent, MouseEventInterface); module.exports = SyntheticMouseEvent; },{"111":111,"95":95,"98":98}],93:[function(_dereq_,module,exports){ /** * 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. * */ 'use strict'; var SyntheticUIEvent = _dereq_(95); var getEventModifierState = _dereq_(111); /** * @interface TouchEvent * @see http://www.w3.org/TR/touch-events/ */ var TouchEventInterface = { touches: null, targetTouches: null, changedTouches: null, altKey: null, metaKey: null, ctrlKey: null, shiftKey: null, getModifierState: getEventModifierState }; /** * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @extends {SyntheticUIEvent} */ function SyntheticTouchEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { return SyntheticUIEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); } SyntheticUIEvent.augmentClass(SyntheticTouchEvent, TouchEventInterface); module.exports = SyntheticTouchEvent; },{"111":111,"95":95}],94:[function(_dereq_,module,exports){ /** * 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. * */ 'use strict'; var SyntheticEvent = _dereq_(88); /** * @interface Event * @see http://www.w3.org/TR/2009/WD-css3-transitions-20090320/#transition-events- * @see https://developer.mozilla.org/en-US/docs/Web/API/TransitionEvent */ var TransitionEventInterface = { propertyName: null, elapsedTime: null, pseudoElement: null }; /** * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @extends {SyntheticEvent} */ function SyntheticTransitionEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { return SyntheticEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); } SyntheticEvent.augmentClass(SyntheticTransitionEvent, TransitionEventInterface); module.exports = SyntheticTransitionEvent; },{"88":88}],95:[function(_dereq_,module,exports){ /** * 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. * */ 'use strict'; var SyntheticEvent = _dereq_(88); var getEventTarget = _dereq_(112); /** * @interface UIEvent * @see http://www.w3.org/TR/DOM-Level-3-Events/ */ var UIEventInterface = { view: function (event) { if (event.view) { return event.view; } var target = getEventTarget(event); if (target.window === target) { // target is a window object return target; } var doc = target.ownerDocument; // TODO: Figure out why `ownerDocument` is sometimes undefined in IE8. if (doc) { return doc.defaultView || doc.parentWindow; } else { return window; } }, detail: function (event) { return event.detail || 0; } }; /** * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @extends {SyntheticEvent} */ function SyntheticUIEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { return SyntheticEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); } SyntheticEvent.augmentClass(SyntheticUIEvent, UIEventInterface); module.exports = SyntheticUIEvent; },{"112":112,"88":88}],96:[function(_dereq_,module,exports){ /** * 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. * */ 'use strict'; var SyntheticMouseEvent = _dereq_(92); /** * @interface WheelEvent * @see http://www.w3.org/TR/DOM-Level-3-Events/ */ var WheelEventInterface = { deltaX: function (event) { return 'deltaX' in event ? event.deltaX : // Fallback to `wheelDeltaX` for Webkit and normalize (right is positive). 'wheelDeltaX' in event ? -event.wheelDeltaX : 0; }, deltaY: function (event) { return 'deltaY' in event ? event.deltaY : // Fallback to `wheelDeltaY` for Webkit and normalize (down is positive). 'wheelDeltaY' in event ? -event.wheelDeltaY : // Fallback to `wheelDelta` for IE<9 and normalize (down is positive). 'wheelDelta' in event ? -event.wheelDelta : 0; }, deltaZ: null, // Browsers without "deltaMode" is reporting in raw wheel delta where one // notch on the scroll is always +/- 120, roughly equivalent to pixels. // A good approximation of DOM_DELTA_LINE (1) is 5% of viewport size or // ~40 pixels, for DOM_DELTA_SCREEN (2) it is 87.5% of viewport size. deltaMode: null }; /** * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @extends {SyntheticMouseEvent} */ function SyntheticWheelEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { return SyntheticMouseEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); } SyntheticMouseEvent.augmentClass(SyntheticWheelEvent, WheelEventInterface); module.exports = SyntheticWheelEvent; },{"92":92}],97:[function(_dereq_,module,exports){ /** * 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. * * */ 'use strict'; var _prodInvariant = _dereq_(124); var invariant = _dereq_(149); var OBSERVED_ERROR = {}; /** * `Transaction` creates a black box that is able to wrap any method such that * certain invariants are maintained before and after the method is invoked * (Even if an exception is thrown while invoking the wrapped method). Whoever * instantiates a transaction can provide enforcers of the invariants at * creation time. The `Transaction` class itself will supply one additional * automatic invariant for you - the invariant that any transaction instance * should not be run while it is already being run. You would typically create a * single instance of a `Transaction` for reuse multiple times, that potentially * is used to wrap several different methods. Wrappers are extremely simple - * they only require implementing two methods. * * <pre> * wrappers (injected at creation time) * + + * | | * +-----------------|--------|--------------+ * | v | | * | +---------------+ | | * | +--| wrapper1 |---|----+ | * | | +---------------+ v | | * | | +-------------+ | | * | | +----| wrapper2 |--------+ | * | | | +-------------+ | | | * | | | | | | * | v v v v | wrapper * | +---+ +---+ +---------+ +---+ +---+ | invariants * perform(anyMethod) | | | | | | | | | | | | maintained * +----------------->|-|---|-|---|-->|anyMethod|---|---|-|---|-|--------> * | | | | | | | | | | | | * | | | | | | | | | | | | * | | | | | | | | | | | | * | +---+ +---+ +---------+ +---+ +---+ | * | initialize close | * +-----------------------------------------+ * </pre> * * Use cases: * - Preserving the input selection ranges before/after reconciliation. * Restoring selection even in the event of an unexpected error. * - Deactivating events while rearranging the DOM, preventing blurs/focuses, * while guaranteeing that afterwards, the event system is reactivated. * - Flushing a queue of collected DOM mutations to the main UI thread after a * reconciliation takes place in a worker thread. * - Invoking any collected `componentDidUpdate` callbacks after rendering new * content. * - (Future use case): Wrapping particular flushes of the `ReactWorker` queue * to preserve the `scrollTop` (an automatic scroll aware DOM). * - (Future use case): Layout calculations before and after DOM updates. * * Transactional plugin API: * - A module that has an `initialize` method that returns any precomputation. * - and a `close` method that accepts the precomputation. `close` is invoked * when the wrapped process is completed, or has failed. * * @param {Array<TransactionalWrapper>} transactionWrapper Wrapper modules * that implement `initialize` and `close`. * @return {Transaction} Single transaction for reuse in thread. * * @class Transaction */ var TransactionImpl = { /** * Sets up this instance so that it is prepared for collecting metrics. Does * so such that this setup method may be used on an instance that is already * initialized, in a way that does not consume additional memory upon reuse. * That can be useful if you decide to make your subclass of this mixin a * "PooledClass". */ reinitializeTransaction: function () { this.transactionWrappers = this.getTransactionWrappers(); if (this.wrapperInitData) { this.wrapperInitData.length = 0; } else { this.wrapperInitData = []; } this._isInTransaction = false; }, _isInTransaction: false, /** * @abstract * @return {Array<TransactionWrapper>} Array of transaction wrappers. */ getTransactionWrappers: null, isInTransaction: function () { return !!this._isInTransaction; }, /** * Executes the function within a safety window. Use this for the top level * methods that result in large amounts of computation/mutations that would * need to be safety checked. The optional arguments helps prevent the need * to bind in many cases. * * @param {function} method Member of scope to call. * @param {Object} scope Scope to invoke from. * @param {Object?=} a Argument to pass to the method. * @param {Object?=} b Argument to pass to the method. * @param {Object?=} c Argument to pass to the method. * @param {Object?=} d Argument to pass to the method. * @param {Object?=} e Argument to pass to the method. * @param {Object?=} f Argument to pass to the method. * * @return {*} Return value from `method`. */ perform: function (method, scope, a, b, c, d, e, f) { !!this.isInTransaction() ? "development" !== 'production' ? invariant(false, 'Transaction.perform(...): Cannot initialize a transaction when there is already an outstanding transaction.') : _prodInvariant('27') : void 0; var errorThrown; var ret; try { this._isInTransaction = true; // Catching errors makes debugging more difficult, so we start with // errorThrown set to true before setting it to false after calling // close -- if it's still set to true in the finally block, it means // one of these calls threw. errorThrown = true; this.initializeAll(0); ret = method.call(scope, a, b, c, d, e, f); errorThrown = false; } finally { try { if (errorThrown) { // If `method` throws, prefer to show that stack trace over any thrown // by invoking `closeAll`. try { this.closeAll(0); } catch (err) {} } else { // Since `method` didn't throw, we don't want to silence the exception // here. this.closeAll(0); } } finally { this._isInTransaction = false; } } return ret; }, initializeAll: function (startIndex) { var transactionWrappers = this.transactionWrappers; for (var i = startIndex; i < transactionWrappers.length; i++) { var wrapper = transactionWrappers[i]; try { // Catching errors makes debugging more difficult, so we start with the // OBSERVED_ERROR state before overwriting it with the real return value // of initialize -- if it's still set to OBSERVED_ERROR in the finally // block, it means wrapper.initialize threw. this.wrapperInitData[i] = OBSERVED_ERROR; this.wrapperInitData[i] = wrapper.initialize ? wrapper.initialize.call(this) : null; } finally { if (this.wrapperInitData[i] === OBSERVED_ERROR) { // The initializer for wrapper i threw an error; initialize the // remaining wrappers but silence any exceptions from them to ensure // that the first error is the one to bubble up. try { this.initializeAll(i + 1); } catch (err) {} } } } }, /** * Invokes each of `this.transactionWrappers.close[i]` functions, passing into * them the respective return values of `this.transactionWrappers.init[i]` * (`close`rs that correspond to initializers that failed will not be * invoked). */ closeAll: function (startIndex) { !this.isInTransaction() ? "development" !== 'production' ? invariant(false, 'Transaction.closeAll(): Cannot close transaction when none are open.') : _prodInvariant('28') : void 0; var transactionWrappers = this.transactionWrappers; for (var i = startIndex; i < transactionWrappers.length; i++) { var wrapper = transactionWrappers[i]; var initData = this.wrapperInitData[i]; var errorThrown; try { // Catching errors makes debugging more difficult, so we start with // errorThrown set to true before setting it to false after calling // close -- if it's still set to true in the finally block, it means // wrapper.close threw. errorThrown = true; if (initData !== OBSERVED_ERROR && wrapper.close) { wrapper.close.call(this, initData); } errorThrown = false; } finally { if (errorThrown) { // The closer for wrapper i threw an error; close the remaining // wrappers but silence any exceptions from them to ensure that the // first error is the one to bubble up. try { this.closeAll(i + 1); } catch (e) {} } } } this.wrapperInitData.length = 0; } }; module.exports = TransactionImpl; },{"124":124,"149":149}],98:[function(_dereq_,module,exports){ /** * 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. * */ 'use strict'; var ViewportMetrics = { currentScrollLeft: 0, currentScrollTop: 0, refreshScrollValues: function (scrollPosition) { ViewportMetrics.currentScrollLeft = scrollPosition.x; ViewportMetrics.currentScrollTop = scrollPosition.y; } }; module.exports = ViewportMetrics; },{}],99:[function(_dereq_,module,exports){ /** * Copyright 2014-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'; var _prodInvariant = _dereq_(124); var invariant = _dereq_(149); /** * Accumulates items that must not be null or undefined into the first one. This * is used to conserve memory by avoiding array allocations, and thus sacrifices * API cleanness. Since `current` can be null before being passed in and not * null after this function, make sure to assign it back to `current`: * * `a = accumulateInto(a, b);` * * This API should be sparingly used. Try `accumulate` for something cleaner. * * @return {*|array<*>} An accumulation of items. */ function accumulateInto(current, next) { !(next != null) ? "development" !== 'production' ? invariant(false, 'accumulateInto(...): Accumulated items must not be null or undefined.') : _prodInvariant('30') : void 0; if (current == null) { return next; } // Both are not empty. Warning: Never call x.concat(y) when you are not // certain that x is an Array (x could be a string with concat method). if (Array.isArray(current)) { if (Array.isArray(next)) { current.push.apply(current, next); return current; } current.push(next); return current; } if (Array.isArray(next)) { // A bit too dangerous to mutate `next`. return [current].concat(next); } return [current, next]; } module.exports = accumulateInto; },{"124":124,"149":149}],100:[function(_dereq_,module,exports){ /** * 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. * * */ 'use strict'; var MOD = 65521; // adler32 is not cryptographically strong, and is only used to sanity check that // markup generated on the server matches the markup generated on the client. // This implementation (a modified version of the SheetJS version) has been optimized // for our use case, at the expense of conforming to the adler32 specification // for non-ascii inputs. function adler32(data) { var a = 1; var b = 0; var i = 0; var l = data.length; var m = l & ~0x3; while (i < m) { var n = Math.min(i + 4096, m); for (; i < n; i += 4) { b += (a += data.charCodeAt(i)) + (a += data.charCodeAt(i + 1)) + (a += data.charCodeAt(i + 2)) + (a += data.charCodeAt(i + 3)); } a %= MOD; b %= MOD; } for (; i < l; i++) { b += a += data.charCodeAt(i); } a %= MOD; b %= MOD; return a | b << 16; } module.exports = adler32; },{}],101:[function(_dereq_,module,exports){ (function (process){ /** * 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. * */ 'use strict'; var _prodInvariant = _dereq_(124); var ReactPropTypeLocationNames = _dereq_(68); var invariant = _dereq_(149); var warning = _dereq_(156); var ReactComponentTreeHook; if (typeof process !== 'undefined' && process.env && "development" === 'test') { // Temporary hack. // Inline requires don't work well with Jest: // https://github.com/facebook/react/issues/7240 // Remove the inline requires when we don't need them anymore: // https://github.com/facebook/react/pull/7178 ReactComponentTreeHook = _dereq_(131); } var loggedTypeFailures = {}; /** * Assert that the values match with the type specs. * Error messages are memorized and will only be shown once. * * @param {object} typeSpecs Map of name to a ReactPropType * @param {object} values Runtime values that need to be type-checked * @param {string} location e.g. "prop", "context", "child context" * @param {string} componentName Name of the component for error messages. * @param {?object} element The React element that is being type-checked * @param {?number} workInProgressOrDebugID The React component instance that is being type-checked * @private */ function checkReactTypeSpec(typeSpecs, values, location, componentName, element, // It is only safe to pass fiber if it is the work-in-progress version, and workInProgressOrDebugID) { for (var typeSpecName in typeSpecs) { if (typeSpecs.hasOwnProperty(typeSpecName)) { var error; // Prop type validation may throw. In case they do, we don't want to // fail the render phase where it didn't fail before. So we log it. // After these have been cleaned up, we'll let them throw. try { // This is intentionally an invariant that gets caught. It's the same // behavior as without this statement except with a better message. !(typeof typeSpecs[typeSpecName] === 'function') ? "development" !== 'production' ? invariant(false, '%s: %s type `%s` is invalid; it must be a function, usually from React.PropTypes.', componentName || 'React class', ReactPropTypeLocationNames[location], typeSpecName) : _prodInvariant('84', componentName || 'React class', ReactPropTypeLocationNames[location], typeSpecName) : void 0; error = typeSpecs[typeSpecName](values, typeSpecName, componentName, location); } catch (ex) { error = ex; } "development" !== 'production' ? warning(!error || error instanceof Error, '%s: type specification of %s `%s` is invalid; the type checker ' + 'function must return `null` or an `Error` but returned a %s. ' + 'You may have forgotten to pass an argument to the type checker ' + 'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and ' + 'shape all require an argument).', componentName || 'React class', ReactPropTypeLocationNames[location], typeSpecName, typeof error) : void 0; if (error instanceof Error && !(error.message in loggedTypeFailures)) { // Only monitor this failure once because there tends to be a lot of the // same error. loggedTypeFailures[error.message] = true; var componentStackInfo = ''; if ("development" !== 'production') { if (!ReactComponentTreeHook) { ReactComponentTreeHook = _dereq_(131); } if (workInProgressOrDebugID != null) { if (typeof workInProgressOrDebugID === 'number') { // DebugID from Stack. var debugID = workInProgressOrDebugID; componentStackInfo = ReactComponentTreeHook.getStackAddendumByID(debugID); } else if (typeof workInProgressOrDebugID.tag === 'number') { // This is a Fiber. // The stack will only be correct if this is a work in progress // version and we're calling it during reconciliation. var workInProgress = workInProgressOrDebugID; componentStackInfo = ReactComponentTreeHook.getStackAddendumByWorkInProgressFiber(workInProgress); } } else if (element !== null) { componentStackInfo = ReactComponentTreeHook.getCurrentStackAddendum(element); } } "development" !== 'production' ? warning(false, 'Failed %s type: %s%s', location, error.message, componentStackInfo) : void 0; } } } } module.exports = checkReactTypeSpec; }).call(this,undefined) },{"124":124,"131":131,"149":149,"156":156,"68":68}],102:[function(_dereq_,module,exports){ /** * 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. * */ /* globals MSApp */ 'use strict'; /** * Create a function which has 'unsafe' privileges (required by windows8 apps) */ var createMicrosoftUnsafeLocalFunction = function (func) { if (typeof MSApp !== 'undefined' && MSApp.execUnsafeLocalFunction) { return function (arg0, arg1, arg2, arg3) { MSApp.execUnsafeLocalFunction(function () { return func(arg0, arg1, arg2, arg3); }); }; } else { return func; } }; module.exports = createMicrosoftUnsafeLocalFunction; },{}],103:[function(_dereq_,module,exports){ /** * 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. * */ 'use strict'; var CSSProperty = _dereq_(4); var isUnitlessNumber = CSSProperty.isUnitlessNumber; /** * Convert a value into the proper css writable value. The style name `name` * should be logical (no hyphens), as specified * in `CSSProperty.isUnitlessNumber`. * * @param {string} name CSS property name such as `topMargin`. * @param {*} value CSS property value such as `10px`. * @param {ReactDOMComponent} component * @return {string} Normalized style value with dimensions applied. */ function dangerousStyleValue(name, value, component) { // Note that we've removed escapeTextForBrowser() calls here since the // whole string will be escaped when the attribute is injected into // the markup. If you provide unsafe user data here they can inject // arbitrary CSS which may be problematic (I couldn't repro this): // https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet // http://www.thespanner.co.uk/2007/11/26/ultimate-xss-css-injection/ // This is not an XSS hole but instead a potential CSS injection issue // which has lead to a greater discussion about how we're going to // trust URLs moving forward. See #2115901 var isEmpty = value == null || typeof value === 'boolean' || value === ''; if (isEmpty) { return ''; } if (typeof value === 'number' && value !== 0 && !(isUnitlessNumber.hasOwnProperty(name) && isUnitlessNumber[name])) { return value + 'px'; // Presumes implicit 'px' suffix for unitless numbers } return ('' + value).trim(); } module.exports = dangerousStyleValue; },{"4":4}],104:[function(_dereq_,module,exports){ /** * Copyright 2016-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. * * Based on the escape-html library, which is used under the MIT License below: * * Copyright (c) 2012-2013 TJ Holowaychuk * Copyright (c) 2015 Andreas Lubbe * Copyright (c) 2015 Tiancheng "Timothy" Gu * * 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. * */ 'use strict'; // code copied and modified from escape-html /** * Module variables. * @private */ var matchHtmlRegExp = /["'&<>]/; /** * Escape special characters in the given string of html. * * @param {string} string The string to escape for inserting into HTML * @return {string} * @public */ function escapeHtml(string) { var str = '' + string; var match = matchHtmlRegExp.exec(str); if (!match) { return str; } var escape; var html = ''; var index = 0; var lastIndex = 0; for (index = match.index; index < str.length; index++) { switch (str.charCodeAt(index)) { case 34: // " escape = '&quot;'; break; case 38: // & escape = '&amp;'; break; case 39: // ' escape = '&#x27;'; // modified from escape-html; used to be '&#39' break; case 60: // < escape = '&lt;'; break; case 62: // > escape = '&gt;'; break; default: continue; } if (lastIndex !== index) { html += str.substring(lastIndex, index); } lastIndex = index + 1; html += escape; } return lastIndex !== index ? html + str.substring(lastIndex, index) : html; } // end code copied and modified from escape-html /** * Escapes text to prevent scripting attacks. * * @param {*} text Text value to escape. * @return {string} An escaped string. */ function escapeTextContentForBrowser(text) { if (typeof text === 'boolean' || typeof text === 'number') { // this shortcircuit helps perf for types that we know will never have // special characters, especially given that this function is used often // for numeric dom ids. return '' + text; } return escapeHtml(text); } module.exports = escapeTextContentForBrowser; },{}],105:[function(_dereq_,module,exports){ 'use strict'; var _prodInvariant = _dereq_(124); /** * 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. * * */ var ReactCurrentOwner = _dereq_(132); var ReactInstanceMap = _dereq_(61); var getComponentName = _dereq_(108); var invariant = _dereq_(149); var warning = _dereq_(156); var findFiber = function (arg) { invariant(false, 'Missing injection for fiber findDOMNode'); }; var findStack = function (arg) { invariant(false, 'Missing injection for stack findDOMNode'); }; var findDOMNode = function (componentOrElement) { if ("development" !== 'production') { var owner = ReactCurrentOwner.current; if (owner !== null && '_warnedAboutRefsInRender' in owner) { "development" !== 'production' ? warning(owner._warnedAboutRefsInRender, '%s is accessing findDOMNode inside its render(). ' + 'render() should be a pure function of props and state. It should ' + 'never access something that requires stale data from the previous ' + 'render, such as refs. Move this logic to componentDidMount and ' + 'componentDidUpdate instead.', getComponentName(owner) || 'A component') : void 0; owner._warnedAboutRefsInRender = true; } } if (componentOrElement == null) { return null; } if (componentOrElement.nodeType === 1) { return componentOrElement; } var inst = ReactInstanceMap.get(componentOrElement); if (inst) { if (typeof inst.tag === 'number') { return findFiber(inst); } else { return findStack(inst); } } if (typeof componentOrElement.render === 'function') { invariant(false, 'Unable to find node on an unmounted component.'); } else { !false ? "development" !== 'production' ? invariant(false, 'Element appears to be neither ReactComponent nor DOMNode (keys: %s)', Object.keys(componentOrElement)) : _prodInvariant('45', Object.keys(componentOrElement)) : void 0; } }; findDOMNode._injectFiber = function (fn) { findFiber = fn; }; findDOMNode._injectStack = function (fn) { findStack = fn; }; module.exports = findDOMNode; },{"108":108,"124":124,"132":132,"149":149,"156":156,"61":61}],106:[function(_dereq_,module,exports){ (function (process){ /** * 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. * * */ 'use strict'; var KeyEscapeUtils = _dereq_(22); var traverseAllChildren = _dereq_(128); var warning = _dereq_(156); var ReactComponentTreeHook; if (typeof process !== 'undefined' && process.env && "development" === 'test') { // Temporary hack. // Inline requires don't work well with Jest: // https://github.com/facebook/react/issues/7240 // Remove the inline requires when we don't need them anymore: // https://github.com/facebook/react/pull/7178 ReactComponentTreeHook = _dereq_(131); } /** * @param {function} traverseContext Context passed through traversal. * @param {?ReactComponent} child React child component. * @param {!string} name String name of key path to child. * @param {number=} selfDebugID Optional debugID of the current internal instance. */ function flattenSingleChildIntoContext(traverseContext, child, name, selfDebugID) { // We found a component instance. if (traverseContext && typeof traverseContext === 'object') { var result = traverseContext; var keyUnique = result[name] === undefined; if ("development" !== 'production') { if (!ReactComponentTreeHook) { ReactComponentTreeHook = _dereq_(131); } if (!keyUnique) { "development" !== 'production' ? warning(false, 'flattenChildren(...): Encountered two children with the same key, ' + '`%s`. Child keys must be unique; when two children share a key, only ' + 'the first child will be used.%s', KeyEscapeUtils.unescape(name), ReactComponentTreeHook.getStackAddendumByID(selfDebugID)) : void 0; } } if (keyUnique && child != null) { result[name] = child; } } } /** * Flattens children that are typically specified as `props.children`. Any null * children will not be included in the resulting object. * @return {!object} flattened children keyed by name. */ function flattenChildren(children, selfDebugID) { if (children == null) { return children; } var result = {}; if ("development" !== 'production') { traverseAllChildren(children, function (traverseContext, child, name) { return flattenSingleChildIntoContext(traverseContext, child, name, selfDebugID); }, result); } else { traverseAllChildren(children, flattenSingleChildIntoContext, result); } return result; } module.exports = flattenChildren; }).call(this,undefined) },{"128":128,"131":131,"156":156,"22":22}],107:[function(_dereq_,module,exports){ /** * 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. * * */ 'use strict'; /** * @param {array} arr an "accumulation" of items which is either an Array or * a single item. Useful when paired with the `accumulate` module. This is a * simple utility that allows us to reason about a collection of items, but * handling the case when there is exactly one item (and we do not need to * allocate an array). */ function forEachAccumulated(arr, cb, scope) { if (Array.isArray(arr)) { arr.forEach(cb, scope); } else if (arr) { cb.call(scope, arr); } } module.exports = forEachAccumulated; },{}],108:[function(_dereq_,module,exports){ /** * 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. * * */ 'use strict'; function getComponentName(instanceOrFiber) { if ("development" !== 'production') { if (typeof instanceOrFiber.getName === 'function') { // Stack reconciler var instance = instanceOrFiber; return instance.getName() || 'Component'; } if (typeof instanceOrFiber.tag === 'number') { // Fiber reconciler var fiber = instanceOrFiber; var type = fiber.type; if (typeof type === 'string') { return type; } if (typeof type === 'function') { return type.displayName || type.name || null; } } } return null; } module.exports = getComponentName; },{}],109:[function(_dereq_,module,exports){ /** * 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. * */ 'use strict'; /** * `charCode` represents the actual "character code" and is safe to use with * `String.fromCharCode`. As such, only keys that correspond to printable * characters produce a valid `charCode`, the only exception to this is Enter. * The Tab-key is considered non-printable and does not have a `charCode`, * presumably because it does not produce a tab-character in browsers. * * @param {object} nativeEvent Native browser event. * @return {number} Normalized `charCode` property. */ function getEventCharCode(nativeEvent) { var charCode; var keyCode = nativeEvent.keyCode; if ('charCode' in nativeEvent) { charCode = nativeEvent.charCode; // FF does not set `charCode` for the Enter-key, check against `keyCode`. if (charCode === 0 && keyCode === 13) { charCode = 13; } } else { // IE8 does not implement `charCode`, but `keyCode` has the correct value. charCode = keyCode; } // Some non-printable keys are reported in `charCode`/`keyCode`, discard them. // Must not discard the (non-)printable Enter-key. if (charCode >= 32 || charCode === 13) { return charCode; } return 0; } module.exports = getEventCharCode; },{}],110:[function(_dereq_,module,exports){ /** * 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. * */ 'use strict'; var getEventCharCode = _dereq_(109); /** * Normalization of deprecated HTML5 `key` values * @see https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent#Key_names */ var normalizeKey = { 'Esc': 'Escape', 'Spacebar': ' ', 'Left': 'ArrowLeft', 'Up': 'ArrowUp', 'Right': 'ArrowRight', 'Down': 'ArrowDown', 'Del': 'Delete', 'Win': 'OS', 'Menu': 'ContextMenu', 'Apps': 'ContextMenu', 'Scroll': 'ScrollLock', 'MozPrintableKey': 'Unidentified' }; /** * Translation from legacy `keyCode` to HTML5 `key` * Only special keys supported, all others depend on keyboard layout or browser * @see https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent#Key_names */ var translateToKey = { 8: 'Backspace', 9: 'Tab', 12: 'Clear', 13: 'Enter', 16: 'Shift', 17: 'Control', 18: 'Alt', 19: 'Pause', 20: 'CapsLock', 27: 'Escape', 32: ' ', 33: 'PageUp', 34: 'PageDown', 35: 'End', 36: 'Home', 37: 'ArrowLeft', 38: 'ArrowUp', 39: 'ArrowRight', 40: 'ArrowDown', 45: 'Insert', 46: 'Delete', 112: 'F1', 113: 'F2', 114: 'F3', 115: 'F4', 116: 'F5', 117: 'F6', 118: 'F7', 119: 'F8', 120: 'F9', 121: 'F10', 122: 'F11', 123: 'F12', 144: 'NumLock', 145: 'ScrollLock', 224: 'Meta' }; /** * @param {object} nativeEvent Native browser event. * @return {string} Normalized `key` property. */ function getEventKey(nativeEvent) { if (nativeEvent.key) { // Normalize inconsistent values reported by browsers due to // implementations of a working draft specification. // FireFox implements `key` but returns `MozPrintableKey` for all // printable characters (normalized to `Unidentified`), ignore it. var key = normalizeKey[nativeEvent.key] || nativeEvent.key; if (key !== 'Unidentified') { return key; } } // Browser does not implement `key`, polyfill as much of it as we can. if (nativeEvent.type === 'keypress') { var charCode = getEventCharCode(nativeEvent); // The enter-key is technically both printable and non-printable and can // thus be captured by `keypress`, no other non-printable key should. return charCode === 13 ? 'Enter' : String.fromCharCode(charCode); } if (nativeEvent.type === 'keydown' || nativeEvent.type === 'keyup') { // While user keyboard layout determines the actual meaning of each // `keyCode` value, almost all function keys have a universal value. return translateToKey[nativeEvent.keyCode] || 'Unidentified'; } return ''; } module.exports = getEventKey; },{"109":109}],111:[function(_dereq_,module,exports){ /** * 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. * */ 'use strict'; /** * Translation from modifier key to the associated property in the event. * @see http://www.w3.org/TR/DOM-Level-3-Events/#keys-Modifiers */ var modifierKeyToProp = { 'Alt': 'altKey', 'Control': 'ctrlKey', 'Meta': 'metaKey', 'Shift': 'shiftKey' }; // IE8 does not implement getModifierState so we simply map it to the only // modifier keys exposed by the event itself, does not support Lock-keys. // Currently, all major browsers except Chrome seems to support Lock-keys. function modifierStateGetter(keyArg) { var syntheticEvent = this; var nativeEvent = syntheticEvent.nativeEvent; if (nativeEvent.getModifierState) { return nativeEvent.getModifierState(keyArg); } var keyProp = modifierKeyToProp[keyArg]; return keyProp ? !!nativeEvent[keyProp] : false; } function getEventModifierState(nativeEvent) { return modifierStateGetter; } module.exports = getEventModifierState; },{}],112:[function(_dereq_,module,exports){ /** * 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. * */ 'use strict'; /** * Gets the target node from a native browser event by accounting for * inconsistencies in browser DOM APIs. * * @param {object} nativeEvent Native browser event. * @return {DOMEventTarget} Target node. */ function getEventTarget(nativeEvent) { var target = nativeEvent.target || nativeEvent.srcElement || window; // Normalize SVG <use> element events #4963 if (target.correspondingUseElement) { target = target.correspondingUseElement; } // Safari may fire events on text nodes (Node.TEXT_NODE is 3). // @see http://www.quirksmode.org/js/events_properties.html return target.nodeType === 3 ? target.parentNode : target; } module.exports = getEventTarget; },{}],113:[function(_dereq_,module,exports){ /** * 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. * */ 'use strict'; var ReactNodeTypes = _dereq_(66); function getHostComponentFromComposite(inst) { var type; while ((type = inst._renderedNodeType) === ReactNodeTypes.COMPOSITE) { inst = inst._renderedComponent; } if (type === ReactNodeTypes.HOST) { return inst._renderedComponent; } else if (type === ReactNodeTypes.EMPTY) { return null; } } module.exports = getHostComponentFromComposite; },{"66":66}],114:[function(_dereq_,module,exports){ /** * 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. * * */ 'use strict'; /* global Symbol */ var ITERATOR_SYMBOL = typeof Symbol === 'function' && Symbol.iterator; var FAUX_ITERATOR_SYMBOL = '@@iterator'; // Before Symbol spec. /** * Returns the iterator method function contained on the iterable object. * * Be sure to invoke the function with the iterable as context: * * var iteratorFn = getIteratorFn(myIterable); * if (iteratorFn) { * var iterator = iteratorFn.call(myIterable); * ... * } * * @param {?object} maybeIterable * @return {?function} */ function getIteratorFn(maybeIterable) { var iteratorFn = maybeIterable && (ITERATOR_SYMBOL && maybeIterable[ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL]); if (typeof iteratorFn === 'function') { return iteratorFn; } } module.exports = getIteratorFn; },{}],115:[function(_dereq_,module,exports){ /** * 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. * * */ 'use strict'; var nextDebugID = 1; function getNextDebugID() { return nextDebugID++; } module.exports = getNextDebugID; },{}],116:[function(_dereq_,module,exports){ /** * 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. * */ 'use strict'; /** * Given any node return the first leaf node without children. * * @param {DOMElement|DOMTextNode} node * @return {DOMElement|DOMTextNode} */ function getLeafNode(node) { while (node && node.firstChild) { node = node.firstChild; } return node; } /** * Get the next sibling within a container. This will walk up the * DOM if a node's siblings have been exhausted. * * @param {DOMElement|DOMTextNode} node * @return {?DOMElement|DOMTextNode} */ function getSiblingNode(node) { while (node) { if (node.nextSibling) { return node.nextSibling; } node = node.parentNode; } } /** * Get object describing the nodes which contain characters at offset. * * @param {DOMElement|DOMTextNode} root * @param {number} offset * @return {?object} */ function getNodeForCharacterOffset(root, offset) { var node = getLeafNode(root); var nodeStart = 0; var nodeEnd = 0; while (node) { if (node.nodeType === 3) { nodeEnd = nodeStart + node.textContent.length; if (nodeStart <= offset && nodeEnd >= offset) { return { node: node, offset: offset - nodeStart }; } nodeStart = nodeEnd; } node = getLeafNode(getSiblingNode(node)); } } module.exports = getNodeForCharacterOffset; },{}],117:[function(_dereq_,module,exports){ /** * 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. * */ 'use strict'; var ExecutionEnvironment = _dereq_(135); var contentKey = null; /** * Gets the key used to access text content on a DOM node. * * @return {?string} Key used to access text content. * @internal */ function getTextContentAccessor() { if (!contentKey && ExecutionEnvironment.canUseDOM) { // Prefer textContent to innerText because many browsers support both but // SVG <text> elements don't support innerText even when <div> does. contentKey = 'textContent' in document.documentElement ? 'textContent' : 'innerText'; } return contentKey; } module.exports = getTextContentAccessor; },{"135":135}],118:[function(_dereq_,module,exports){ /** * 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. * */ 'use strict'; var ExecutionEnvironment = _dereq_(135); /** * Generate a mapping of standard vendor prefixes using the defined style property and event name. * * @param {string} styleProp * @param {string} eventName * @returns {object} */ function makePrefixMap(styleProp, eventName) { var prefixes = {}; prefixes[styleProp.toLowerCase()] = eventName.toLowerCase(); prefixes['Webkit' + styleProp] = 'webkit' + eventName; prefixes['Moz' + styleProp] = 'moz' + eventName; prefixes['ms' + styleProp] = 'MS' + eventName; prefixes['O' + styleProp] = 'o' + eventName.toLowerCase(); return prefixes; } /** * A list of event names to a configurable list of vendor prefixes. */ var vendorPrefixes = { animationend: makePrefixMap('Animation', 'AnimationEnd'), animationiteration: makePrefixMap('Animation', 'AnimationIteration'), animationstart: makePrefixMap('Animation', 'AnimationStart'), transitionend: makePrefixMap('Transition', 'TransitionEnd') }; /** * Event names that have already been detected and prefixed (if applicable). */ var prefixedEventNames = {}; /** * Element to check for prefixes on. */ var style = {}; /** * Bootstrap if a DOM exists. */ if (ExecutionEnvironment.canUseDOM) { style = document.createElement('div').style; // On some platforms, in particular some releases of Android 4.x, // the un-prefixed "animation" and "transition" properties are defined on the // style object but the events that fire will still be prefixed, so we need // to check if the un-prefixed events are usable, and if not remove them from the map. if (!('AnimationEvent' in window)) { delete vendorPrefixes.animationend.animation; delete vendorPrefixes.animationiteration.animation; delete vendorPrefixes.animationstart.animation; } // Same as above if (!('TransitionEvent' in window)) { delete vendorPrefixes.transitionend.transition; } } /** * Attempts to determine the correct vendor prefixed event name. * * @param {string} eventName * @returns {string} */ function getVendorPrefixedEventName(eventName) { if (prefixedEventNames[eventName]) { return prefixedEventNames[eventName]; } else if (!vendorPrefixes[eventName]) { return eventName; } var prefixMap = vendorPrefixes[eventName]; for (var styleProp in prefixMap) { if (prefixMap.hasOwnProperty(styleProp) && styleProp in style) { return prefixedEventNames[eventName] = prefixMap[styleProp]; } } return ''; } module.exports = getVendorPrefixedEventName; },{"135":135}],119:[function(_dereq_,module,exports){ /** * 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. * * */ 'use strict'; var ReactDOMComponentTree = _dereq_(34); function isCheckable(elem) { var type = elem.type; var nodeName = elem.nodeName; return nodeName && nodeName.toLowerCase() === 'input' && (type === 'checkbox' || type === 'radio'); } function getTracker(inst) { if (typeof inst.tag === 'number') { inst = inst.stateNode; } return inst._wrapperState.valueTracker; } function attachTracker(inst, tracker) { inst._wrapperState.valueTracker = tracker; } function detachTracker(inst) { delete inst._wrapperState.valueTracker; } function getValueFromNode(node) { var value; if (node) { value = isCheckable(node) ? '' + node.checked : node.value; } return value; } function trackValueOnNode(node, inst) { var valueField = isCheckable(node) ? 'checked' : 'value'; var descriptor = Object.getOwnPropertyDescriptor(node.constructor.prototype, valueField); var currentValue = '' + node[valueField]; // if someone has already defined a value or Safari, then bail // and don't track value will cause over reporting of changes, // but it's better then a hard failure // (needed for certain tests that spyOn input values and Safari) if (node.hasOwnProperty(valueField) || typeof descriptor.get !== 'function' || typeof descriptor.set !== 'function') { return; } Object.defineProperty(node, valueField, { enumerable: descriptor.enumerable, configurable: true, get: function () { return descriptor.get.call(this); }, set: function (value) { currentValue = '' + value; descriptor.set.call(this, value); } }); var tracker = { getValue: function () { return currentValue; }, setValue: function (value) { currentValue = '' + value; }, stopTracking: function () { detachTracker(inst); delete node[valueField]; } }; return tracker; } var inputValueTracking = { // exposed for testing _getTrackerFromNode: function (node) { return getTracker(ReactDOMComponentTree.getInstanceFromNode(node)); }, trackNode: function (node) { if (node._wrapperState.valueTracker) { return; } node._wrapperState.valueTracker = trackValueOnNode(node, node); }, track: function (inst) { if (getTracker(inst)) { return; } var node = ReactDOMComponentTree.getNodeFromInstance(inst); attachTracker(inst, trackValueOnNode(node, inst)); }, updateValueIfChanged: function (inst) { if (!inst) { return false; } var tracker = getTracker(inst); if (!tracker) { if (typeof inst.tag === 'number') { inputValueTracking.trackNode(inst.stateNode); } else { inputValueTracking.track(inst); } return true; } var lastValue = tracker.getValue(); var nextValue = getValueFromNode(ReactDOMComponentTree.getNodeFromInstance(inst)); if (nextValue !== lastValue) { tracker.setValue(nextValue); return true; } return false; }, stopTracking: function (inst) { var tracker = getTracker(inst); if (tracker) { tracker.stopTracking(); } } }; module.exports = inputValueTracking; },{"34":34}],120:[function(_dereq_,module,exports){ /** * 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. * */ 'use strict'; var _prodInvariant = _dereq_(124), _assign = _dereq_(157); var ReactCompositeComponent = _dereq_(28); var ReactEmptyComponent = _dereq_(52); var ReactHostComponent = _dereq_(58); var getNextDebugID = _dereq_(115); var invariant = _dereq_(149); var warning = _dereq_(156); // To avoid a cyclic dependency, we create the final class in this module var ReactCompositeComponentWrapper = function (element) { this.construct(element); }; _assign(ReactCompositeComponentWrapper.prototype, ReactCompositeComponent, { _instantiateReactComponent: instantiateReactComponent }); function getDeclarationErrorAddendum(owner) { if (owner) { var name = owner.getName(); if (name) { return ' Check the render method of `' + name + '`.'; } } return ''; } /** * Check if the type reference is a known internal type. I.e. not a user * provided composite type. * * @param {function} type * @return {boolean} Returns true if this is a valid internal type. */ function isInternalComponentType(type) { return typeof type === 'function' && typeof type.prototype !== 'undefined' && typeof type.prototype.mountComponent === 'function' && typeof type.prototype.receiveComponent === 'function'; } /** * Given a ReactNode, create an instance that will actually be mounted. * * @param {ReactNode} node * @param {boolean} shouldHaveDebugID * @return {object} A new instance of the element's constructor. * @protected */ function instantiateReactComponent(node, shouldHaveDebugID) { var instance; if (node === null || node === false) { instance = ReactEmptyComponent.create(instantiateReactComponent); } else if (typeof node === 'object') { var element = node; var type = element.type; if (typeof type !== 'function' && typeof type !== 'string') { var info = ''; if ("development" !== 'production') { if (type === undefined || typeof type === 'object' && type !== null && Object.keys(type).length === 0) { info += ' You likely forgot to export your component from the file ' + 'it\'s defined in.'; } } info += getDeclarationErrorAddendum(element._owner); !false ? "development" !== 'production' ? invariant(false, 'Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: %s.%s', type == null ? type : typeof type, info) : _prodInvariant('130', type == null ? type : typeof type, info) : void 0; } // Special case string values if (typeof element.type === 'string') { instance = ReactHostComponent.createInternalComponent(element); } else if (isInternalComponentType(element.type)) { // This is temporarily available for custom components that are not string // representations. I.e. ART. Once those are updated to use the string // representation, we can drop this code path. instance = new element.type(element); // We renamed this. Allow the old name for compat. :( if (!instance.getHostNode) { instance.getHostNode = instance.getNativeNode; } } else { instance = new ReactCompositeComponentWrapper(element); } } else if (typeof node === 'string' || typeof node === 'number') { instance = ReactHostComponent.createInstanceForText(node); } else { !false ? "development" !== 'production' ? invariant(false, 'Encountered invalid React node of type %s', typeof node) : _prodInvariant('131', typeof node) : void 0; } if ("development" !== 'production') { "development" !== 'production' ? warning(typeof instance.mountComponent === 'function' && typeof instance.receiveComponent === 'function' && typeof instance.getHostNode === 'function' && typeof instance.unmountComponent === 'function', 'Only React Components can be mounted.') : void 0; } // These two fields are used by the DOM and ART diffing algorithms // respectively. Instead of using expandos on components, we should be // storing the state needed by the diffing algorithms elsewhere. instance._mountIndex = 0; instance._mountImage = null; if ("development" !== 'production') { instance._debugID = shouldHaveDebugID ? getNextDebugID() : 0; } // Internal instances should fully constructed at this point, so they should // not get any new fields added to them at this point. if ("development" !== 'production') { if (Object.preventExtensions) { Object.preventExtensions(instance); } } return instance; } module.exports = instantiateReactComponent; },{"115":115,"124":124,"149":149,"156":156,"157":157,"28":28,"52":52,"58":58}],121:[function(_dereq_,module,exports){ /** * 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. * */ 'use strict'; var ExecutionEnvironment = _dereq_(135); var useHasFeature; if (ExecutionEnvironment.canUseDOM) { useHasFeature = document.implementation && document.implementation.hasFeature && // always returns true in newer browsers as per the standard. // @see http://dom.spec.whatwg.org/#dom-domimplementation-hasfeature document.implementation.hasFeature('', '') !== true; } /** * Checks if an event is supported in the current execution environment. * * NOTE: This will not work correctly for non-generic events such as `change`, * `reset`, `load`, `error`, and `select`. * * Borrows from Modernizr. * * @param {string} eventNameSuffix Event name, e.g. "click". * @param {?boolean} capture Check if the capture phase is supported. * @return {boolean} True if the event is supported. * @internal * @license Modernizr 3.0.0pre (Custom Build) | MIT */ function isEventSupported(eventNameSuffix, capture) { if (!ExecutionEnvironment.canUseDOM || capture && !('addEventListener' in document)) { return false; } var eventName = 'on' + eventNameSuffix; var isSupported = eventName in document; if (!isSupported) { var element = document.createElement('div'); element.setAttribute(eventName, 'return;'); isSupported = typeof element[eventName] === 'function'; } if (!isSupported && useHasFeature && eventNameSuffix === 'wheel') { // This is the only way to test support for the `wheel` event in IE9+. isSupported = document.implementation.hasFeature('Events.wheel', '3.0'); } return isSupported; } module.exports = isEventSupported; },{"135":135}],122:[function(_dereq_,module,exports){ /** * 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. * * */ 'use strict'; /** * @see http://www.whatwg.org/specs/web-apps/current-work/multipage/the-input-element.html#input-type-attr-summary */ var supportedInputTypes = { 'color': true, 'date': true, 'datetime': true, 'datetime-local': true, 'email': true, 'month': true, 'number': true, 'password': true, 'range': true, 'search': true, 'tel': true, 'text': true, 'time': true, 'url': true, 'week': true }; function isTextInputElement(elem) { var nodeName = elem && elem.nodeName && elem.nodeName.toLowerCase(); if (nodeName === 'input') { return !!supportedInputTypes[elem.type]; } if (nodeName === 'textarea') { return true; } return false; } module.exports = isTextInputElement; },{}],123:[function(_dereq_,module,exports){ /** * 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. * */ 'use strict'; var escapeTextContentForBrowser = _dereq_(104); /** * Escapes attribute value to prevent scripting attacks. * * @param {*} value Value to escape. * @return {string} An escaped string. */ function quoteAttributeValueForBrowser(value) { return '"' + escapeTextContentForBrowser(value) + '"'; } module.exports = quoteAttributeValueForBrowser; },{"104":104}],124:[function(_dereq_,module,exports){ /** * 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. * * */ 'use strict'; /** * WARNING: DO NOT manually require this module. * This is a replacement for `invariant(...)` used by the error code system * and will _only_ be required by the corresponding babel pass. * It always throws. */ function reactProdInvariant(code) { var argCount = arguments.length - 1; var message = 'Minified React error #' + code + '; visit ' + 'http://facebook.github.io/react/docs/error-decoder.html?invariant=' + code; for (var argIdx = 0; argIdx < argCount; argIdx++) { message += '&args[]=' + encodeURIComponent(arguments[argIdx + 1]); } message += ' for the full message or use the non-minified dev environment' + ' for full errors and additional helpful warnings.'; var error = new Error(message); error.name = 'Invariant Violation'; error.framesToPop = 1; // we don't care about reactProdInvariant's own frame throw error; } module.exports = reactProdInvariant; },{}],125:[function(_dereq_,module,exports){ /** * 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. * */ 'use strict'; var ExecutionEnvironment = _dereq_(135); var DOMNamespaces = _dereq_(11); var WHITESPACE_TEST = /^[ \r\n\t\f]/; var NONVISIBLE_TEST = /<(!--|link|noscript|meta|script|style)[ \r\n\t\f\/>]/; var createMicrosoftUnsafeLocalFunction = _dereq_(102); // SVG temp container for IE lacking innerHTML var reusableSVGContainer; /** * Set the innerHTML property of a node, ensuring that whitespace is preserved * even in IE8. * * @param {DOMElement} node * @param {string} html * @internal */ var setInnerHTML = createMicrosoftUnsafeLocalFunction(function (node, html) { // IE does not have innerHTML for SVG nodes, so instead we inject the // new markup in a temp node and then move the child nodes across into // the target node if (node.namespaceURI === DOMNamespaces.svg && !('innerHTML' in node)) { reusableSVGContainer = reusableSVGContainer || document.createElement('div'); reusableSVGContainer.innerHTML = '<svg>' + html + '</svg>'; var svgNode = reusableSVGContainer.firstChild; while (svgNode.firstChild) { node.appendChild(svgNode.firstChild); } } else { node.innerHTML = html; } }); if (ExecutionEnvironment.canUseDOM) { // IE8: When updating a just created node with innerHTML only leading // whitespace is removed. When updating an existing node with innerHTML // whitespace in root TextNodes is also collapsed. // @see quirksmode.org/bugreports/archives/2004/11/innerhtml_and_t.html // Feature detection; only IE8 is known to behave improperly like this. var testElement = document.createElement('div'); testElement.innerHTML = ' '; if (testElement.innerHTML === '') { setInnerHTML = function (node, html) { // Magic theory: IE8 supposedly differentiates between added and updated // nodes when processing innerHTML, innerHTML on updated nodes suffers // from worse whitespace behavior. Re-adding a node like this triggers // the initial and more favorable whitespace behavior. // TODO: What to do on a detached node? if (node.parentNode) { node.parentNode.replaceChild(node, node); } // We also implement a workaround for non-visible tags disappearing into // thin air on IE8, this only happens if there is no visible text // in-front of the non-visible tags. Piggyback on the whitespace fix // and simply check if any non-visible tags appear in the source. if (WHITESPACE_TEST.test(html) || html[0] === '<' && NONVISIBLE_TEST.test(html)) { // Recover leading whitespace by temporarily prepending any character. // \uFEFF has the potential advantage of being zero-width/invisible. // UglifyJS drops U+FEFF chars when parsing, so use String.fromCharCode // in hopes that this is preserved even if "\uFEFF" is transformed to // the actual Unicode character (by Babel, for example). // https://github.com/mishoo/UglifyJS2/blob/v2.4.20/lib/parse.js#L216 node.innerHTML = String.fromCharCode(0xFEFF) + html; // deleteData leaves an empty `TextNode` which offsets the index of all // children. Definitely want to avoid this. var textNode = node.firstChild; if (textNode.data.length === 1) { node.removeChild(textNode); } else { textNode.deleteData(0, 1); } } else { node.innerHTML = html; } }; } testElement = null; } module.exports = setInnerHTML; },{"102":102,"11":11,"135":135}],126:[function(_dereq_,module,exports){ /** * 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. * */ 'use strict'; var ExecutionEnvironment = _dereq_(135); var escapeTextContentForBrowser = _dereq_(104); var setInnerHTML = _dereq_(125); /** * Set the textContent property of a node, ensuring that whitespace is preserved * even in IE8. innerText is a poor substitute for textContent and, among many * issues, inserts <br> instead of the literal newline chars. innerHTML behaves * as it should. * * @param {DOMElement} node * @param {string} text * @internal */ var setTextContent = function (node, text) { if (text) { var firstChild = node.firstChild; if (firstChild && firstChild === node.lastChild && firstChild.nodeType === 3) { firstChild.nodeValue = text; return; } } node.textContent = text; }; if (ExecutionEnvironment.canUseDOM) { if (!('textContent' in document.documentElement)) { setTextContent = function (node, text) { if (node.nodeType === 3) { node.nodeValue = text; return; } setInnerHTML(node, escapeTextContentForBrowser(text)); }; } } module.exports = setTextContent; },{"104":104,"125":125,"135":135}],127:[function(_dereq_,module,exports){ /** * 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. * */ 'use strict'; /** * Given a `prevElement` and `nextElement`, determines if the existing * instance should be updated as opposed to being destroyed or replaced by a new * instance. Both arguments are elements. This ensures that this logic can * operate on stateless trees without any backing instance. * * @param {?object} prevElement * @param {?object} nextElement * @return {boolean} True if the existing instance should be updated. * @protected */ function shouldUpdateReactComponent(prevElement, nextElement) { var prevEmpty = prevElement === null || prevElement === false; var nextEmpty = nextElement === null || nextElement === false; if (prevEmpty || nextEmpty) { return prevEmpty === nextEmpty; } var prevType = typeof prevElement; var nextType = typeof nextElement; if (prevType === 'string' || prevType === 'number') { return nextType === 'string' || nextType === 'number'; } else { return nextType === 'object' && prevElement.type === nextElement.type && prevElement.key === nextElement.key; } } module.exports = shouldUpdateReactComponent; },{}],128:[function(_dereq_,module,exports){ /** * 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. * */ 'use strict'; var _prodInvariant = _dereq_(124); var ReactCurrentOwner = _dereq_(132); var REACT_ELEMENT_TYPE = _dereq_(51); var getIteratorFn = _dereq_(114); var invariant = _dereq_(149); var KeyEscapeUtils = _dereq_(22); var warning = _dereq_(156); var SEPARATOR = '.'; var SUBSEPARATOR = ':'; /** * This is inlined from ReactElement since this file is shared between * isomorphic and renderers. We could extract this to a * */ /** * TODO: Test that a single child and an array with one item have the same key * pattern. */ var didWarnAboutMaps = false; /** * Generate a key string that identifies a component within a set. * * @param {*} component A component that could contain a manual key. * @param {number} index Index that is used if a manual key is not provided. * @return {string} */ function getComponentKey(component, index) { // Do some typechecking here since we call this blindly. We want to ensure // that we don't block potential future ES APIs. if (component && typeof component === 'object' && component.key != null) { // Explicit key return KeyEscapeUtils.escape(component.key); } // Implicit key determined by the index in the set return index.toString(36); } /** * @param {?*} children Children tree container. * @param {!string} nameSoFar Name of the key path so far. * @param {!function} callback Callback to invoke with each child found. * @param {?*} traverseContext Used to pass information throughout the traversal * process. * @return {!number} The number of children in this subtree. */ function traverseAllChildrenImpl(children, nameSoFar, callback, traverseContext) { var type = typeof children; if (type === 'undefined' || type === 'boolean') { // All of the above are perceived as null. children = null; } if (children === null || type === 'string' || type === 'number' || // The following is inlined from ReactElement. This means we can optimize // some checks. React Fiber also inlines this logic for similar purposes. type === 'object' && children.$$typeof === REACT_ELEMENT_TYPE) { callback(traverseContext, children, // If it's the only child, treat the name as if it was wrapped in an array // so that it's consistent if the number of children grows. nameSoFar === '' ? SEPARATOR + getComponentKey(children, 0) : nameSoFar); return 1; } var child; var nextName; var subtreeCount = 0; // Count of children found in the current subtree. var nextNamePrefix = nameSoFar === '' ? SEPARATOR : nameSoFar + SUBSEPARATOR; if (Array.isArray(children)) { for (var i = 0; i < children.length; i++) { child = children[i]; nextName = nextNamePrefix + getComponentKey(child, i); subtreeCount += traverseAllChildrenImpl(child, nextName, callback, traverseContext); } } else { var iteratorFn = getIteratorFn(children); if (iteratorFn) { var iterator = iteratorFn.call(children); var step; if (iteratorFn !== children.entries) { var ii = 0; while (!(step = iterator.next()).done) { child = step.value; nextName = nextNamePrefix + getComponentKey(child, ii++); subtreeCount += traverseAllChildrenImpl(child, nextName, callback, traverseContext); } } else { if ("development" !== 'production') { var mapsAsChildrenAddendum = ''; if (ReactCurrentOwner.current) { var mapsAsChildrenOwnerName = ReactCurrentOwner.current.getName(); if (mapsAsChildrenOwnerName) { mapsAsChildrenAddendum = ' Check the render method of `' + mapsAsChildrenOwnerName + '`.'; } } "development" !== 'production' ? warning(didWarnAboutMaps, 'Using Maps as children is not yet fully supported. It is an ' + 'experimental feature that might be removed. Convert it to a ' + 'sequence / iterable of keyed ReactElements instead.%s', mapsAsChildrenAddendum) : void 0; didWarnAboutMaps = true; } // Iterator will provide entry [k,v] tuples rather than values. while (!(step = iterator.next()).done) { var entry = step.value; if (entry) { child = entry[1]; nextName = nextNamePrefix + KeyEscapeUtils.escape(entry[0]) + SUBSEPARATOR + getComponentKey(child, 0); subtreeCount += traverseAllChildrenImpl(child, nextName, callback, traverseContext); } } } } else if (type === 'object') { var addendum = ''; if ("development" !== 'production') { addendum = ' If you meant to render a collection of children, use an array ' + 'instead or wrap the object using createFragment(object) from the ' + 'React add-ons.'; if (children._isReactElement) { addendum = ' It looks like you\'re using an element created by a different ' + 'version of React. Make sure to use only one copy of React.'; } if (ReactCurrentOwner.current) { var name = ReactCurrentOwner.current.getName(); if (name) { addendum += ' Check the render method of `' + name + '`.'; } } } var childrenString = String(children); !false ? "development" !== 'production' ? invariant(false, 'Objects are not valid as a React child (found: %s).%s', childrenString === '[object Object]' ? 'object with keys {' + Object.keys(children).join(', ') + '}' : childrenString, addendum) : _prodInvariant('31', childrenString === '[object Object]' ? 'object with keys {' + Object.keys(children).join(', ') + '}' : childrenString, addendum) : void 0; } } return subtreeCount; } /** * Traverses children that are typically specified as `props.children`, but * might also be specified through attributes: * * - `traverseAllChildren(this.props.children, ...)` * - `traverseAllChildren(this.props.leftPanelChildren, ...)` * * The `traverseContext` is an optional argument that is passed through the * entire traversal. It can be used to store accumulations or anything else that * the callback might find relevant. * * @param {?*} children Children tree object. * @param {!function} callback To invoke upon traversing each child. * @param {?*} traverseContext Context for traversal. * @return {!number} The number of children in this subtree. */ function traverseAllChildren(children, callback, traverseContext) { if (children == null) { return 0; } return traverseAllChildrenImpl(children, '', callback, traverseContext); } module.exports = traverseAllChildren; },{"114":114,"124":124,"132":132,"149":149,"156":156,"22":22,"51":51}],129:[function(_dereq_,module,exports){ /** * 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. * * */ 'use strict'; var _prodInvariant = _dereq_(124); var invariant = _dereq_(149); function formatUnexpectedArgument(arg) { var type = typeof arg; if (type !== 'object') { return type; } var displayName = arg.constructor && arg.constructor.name || type; var keys = Object.keys(arg); if (keys.length > 0 && keys.length < 20) { return displayName + ' (keys: ' + keys.join(', ') + ')'; } return displayName; } function validateCallback(callback, callerName) { !(!callback || typeof callback === 'function') ? "development" !== 'production' ? invariant(false, '%s(...): Expected the last optional `callback` argument to be a function. Instead received: %s.', callerName, formatUnexpectedArgument(callback)) : _prodInvariant('122', callerName, formatUnexpectedArgument(callback)) : void 0; } module.exports = validateCallback; },{"124":124,"149":149}],130:[function(_dereq_,module,exports){ /** * Copyright 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'; var _assign = _dereq_(157); var emptyFunction = _dereq_(141); var getComponentName = _dereq_(108); var warning = _dereq_(156); var validateDOMNesting = emptyFunction; if ("development" !== 'production') { var _require = _dereq_(48), getCurrentFiberStackAddendum = _require.getCurrentFiberStackAddendum; // This validation code was written based on the HTML5 parsing spec: // https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-scope // // Note: this does not catch all invalid nesting, nor does it try to (as it's // not clear what practical benefit doing so provides); instead, we warn only // for cases where the parser will give a parse tree differing from what React // intended. For example, <b><div></div></b> is invalid but we don't warn // because it still parses correctly; we do warn for other cases like nested // <p> tags where the beginning of the second element implicitly closes the // first, causing a confusing mess. // https://html.spec.whatwg.org/multipage/syntax.html#special var specialTags = ['address', 'applet', 'area', 'article', 'aside', 'base', 'basefont', 'bgsound', 'blockquote', 'body', 'br', 'button', 'caption', 'center', 'col', 'colgroup', 'dd', 'details', 'dir', 'div', 'dl', 'dt', 'embed', 'fieldset', 'figcaption', 'figure', 'footer', 'form', 'frame', 'frameset', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'head', 'header', 'hgroup', 'hr', 'html', 'iframe', 'img', 'input', 'isindex', 'li', 'link', 'listing', 'main', 'marquee', 'menu', 'menuitem', 'meta', 'nav', 'noembed', 'noframes', 'noscript', 'object', 'ol', 'p', 'param', 'plaintext', 'pre', 'script', 'section', 'select', 'source', 'style', 'summary', 'table', 'tbody', 'td', 'template', 'textarea', 'tfoot', 'th', 'thead', 'title', 'tr', 'track', 'ul', 'wbr', 'xmp']; // https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-scope var inScopeTags = ['applet', 'caption', 'html', 'table', 'td', 'th', 'marquee', 'object', 'template', // https://html.spec.whatwg.org/multipage/syntax.html#html-integration-point // TODO: Distinguish by namespace here -- for <title>, including it here // errs on the side of fewer warnings 'foreignObject', 'desc', 'title']; // https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-button-scope var buttonScopeTags = inScopeTags.concat(['button']); // https://html.spec.whatwg.org/multipage/syntax.html#generate-implied-end-tags var impliedEndTags = ['dd', 'dt', 'li', 'option', 'optgroup', 'p', 'rp', 'rt']; var emptyAncestorInfo = { current: null, formTag: null, aTagInScope: null, buttonTagInScope: null, nobrTagInScope: null, pTagInButtonScope: null, listItemTagAutoclosing: null, dlItemTagAutoclosing: null }; var updatedAncestorInfo = function (oldInfo, tag, instance) { var ancestorInfo = _assign({}, oldInfo || emptyAncestorInfo); var info = { tag: tag, instance: instance }; if (inScopeTags.indexOf(tag) !== -1) { ancestorInfo.aTagInScope = null; ancestorInfo.buttonTagInScope = null; ancestorInfo.nobrTagInScope = null; } if (buttonScopeTags.indexOf(tag) !== -1) { ancestorInfo.pTagInButtonScope = null; } // See rules for 'li', 'dd', 'dt' start tags in // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inbody if (specialTags.indexOf(tag) !== -1 && tag !== 'address' && tag !== 'div' && tag !== 'p') { ancestorInfo.listItemTagAutoclosing = null; ancestorInfo.dlItemTagAutoclosing = null; } ancestorInfo.current = info; if (tag === 'form') { ancestorInfo.formTag = info; } if (tag === 'a') { ancestorInfo.aTagInScope = info; } if (tag === 'button') { ancestorInfo.buttonTagInScope = info; } if (tag === 'nobr') { ancestorInfo.nobrTagInScope = info; } if (tag === 'p') { ancestorInfo.pTagInButtonScope = info; } if (tag === 'li') { ancestorInfo.listItemTagAutoclosing = info; } if (tag === 'dd' || tag === 'dt') { ancestorInfo.dlItemTagAutoclosing = info; } return ancestorInfo; }; /** * Returns whether */ var isTagValidWithParent = function (tag, parentTag) { // First, let's check if we're in an unusual parsing mode... switch (parentTag) { // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inselect case 'select': return tag === 'option' || tag === 'optgroup' || tag === '#text'; case 'optgroup': return tag === 'option' || tag === '#text'; // Strictly speaking, seeing an <option> doesn't mean we're in a <select> // but case 'option': return tag === '#text'; // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intd // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-incaption // No special behavior since these rules fall back to "in body" mode for // all except special table nodes which cause bad parsing behavior anyway. // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intr case 'tr': return tag === 'th' || tag === 'td' || tag === 'style' || tag === 'script' || tag === 'template'; // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intbody case 'tbody': case 'thead': case 'tfoot': return tag === 'tr' || tag === 'style' || tag === 'script' || tag === 'template'; // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-incolgroup case 'colgroup': return tag === 'col' || tag === 'template'; // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intable case 'table': return tag === 'caption' || tag === 'colgroup' || tag === 'tbody' || tag === 'tfoot' || tag === 'thead' || tag === 'style' || tag === 'script' || tag === 'template'; // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inhead case 'head': return tag === 'base' || tag === 'basefont' || tag === 'bgsound' || tag === 'link' || tag === 'meta' || tag === 'title' || tag === 'noscript' || tag === 'noframes' || tag === 'style' || tag === 'script' || tag === 'template'; // https://html.spec.whatwg.org/multipage/semantics.html#the-html-element case 'html': return tag === 'head' || tag === 'body'; case '#document': return tag === 'html'; } // Probably in the "in body" parsing mode, so we outlaw only tag combos // where the parsing rules cause implicit opens or closes to be added. // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inbody switch (tag) { case 'h1': case 'h2': case 'h3': case 'h4': case 'h5': case 'h6': return parentTag !== 'h1' && parentTag !== 'h2' && parentTag !== 'h3' && parentTag !== 'h4' && parentTag !== 'h5' && parentTag !== 'h6'; case 'rp': case 'rt': return impliedEndTags.indexOf(parentTag) === -1; case 'body': case 'caption': case 'col': case 'colgroup': case 'frame': case 'head': case 'html': case 'tbody': case 'td': case 'tfoot': case 'th': case 'thead': case 'tr': // These tags are only valid with a few parents that have special child // parsing rules -- if we're down here, then none of those matched and // so we allow it only if we don't know what the parent is, as all other // cases are invalid. return parentTag == null; } return true; }; /** * Returns whether */ var findInvalidAncestorForTag = function (tag, ancestorInfo) { switch (tag) { case 'address': case 'article': case 'aside': case 'blockquote': case 'center': case 'details': case 'dialog': case 'dir': case 'div': case 'dl': case 'fieldset': case 'figcaption': case 'figure': case 'footer': case 'header': case 'hgroup': case 'main': case 'menu': case 'nav': case 'ol': case 'p': case 'section': case 'summary': case 'ul': case 'pre': case 'listing': case 'table': case 'hr': case 'xmp': case 'h1': case 'h2': case 'h3': case 'h4': case 'h5': case 'h6': return ancestorInfo.pTagInButtonScope; case 'form': return ancestorInfo.formTag || ancestorInfo.pTagInButtonScope; case 'li': return ancestorInfo.listItemTagAutoclosing; case 'dd': case 'dt': return ancestorInfo.dlItemTagAutoclosing; case 'button': return ancestorInfo.buttonTagInScope; case 'a': // Spec says something about storing a list of markers, but it sounds // equivalent to this check. return ancestorInfo.aTagInScope; case 'nobr': return ancestorInfo.nobrTagInScope; } return null; }; /** * Given a ReactCompositeComponent instance, return a list of its recursive * owners, starting at the root and ending with the instance itself. */ var findOwnerStack = function (instance) { if (!instance) { return []; } var stack = []; do { stack.push(instance); } while (instance = instance._currentElement._owner); stack.reverse(); return stack; }; var getOwnerInfo = function (childInstance, childTag, ancestorInstance, ancestorTag, isParent) { var childOwner = childInstance && childInstance._currentElement._owner; var ancestorOwner = ancestorInstance && ancestorInstance._currentElement._owner; var childOwners = findOwnerStack(childOwner); var ancestorOwners = findOwnerStack(ancestorOwner); var minStackLen = Math.min(childOwners.length, ancestorOwners.length); var i; var deepestCommon = -1; for (i = 0; i < minStackLen; i++) { if (childOwners[i] === ancestorOwners[i]) { deepestCommon = i; } else { break; } } var UNKNOWN = '(unknown)'; var childOwnerNames = childOwners.slice(deepestCommon + 1).map(function (inst) { return getComponentName(inst) || UNKNOWN; }); var ancestorOwnerNames = ancestorOwners.slice(deepestCommon + 1).map(function (inst) { return getComponentName(inst) || UNKNOWN; }); var ownerInfo = [].concat( // If the parent and child instances have a common owner ancestor, start // with that -- otherwise we just start with the parent's owners. deepestCommon !== -1 ? getComponentName(childOwners[deepestCommon]) || UNKNOWN : [], ancestorOwnerNames, ancestorTag, // If we're warning about an invalid (non-parent) ancestry, add '...' isParent ? [] : ['...'], childOwnerNames, childTag).join(' > '); return ownerInfo; }; var didWarn = {}; validateDOMNesting = function (childTag, childText, childInstance, ancestorInfo) { ancestorInfo = ancestorInfo || emptyAncestorInfo; var parentInfo = ancestorInfo.current; var parentTag = parentInfo && parentInfo.tag; if (childText != null) { "development" !== 'production' ? warning(childTag == null, 'validateDOMNesting: when childText is passed, childTag should be null') : void 0; childTag = '#text'; } var invalidParent = isTagValidWithParent(childTag, parentTag) ? null : parentInfo; var invalidAncestor = invalidParent ? null : findInvalidAncestorForTag(childTag, ancestorInfo); var invalidParentOrAncestor = invalidParent || invalidAncestor; if (!invalidParentOrAncestor) { return; } var ancestorInstance = invalidParentOrAncestor.instance; var ancestorTag = invalidParentOrAncestor.tag; var addendum; if (childInstance != null) { addendum = ' See ' + getOwnerInfo(childInstance, childTag, ancestorInstance, ancestorTag, Boolean(invalidParent)) + '.'; } else { addendum = getCurrentFiberStackAddendum(); } var warnKey = !!invalidParent + '|' + childTag + '|' + ancestorTag + '|' + addendum; if (didWarn[warnKey]) { return; } didWarn[warnKey] = true; var tagDisplayName = childTag; var whitespaceInfo = ''; if (childTag === '#text') { if (/\S/.test(childText)) { tagDisplayName = 'Text nodes'; } else { tagDisplayName = 'Whitespace text nodes'; whitespaceInfo = ' Make sure you don\'t have any extra whitespace between tags on ' + 'each line of your source code.'; } } else { tagDisplayName = '<' + childTag + '>'; } if (invalidParent) { var info = ''; if (ancestorTag === 'table' && childTag === 'tr') { info += ' Add a <tbody> to your code to match the DOM tree generated by ' + 'the browser.'; } "development" !== 'production' ? warning(false, 'validateDOMNesting(...): %s cannot appear as a child of <%s>.%s%s%s', tagDisplayName, ancestorTag, whitespaceInfo, info, addendum) : void 0; } else { "development" !== 'production' ? warning(false, 'validateDOMNesting(...): %s cannot appear as a descendant of ' + '<%s>.%s', tagDisplayName, ancestorTag, addendum) : void 0; } }; validateDOMNesting.updatedAncestorInfo = updatedAncestorInfo; // For testing validateDOMNesting.isTagValidInContext = function (tag, ancestorInfo) { ancestorInfo = ancestorInfo || emptyAncestorInfo; var parentInfo = ancestorInfo.current; var parentTag = parentInfo && parentInfo.tag; return isTagValidWithParent(tag, parentTag) && !findInvalidAncestorForTag(tag, ancestorInfo); }; } module.exports = validateDOMNesting; },{"108":108,"141":141,"156":156,"157":157,"48":48}],131:[function(_dereq_,module,exports){ /** * 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. * */ /* globals React */ 'use strict'; var ReactInternals = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED; module.exports = ReactInternals.ReactComponentTreeHook; },{}],132:[function(_dereq_,module,exports){ /** * 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. * */ /* globals React */ 'use strict'; var ReactInternals = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED; module.exports = ReactInternals.ReactCurrentOwner; },{}],133:[function(_dereq_,module,exports){ /** * 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. * */ /* globals React */ 'use strict'; module.exports = React; },{}],134:[function(_dereq_,module,exports){ 'use strict'; /** * Copyright (c) 2013-present, Facebook, 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. * * @typechecks */ var emptyFunction = _dereq_(141); /** * Upstream version of event listener. Does not take into account specific * nature of platform. */ var EventListener = { /** * Listen to DOM events during the bubble phase. * * @param {DOMEventTarget} target DOM element to register listener on. * @param {string} eventType Event type, e.g. 'click' or 'mouseover'. * @param {function} callback Callback function. * @return {object} Object with a `remove` method. */ listen: function listen(target, eventType, callback) { if (target.addEventListener) { target.addEventListener(eventType, callback, false); return { remove: function remove() { target.removeEventListener(eventType, callback, false); } }; } else if (target.attachEvent) { target.attachEvent('on' + eventType, callback); return { remove: function remove() { target.detachEvent('on' + eventType, callback); } }; } }, /** * Listen to DOM events during the capture phase. * * @param {DOMEventTarget} target DOM element to register listener on. * @param {string} eventType Event type, e.g. 'click' or 'mouseover'. * @param {function} callback Callback function. * @return {object} Object with a `remove` method. */ capture: function capture(target, eventType, callback) { if (target.addEventListener) { target.addEventListener(eventType, callback, true); return { remove: function remove() { target.removeEventListener(eventType, callback, true); } }; } else { if ("development" !== 'production') { console.error('Attempted to listen to events during the capture phase on a ' + 'browser that does not support the capture phase. Your application ' + 'will not receive some events.'); } return { remove: emptyFunction }; } }, registerDefault: function registerDefault() {} }; module.exports = EventListener; },{"141":141}],135:[function(_dereq_,module,exports){ /** * 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. * */ 'use strict'; var canUseDOM = !!(typeof window !== 'undefined' && window.document && window.document.createElement); /** * Simple, lightweight module assisting with the detection and context of * Worker. Helps avoid circular dependencies and allows code to reason about * whether or not they are in a Worker, even if they never include the main * `ReactWorker` dependency. */ var ExecutionEnvironment = { canUseDOM: canUseDOM, canUseWorkers: typeof Worker !== 'undefined', canUseEventListeners: canUseDOM && !!(window.addEventListener || window.attachEvent), canUseViewport: canUseDOM && !!window.screen, isInWorker: !canUseDOM // For now, this is true - might change in the future. }; module.exports = ExecutionEnvironment; },{}],136:[function(_dereq_,module,exports){ "use strict"; /** * 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(string) { return string.replace(_hyphenPattern, function (_, character) { return character.toUpperCase(); }); } module.exports = camelize; },{}],137:[function(_dereq_,module,exports){ /** * 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 */ 'use strict'; var camelize = _dereq_(136); var msPattern = /^-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, 'ms-')); } module.exports = camelizeStyleName; },{"136":136}],138:[function(_dereq_,module,exports){ 'use strict'; /** * 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. * * */ var isTextNode = _dereq_(151); /*eslint-disable no-bitwise */ /** * Checks if a given DOM node contains or is another DOM node. */ function containsNode(outerNode, innerNode) { if (!outerNode || !innerNode) { return false; } else if (outerNode === innerNode) { return true; } else if (isTextNode(outerNode)) { return false; } else if (isTextNode(innerNode)) { return containsNode(outerNode, innerNode.parentNode); } else if ('contains' in outerNode) { return outerNode.contains(innerNode); } else if (outerNode.compareDocumentPosition) { return !!(outerNode.compareDocumentPosition(innerNode) & 16); } else { return false; } } module.exports = containsNode; },{"151":151}],139:[function(_dereq_,module,exports){ 'use strict'; /** * 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 invariant = _dereq_(149); /** * Convert array-like objects to arrays. * * This API assumes the caller knows the contents of the data type. For less * well defined inputs use createArrayFromMixed. * * @param {object|function|filelist} obj * @return {array} */ function toArray(obj) { var length = obj.length; // Some browsers builtin objects can report typeof 'function' (e.g. NodeList // in old versions of Safari). !(!Array.isArray(obj) && (typeof obj === 'object' || typeof obj === 'function')) ? "development" !== 'production' ? invariant(false, 'toArray: Array-like object expected') : invariant(false) : void 0; !(typeof length === 'number') ? "development" !== 'production' ? invariant(false, 'toArray: Object needs a length property') : invariant(false) : void 0; !(length === 0 || length - 1 in obj) ? "development" !== 'production' ? invariant(false, 'toArray: Object should have keys for indices') : invariant(false) : void 0; !(typeof obj.callee !== 'function') ? "development" !== 'production' ? invariant(false, 'toArray: Object can\'t be `arguments`. Use rest params ' + '(function(...args) {}) or Array.from() instead.') : invariant(false) : void 0; // Old IE doesn't give collections access to hasOwnProperty. Assume inputs // without method will throw during the slice call and skip straight to the // fallback. if (obj.hasOwnProperty) { try { return Array.prototype.slice.call(obj); } catch (e) { // IE < 9 does not support Array#slice on collections objects } } // Fall back to copying key by key. This assumes all keys have a value, // so will not preserve sparsely populated inputs. var ret = Array(length); for (var ii = 0; ii < length; ii++) { ret[ii] = obj[ii]; } return ret; } /** * Perform a heuristic test to determine if an object is "array-like". * * A monk asked Joshu, a Zen master, "Has a dog Buddha nature?" * Joshu replied: "Mu." * * This function determines if its argument has "array nature": it returns * true if the argument is an actual array, an `arguments' object, or an * HTMLCollection (e.g. node.childNodes or node.getElementsByTagName()). * * It will return false for other array-like objects like Filelist. * * @param {*} obj * @return {boolean} */ function hasArrayNature(obj) { return ( // not null/false !!obj && ( // arrays are objects, NodeLists are functions in Safari typeof obj == 'object' || typeof obj == 'function') && // quacks like an array 'length' in obj && // not window !('setInterval' in obj) && // no DOM node should be considered an array-like // a 'select' element has 'length' and 'item' properties on IE8 typeof obj.nodeType != 'number' && ( // a real array Array.isArray(obj) || // arguments 'callee' in obj || // HTMLCollection/NodeList 'item' in obj) ); } /** * Ensure that the argument is an array by wrapping it in an array if it is not. * Creates a copy of the argument if it is already an array. * * This is mostly useful idiomatically: * * var createArrayFromMixed = require('createArrayFromMixed'); * * function takesOneOrMoreThings(things) { * things = createArrayFromMixed(things); * ... * } * * This allows you to treat `things' as an array, but accept scalars in the API. * * If you need to convert an array-like object, like `arguments`, into an array * use toArray instead. * * @param {*} obj * @return {array} */ function createArrayFromMixed(obj) { if (!hasArrayNature(obj)) { return [obj]; } else if (Array.isArray(obj)) { return obj.slice(); } else { return toArray(obj); } } module.exports = createArrayFromMixed; },{"149":149}],140:[function(_dereq_,module,exports){ 'use strict'; /** * 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 */ /*eslint-disable fb-www/unsafe-html*/ var ExecutionEnvironment = _dereq_(135); var createArrayFromMixed = _dereq_(139); var getMarkupWrap = _dereq_(145); var invariant = _dereq_(149); /** * Dummy container used to render all markup. */ var dummyNode = ExecutionEnvironment.canUseDOM ? document.createElement('div') : null; /** * Pattern used by `getNodeName`. */ var nodeNamePattern = /^\s*<(\w+)/; /** * Extracts the `nodeName` of the first element in a string of markup. * * @param {string} markup String of markup. * @return {?string} Node name of the supplied markup. */ function getNodeName(markup) { var nodeNameMatch = markup.match(nodeNamePattern); return nodeNameMatch && nodeNameMatch[1].toLowerCase(); } /** * Creates an array containing the nodes rendered from the supplied markup. The * optionally supplied `handleScript` function will be invoked once for each * <script> element that is rendered. If no `handleScript` function is supplied, * an exception is thrown if any <script> elements are rendered. * * @param {string} markup A string of valid HTML markup. * @param {?function} handleScript Invoked once for each rendered <script>. * @return {array<DOMElement|DOMTextNode>} An array of rendered nodes. */ function createNodesFromMarkup(markup, handleScript) { var node = dummyNode; !!!dummyNode ? "development" !== 'production' ? invariant(false, 'createNodesFromMarkup dummy not initialized') : invariant(false) : void 0; var nodeName = getNodeName(markup); var wrap = nodeName && getMarkupWrap(nodeName); if (wrap) { node.innerHTML = wrap[1] + markup + wrap[2]; var wrapDepth = wrap[0]; while (wrapDepth--) { node = node.lastChild; } } else { node.innerHTML = markup; } var scripts = node.getElementsByTagName('script'); if (scripts.length) { !handleScript ? "development" !== 'production' ? invariant(false, 'createNodesFromMarkup(...): Unexpected <script> element rendered.') : invariant(false) : void 0; createArrayFromMixed(scripts).forEach(handleScript); } var nodes = Array.from(node.childNodes); while (node.lastChild) { node.removeChild(node.lastChild); } return nodes; } module.exports = createNodesFromMarkup; },{"135":135,"139":139,"145":145,"149":149}],141:[function(_dereq_,module,exports){ "use strict"; /** * 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. * * */ function makeEmptyFunction(arg) { return function () { return arg; }; } /** * This function accepts and discards inputs; it has no side effects. This is * primarily useful idiomatically for overridable function endpoints which * always need to be callable, since JS lacks a null-call idiom ala Cocoa. */ var emptyFunction = function emptyFunction() {}; emptyFunction.thatReturns = makeEmptyFunction; emptyFunction.thatReturnsFalse = makeEmptyFunction(false); emptyFunction.thatReturnsTrue = makeEmptyFunction(true); emptyFunction.thatReturnsNull = makeEmptyFunction(null); emptyFunction.thatReturnsThis = function () { return this; }; emptyFunction.thatReturnsArgument = function (arg) { return arg; }; module.exports = emptyFunction; },{}],142:[function(_dereq_,module,exports){ /** * 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. * */ 'use strict'; var emptyObject = {}; if ("development" !== 'production') { Object.freeze(emptyObject); } module.exports = emptyObject; },{}],143:[function(_dereq_,module,exports){ /** * 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. * */ 'use strict'; /** * @param {DOMElement} node input/textarea to focus */ function focusNode(node) { // IE8 can throw "Can't move focus to the control because it is invisible, // not enabled, or of a type that does not accept the focus." for all kinds of // reasons that are too expensive and fragile to test. try { node.focus(); } catch (e) {} } module.exports = focusNode; },{}],144:[function(_dereq_,module,exports){ 'use strict'; /** * 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 */ /* eslint-disable fb-www/typeof-undefined */ /** * Same as document.activeElement but wraps in a try-catch block. In IE it is * not safe to call document.activeElement if there is nothing focused. * * The activeElement will be null only if the document or document body is not * yet defined. */ function getActiveElement() /*?DOMElement*/{ if (typeof document === 'undefined') { return null; } try { return document.activeElement || document.body; } catch (e) { return document.body; } } module.exports = getActiveElement; },{}],145:[function(_dereq_,module,exports){ 'use strict'; /** * 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. * */ /*eslint-disable fb-www/unsafe-html */ var ExecutionEnvironment = _dereq_(135); var invariant = _dereq_(149); /** * Dummy container used to detect which wraps are necessary. */ var dummyNode = ExecutionEnvironment.canUseDOM ? document.createElement('div') : null; /** * Some browsers cannot use `innerHTML` to render certain elements standalone, * so we wrap them, render the wrapped nodes, then extract the desired node. * * In IE8, certain elements cannot render alone, so wrap all elements ('*'). */ var shouldWrap = {}; var selectWrap = [1, '<select multiple="true">', '</select>']; var tableWrap = [1, '<table>', '</table>']; var trWrap = [3, '<table><tbody><tr>', '</tr></tbody></table>']; var svgWrap = [1, '<svg xmlns="http://www.w3.org/2000/svg">', '</svg>']; var markupWrap = { '*': [1, '?<div>', '</div>'], 'area': [1, '<map>', '</map>'], 'col': [2, '<table><tbody></tbody><colgroup>', '</colgroup></table>'], 'legend': [1, '<fieldset>', '</fieldset>'], 'param': [1, '<object>', '</object>'], 'tr': [2, '<table><tbody>', '</tbody></table>'], 'optgroup': selectWrap, 'option': selectWrap, 'caption': tableWrap, 'colgroup': tableWrap, 'tbody': tableWrap, 'tfoot': tableWrap, 'thead': tableWrap, 'td': trWrap, 'th': trWrap }; // Initialize the SVG elements since we know they'll always need to be wrapped // consistently. If they are created inside a <div> they will be initialized in // the wrong namespace (and will not display). var svgElements = ['circle', 'clipPath', 'defs', 'ellipse', 'g', 'image', 'line', 'linearGradient', 'mask', 'path', 'pattern', 'polygon', 'polyline', 'radialGradient', 'rect', 'stop', 'text', 'tspan']; svgElements.forEach(function (nodeName) { markupWrap[nodeName] = svgWrap; shouldWrap[nodeName] = true; }); /** * Gets the markup wrap configuration for the supplied `nodeName`. * * NOTE: This lazily detects which wraps are necessary for the current browser. * * @param {string} nodeName Lowercase `nodeName`. * @return {?array} Markup wrap configuration, if applicable. */ function getMarkupWrap(nodeName) { !!!dummyNode ? "development" !== 'production' ? invariant(false, 'Markup wrapping node not initialized') : invariant(false) : void 0; if (!markupWrap.hasOwnProperty(nodeName)) { nodeName = '*'; } if (!shouldWrap.hasOwnProperty(nodeName)) { if (nodeName === '*') { dummyNode.innerHTML = '<link />'; } else { dummyNode.innerHTML = '<' + nodeName + '></' + nodeName + '>'; } shouldWrap[nodeName] = !dummyNode.firstChild; } return shouldWrap[nodeName] ? markupWrap[nodeName] : null; } module.exports = getMarkupWrap; },{"135":135,"149":149}],146:[function(_dereq_,module,exports){ /** * 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 */ 'use strict'; /** * Gets the scroll position of the supplied element or window. * * The return values are unbounded, unlike `getScrollPosition`. This means they * may be negative or exceed the element boundaries (which is possible using * inertial scrolling). * * @param {DOMWindow|DOMElement} scrollable * @return {object} Map with `x` and `y` keys. */ function getUnboundedScrollPosition(scrollable) { if (scrollable === window) { return { x: window.pageXOffset || document.documentElement.scrollLeft, y: window.pageYOffset || document.documentElement.scrollTop }; } return { x: scrollable.scrollLeft, y: scrollable.scrollTop }; } module.exports = getUnboundedScrollPosition; },{}],147:[function(_dereq_,module,exports){ 'use strict'; /** * 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(string) { return string.replace(_uppercasePattern, '-$1').toLowerCase(); } module.exports = hyphenate; },{}],148:[function(_dereq_,module,exports){ /** * 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 */ 'use strict'; var hyphenate = _dereq_(147); 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-'); } module.exports = hyphenateStyleName; },{"147":147}],149:[function(_dereq_,module,exports){ /** * 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. * */ '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. */ function invariant(condition, format, a, b, c, d, e, f) { if ("development" !== '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; },{}],150:[function(_dereq_,module,exports){ 'use strict'; /** * 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 */ /** * @param {*} object The object to check. * @return {boolean} Whether or not the object is a DOM node. */ function isNode(object) { return !!(object && (typeof Node === 'function' ? object instanceof Node : typeof object === 'object' && typeof object.nodeType === 'number' && typeof object.nodeName === 'string')); } module.exports = isNode; },{}],151:[function(_dereq_,module,exports){ 'use strict'; /** * 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 isNode = _dereq_(150); /** * @param {*} object The object to check. * @return {boolean} Whether or not the object is a DOM text node. */ function isTextNode(object) { return isNode(object) && object.nodeType == 3; } module.exports = isTextNode; },{"150":150}],152:[function(_dereq_,module,exports){ /** * 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 static-only */ 'use strict'; /** * Memoizes the return value of a function that accepts one string argument. */ function memoizeStringOnly(callback) { var cache = {}; return function (string) { if (!cache.hasOwnProperty(string)) { cache[string] = callback.call(this, string); } return cache[string]; }; } module.exports = memoizeStringOnly; },{}],153:[function(_dereq_,module,exports){ /** * 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 */ 'use strict'; var ExecutionEnvironment = _dereq_(135); var performance; if (ExecutionEnvironment.canUseDOM) { performance = window.performance || window.msPerformance || window.webkitPerformance; } module.exports = performance || {}; },{"135":135}],154:[function(_dereq_,module,exports){ 'use strict'; /** * 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 performance = _dereq_(153); var performanceNow; /** * Detect if we can use `window.performance.now()` and gracefully fallback to * `Date.now()` if it doesn't exist. We need to support Firefox < 15 for now * because of Facebook's testing infrastructure. */ if (performance.now) { performanceNow = function performanceNow() { return performance.now(); }; } else { performanceNow = function performanceNow() { return Date.now(); }; } module.exports = performanceNow; },{"153":153}],155:[function(_dereq_,module,exports){ /** * 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 * */ /*eslint-disable no-self-compare */ 'use strict'; var hasOwnProperty = Object.prototype.hasOwnProperty; /** * inlined Object.is polyfill to avoid requiring consumers ship their own * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is */ function is(x, y) { // SameValue algorithm if (x === y) { // Steps 1-5, 7-10 // Steps 6.b-6.e: +0 != -0 // Added the nonzero y check to make Flow happy, but it is redundant return x !== 0 || y !== 0 || 1 / x === 1 / y; } else { // Step 6.a: NaN == NaN return x !== x && y !== y; } } /** * Performs equality by iterating through keys on an object and returning false * when any key has values which are not strictly equal between the arguments. * Returns true when the values of all keys are strictly equal. */ function shallowEqual(objA, objB) { if (is(objA, objB)) { return true; } if (typeof objA !== 'object' || objA === null || typeof objB !== 'object' || objB === null) { return false; } var keysA = Object.keys(objA); var keysB = Object.keys(objB); console.log('shallowEqual()', objA, objB) if (keysA.length !== keysB.length) { return false; } // Test for A's keys different from B. for (var i = 0; i < keysA.length; i++) { console.log(' is()', objA[keysA[i]], objB[keysA[i]], is(objA[keysA[i]], objB[keysA[i]])) if (!hasOwnProperty.call(objB, keysA[i]) || !is(objA[keysA[i]], objB[keysA[i]])) { return false; } } return true; } module.exports = shallowEqual; },{}],156:[function(_dereq_,module,exports){ /** * Copyright 2014-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'; var emptyFunction = _dereq_(141); /** * Similar to invariant but only logs a warning if the condition is not met. * This can be used to log issues in development environments in critical * paths. Removing the logging code for production environments will keep the * same logic and follow the same code paths. */ var warning = emptyFunction; if ("development" !== 'production') { (function () { var printWarning = function printWarning(format) { for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { args[_key - 1] = arguments[_key]; } var argIndex = 0; var message = 'Warning: ' + format.replace(/%s/g, function () { return args[argIndex++]; }); if (typeof console !== 'undefined') { console.error(message); } try { // --- Welcome to debugging React --- // This error was thrown as a convenience so that you can use this stack // to find the callsite that caused this warning to fire. throw new Error(message); } catch (x) {} }; warning = function warning(condition, format) { if (format === undefined) { throw new Error('`warning(condition, format, ...args)` requires a warning ' + 'message argument'); } if (format.indexOf('Failed Composite propType: ') === 0) { return; // Ignore CompositeComponent proptype check. } if (!condition) { for (var _len2 = arguments.length, args = Array(_len2 > 2 ? _len2 - 2 : 0), _key2 = 2; _key2 < _len2; _key2++) { args[_key2 - 2] = arguments[_key2]; } printWarning.apply(undefined, [format].concat(args)); } }; })(); } module.exports = warning; },{"141":141}],157:[function(_dereq_,module,exports){ 'use strict'; /* eslint-disable no-unused-vars */ var hasOwnProperty = Object.prototype.hasOwnProperty; var propIsEnumerable = Object.prototype.propertyIsEnumerable; function toObject(val) { if (val === null || val === undefined) { throw new TypeError('Object.assign cannot be called with null or undefined'); } return Object(val); } function shouldUseNative() { try { if (!Object.assign) { return false; } // Detect buggy property enumeration order in older V8 versions. // https://bugs.chromium.org/p/v8/issues/detail?id=4118 var test1 = new String('abc'); // eslint-disable-line test1[5] = 'de'; if (Object.getOwnPropertyNames(test1)[0] === '5') { return false; } // https://bugs.chromium.org/p/v8/issues/detail?id=3056 var test2 = {}; for (var i = 0; i < 10; i++) { test2['_' + String.fromCharCode(i)] = i; } var order2 = Object.getOwnPropertyNames(test2).map(function (n) { return test2[n]; }); if (order2.join('') !== '0123456789') { return false; } // https://bugs.chromium.org/p/v8/issues/detail?id=3056 var test3 = {}; 'abcdefghijklmnopqrst'.split('').forEach(function (letter) { test3[letter] = letter; }); if (Object.keys(Object.assign({}, test3)).join('') !== 'abcdefghijklmnopqrst') { return false; } return true; } catch (e) { // We don't expect any of the above to throw, but better to be safe. return false; } } module.exports = shouldUseNative() ? Object.assign : function (target, source) { var from; var to = toObject(target); var symbols; for (var s = 1; s < arguments.length; s++) { from = Object(arguments[s]); for (var key in from) { if (hasOwnProperty.call(from, key)) { to[key] = from[key]; } } if (Object.getOwnPropertySymbols) { symbols = Object.getOwnPropertySymbols(from); for (var i = 0; i < symbols.length; i++) { if (propIsEnumerable.call(from, symbols[i])) { to[symbols[i]] = from[symbols[i]]; } } } } return to; }; },{}]},{},[44])(44) }); });
/** * ag-grid - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components * @version v12.0.2 * @link http://www.ag-grid.com/ * @license MIT */ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var Events = (function () { function Events() { } /** Everything has changed with the columns. Either complete new set of columns set, or user called setState()*/ Events.EVENT_COLUMN_EVERYTHING_CHANGED = 'columnEverythingChanged'; /** User has set in new columns. */ Events.EVENT_NEW_COLUMNS_LOADED = 'newColumnsLoaded'; /** The pivot mode flag was changed */ Events.EVENT_COLUMN_PIVOT_MODE_CHANGED = 'columnPivotModeChanged'; /** A row group column was added, removed or order changed. */ Events.EVENT_COLUMN_ROW_GROUP_CHANGED = 'columnRowGroupChanged'; /** A pivot column was added, removed or order changed. */ Events.EVENT_COLUMN_PIVOT_CHANGED = 'columnPivotChanged'; /** The list of grid columns has changed. */ Events.EVENT_GRID_COLUMNS_CHANGED = 'gridColumnsChanged'; /** A value column was added, removed or agg function was changed. */ Events.EVENT_COLUMN_VALUE_CHANGED = 'columnValueChanged'; /** A column was moved */ Events.EVENT_COLUMN_MOVED = 'columnMoved'; /** One or more columns was shown / hidden */ Events.EVENT_COLUMN_VISIBLE = 'columnVisible'; /** One or more columns was pinned / unpinned*/ Events.EVENT_COLUMN_PINNED = 'columnPinned'; /** A column group was opened / closed */ Events.EVENT_COLUMN_GROUP_OPENED = 'columnGroupOpened'; /** One or more columns was resized. If just one, the column in the event is set. */ Events.EVENT_COLUMN_RESIZED = 'columnResized'; /** The list of displayed columns has changed, can result from columns open / close, column move, pivot, group, etc */ Events.EVENT_DISPLAYED_COLUMNS_CHANGED = 'displayedColumnsChanged'; /** The list of virtual columns has changed, results from viewport changing */ Events.EVENT_VIRTUAL_COLUMNS_CHANGED = 'virtualColumnsChanged'; /** A row group was opened / closed */ Events.EVENT_ROW_GROUP_OPENED = 'rowGroupOpened'; /** The client has set new data into the grid */ Events.EVENT_ROW_DATA_CHANGED = 'rowDataChanged'; /** The client has set new data into the grid */ Events.EVENT_ROW_DATA_UPDATED = 'rowDataUpdated'; /** The client has set new floating data into the grid */ Events.EVENT_PINNED_ROW_DATA_CHANGED = 'pinnedRowDataChanged'; /** Range selection has changed */ Events.EVENT_RANGE_SELECTION_CHANGED = 'rangeSelectionChanged'; /** Model was updated - grid updates the drawn rows when this happens */ Events.EVENT_MODEL_UPDATED = 'modelUpdated'; Events.EVENT_CELL_CLICKED = 'cellClicked'; Events.EVENT_CELL_DOUBLE_CLICKED = 'cellDoubleClicked'; Events.EVENT_CELL_CONTEXT_MENU = 'cellContextMenu'; Events.EVENT_CELL_VALUE_CHANGED = 'cellValueChanged'; Events.EVENT_ROW_VALUE_CHANGED = 'rowValueChanged'; Events.EVENT_CELL_FOCUSED = 'cellFocused'; Events.EVENT_ROW_SELECTED = 'rowSelected'; Events.EVENT_SELECTION_CHANGED = 'selectionChanged'; Events.EVENT_CELL_MOUSE_OVER = 'cellMouseOver'; Events.EVENT_CELL_MOUSE_OUT = 'cellMouseOut'; Events.EVENT_COLUMN_HOVER_CHANGED = 'columnHoverChanged'; /** 2 events for filtering. The grid LISTENS for filterChanged and afterFilterChanged */ Events.EVENT_FILTER_CHANGED = 'filterChanged'; /** Filter was change but not applied. Only useful if apply buttons are used in filters. */ Events.EVENT_FILTER_MODIFIED = 'filterModified'; Events.EVENT_SORT_CHANGED = 'sortChanged'; /** A row was removed from the dom, for any reason. Use to clean up resources (if any) used by the row. */ Events.EVENT_VIRTUAL_ROW_REMOVED = 'virtualRowRemoved'; Events.EVENT_ROW_CLICKED = 'rowClicked'; Events.EVENT_ROW_DOUBLE_CLICKED = 'rowDoubleClicked'; /** Gets called once after the grid has finished initialising. */ Events.EVENT_GRID_READY = 'gridReady'; /** Width of height of the main grid div has changed. Grid listens for this and does layout of grid if it's * changed, so always filling the space it was given. */ Events.EVENT_GRID_SIZE_CHANGED = 'gridSizeChanged'; /** The indexes of the rows rendered has changed, eg user has scrolled to a new vertical position. */ Events.EVENT_VIEWPORT_CHANGED = 'viewportChanged'; /** A column drag has started, either resizing a column or moving a column. */ Events.EVENT_DRAG_STARTED = 'dragStarted'; /** A column drag has stopped */ Events.EVENT_DRAG_STOPPED = 'dragStopped'; Events.EVENT_ROW_EDITING_STARTED = 'rowEditingStarted'; Events.EVENT_ROW_EDITING_STOPPED = 'rowEditingStopped'; Events.EVENT_CELL_EDITING_STARTED = 'cellEditingStarted'; Events.EVENT_CELL_EDITING_STOPPED = 'cellEditingStopped'; /** Client added a new row. */ Events.EVENT_ITEMS_ADDED = 'itemsAdded'; /** Client removed a row. */ Events.EVENT_ITEMS_REMOVED = 'itemsRemoved'; /** Main body of grid has scrolled, either horizontally or vertically */ Events.EVENT_BODY_SCROLL = 'bodyScroll'; /** All items from here down are used internally by the grid, not intended for external use. */ Events.EVENT_FLASH_CELLS = 'flashCells'; /** All the events from here down are experimental, should not be documented or used by ag-Grid customers */ Events.EVENT_PAGINATION_CHANGED = 'paginationChanged'; Events.EVENT_BODY_HEIGHT_CHANGED = 'bodyHeightChanged'; // not documented, as it's experimental, don't want people with dependencies on this Events.EVENT_DISPLAYED_COLUMNS_WIDTH_CHANGED = 'displayedColumnsWidthChanged'; Events.EVENT_SCROLL_VISIBILITY_CHANGED = 'scrollVisibilityChanged'; Events.EVENT_COMPONENT_STATE_CHANGED = 'componentStateChanged'; // these are used for server side group and agg - only used by CS with Viewport Row Model - intention is // to design these better around server side functions and then release to general public when fully working with // all the row models. Events.EVENT_COLUMN_ROW_GROUP_CHANGE_REQUEST = 'columnRowGroupChangeRequest'; Events.EVENT_COLUMN_PIVOT_CHANGE_REQUEST = 'columnPivotChangeRequest'; Events.EVENT_COLUMN_VALUE_CHANGE_REQUEST = 'columnValueChangeRequest'; Events.EVENT_COLUMN_AGG_FUNC_CHANGE_REQUEST = 'columnAggFuncChangeRequest'; return Events; }()); exports.Events = Events;
(function($){ acf.fields.date_picker = acf.field.extend({ type: 'date_picker', $el: null, $input: null, $hidden: null, o : {}, actions: { 'ready': 'initialize', 'append': 'initialize' }, events: { 'blur input[type="text"]': 'blur', }, focus: function(){ // get elements this.$el = this.$field.find('.acf-date_picker'); this.$input = this.$el.find('input[type="text"]'); this.$hidden = this.$el.find('input[type="hidden"]'); // get options this.o = acf.get_data( this.$el ); }, initialize: function(){ // get and set value from alt field this.$input.val( this.$hidden.val() ); // create options var args = $.extend( {}, acf.l10n.date_picker, { dateFormat : 'yymmdd', altField : this.$hidden, altFormat : 'yymmdd', changeYear : true, yearRange : "-100:+100", changeMonth : true, showButtonPanel : true, firstDay : this.o.first_day }); // filter for 3rd party customization args = acf.apply_filters('date_picker_args', args, this.$el); // add date picker this.$input.addClass('active').datepicker( args ); // now change the format back to how it should be. this.$input.datepicker( "option", "dateFormat", this.o.display_format ); // wrap the datepicker (only if it hasn't already been wrapped) if( $('body > #ui-datepicker-div').exists() ) { $('body > #ui-datepicker-div').wrap('<div class="acf-ui-datepicker" />'); } }, blur : function(){ if( !this.$input.val() ) { this.$hidden.val(''); } } }); })(jQuery);
export {}; //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoidGFibGVzdGF0ZS5qcyIsInNvdXJjZVJvb3QiOiIuLi8uLi8uLi9zcmMvYXBwL2NvbXBvbmVudHMvYXBpLyIsInNvdXJjZXMiOlsidGFibGVzdGF0ZS50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiIiwic291cmNlc0NvbnRlbnQiOlsiaW1wb3J0IHsgU29ydE1ldGEgfSBmcm9tICcuL3NvcnRtZXRhJztcbmltcG9ydCB7IEZpbHRlck1ldGFkYXRhIH0gZnJvbSAnLi9maWx0ZXJtZXRhZGF0YSc7XG5cbmV4cG9ydCBpbnRlcmZhY2UgVGFibGVTdGF0ZSB7XG4gICAgZmlyc3Q/OiBudW1iZXI7XG4gICAgcm93cz86IG51bWJlcjtcbiAgICBzb3J0RmllbGQ/OiBzdHJpbmc7XG4gICAgc29ydE9yZGVyPzogbnVtYmVyO1xuICAgIG11bHRpU29ydE1ldGE/OiBTb3J0TWV0YVtdO1xuICAgIGZpbHRlcnM/OiB7W3M6IHN0cmluZ106IEZpbHRlck1ldGFkYXRhIHzCoEZpbHRlck1ldGFkYXRhW107fTtcbiAgICBjb2x1bW5XaWR0aHM/OiBzdHJpbmc7XG4gICAgdGFibGVXaWR0aD86IHN0cmluZztcbiAgICBzZWxlY3Rpb24/OiBhbnk7XG4gICAgY29sdW1uT3JkZXI/OiBzdHJpbmdbXTtcbiAgICBleHBhbmRlZFJvd0tleXM/OiB7W3M6IHN0cmluZ106IGJvb2xlYW47fTtcbn0iXX0=
(function (ng) { 'use strict'; ng.module('smart-table', []).run(['$templateCache', function ($templateCache) { $templateCache.put('template/smart-table/pagination.html', '<div class="pagination" ng-if="pages.length >= 2"><ul class="pagination">' + '<li ng-repeat="page in pages" ng-class="{active: page==currentPage}"><a ng-click="selectPage(page)">{{page}}</a></li>' + '</ul></div>'); }]); })(angular); (function (ng, undefined) { 'use strict'; ng.module('smart-table') .controller('stTableController', ['$scope', '$parse', '$filter', '$attrs', function StTableController($scope, $parse, $filter, $attrs) { var propertyName = $attrs.stTable; var displayGetter = $parse(propertyName); var displaySetter = displayGetter.assign; var safeGetter; var orderBy = $filter('orderBy'); var filter = $filter('filter'); var safeCopy = copyRefs(displayGetter($scope)); var tableState = { sort: {}, search: {}, pagination: { start: 0 } }; var pipeAfterSafeCopy = true; var ctrl = this; var lastSelected; function copyRefs(src) { return [].concat(src); } function updateSafeCopy() { safeCopy = copyRefs(safeGetter($scope)); if (pipeAfterSafeCopy === true) { ctrl.pipe(); } } if ($attrs.stSafeSrc) { safeGetter = $parse($attrs.stSafeSrc); $scope.$watch(function () { var safeSrc = safeGetter($scope); return safeSrc ? safeSrc.length : 0; }, function (newValue, oldValue) { if (newValue !== oldValue) { updateSafeCopy(); } }); $scope.$watch(function () { return safeGetter($scope); }, function (newValue, oldValue) { if (newValue !== oldValue) { updateSafeCopy(); } }); } /** * sort the rows * @param {Function | String} predicate - function or string which will be used as predicate for the sorting * @param [reverse] - if you want to reverse the order */ this.sortBy = function sortBy(predicate, reverse) { tableState.sort.predicate = predicate; tableState.sort.reverse = reverse === true; tableState.pagination.start = 0; this.pipe(); }; /** * search matching rows * @param {String} input - the input string * @param {String} [predicate] - the property name against you want to check the match, otherwise it will search on all properties */ this.search = function search(input, predicate) { var predicateObject = tableState.search.predicateObject || {}; var prop = predicate ? predicate : '$'; predicateObject[prop] = input; // to avoid to filter out null value if (!input) { delete predicateObject[prop]; } tableState.search.predicateObject = predicateObject; tableState.pagination.start = 0; this.pipe(); }; /** * this will chain the operations of sorting and filtering based on the current table state (sort options, filtering, ect) */ this.pipe = function pipe() { var pagination = tableState.pagination; var filtered = tableState.search.predicateObject ? filter(safeCopy, tableState.search.predicateObject) : safeCopy; if (tableState.sort.predicate) { filtered = orderBy(filtered, tableState.sort.predicate, tableState.sort.reverse); } if (pagination.number !== undefined) { pagination.numberOfPages = filtered.length > 0 ? Math.ceil(filtered.length / pagination.number) : 1; pagination.start = pagination.start >= filtered.length ? (pagination.numberOfPages - 1) * pagination.number : pagination.start; filtered = filtered.slice(pagination.start, pagination.start + pagination.number); } displaySetter($scope, filtered); }; /** * select a dataRow (it will add the attribute isSelected to the row object) * @param {Object} row - the row to select * @param {String} [mode] - "single" or "multiple" (multiple by default) */ this.select = function select(row, mode) { var rows = safeCopy; var index = rows.indexOf(row); if (index !== -1) { if (mode === 'single') { row.isSelected = row.isSelected !== true; if (lastSelected) { lastSelected.isSelected = false; } lastSelected = row.isSelected === true ? row : undefined; } else { rows[index].isSelected = !rows[index].isSelected; } } }; /** * take a slice of the current sorted/filtered collection (pagination) * * @param {Number} start - start index of the slice * @param {Number} number - the number of item in the slice */ this.slice = function splice(start, number) { tableState.pagination.start = start; tableState.pagination.number = number; this.pipe(); }; /** * return the current state of the table * @returns {{sort: {}, search: {}, pagination: {start: number}}} */ this.tableState = function getTableState() { return tableState; }; /** * Use a different filter function than the angular FilterFilter * @param filterName the name under which the custom filter is registered */ this.setFilterFunction = function setFilterFunction(filterName) { filter = $filter(filterName); }; /** *User a different function than the angular orderBy * @param sortFunctionName the name under which the custom order function is registered */ this.setSortFunction = function setSortFunction(sortFunctionName) { orderBy = $filter(sortFunctionName); }; /** * Usually when the safe copy is updated the pipe function is called. * Calling this method will prevent it, which is something required when using a custom pipe function */ this.preventPipeOnWatch = function preventPipe() { pipeAfterSafeCopy = false; }; }]) .directive('stTable', function () { return { restrict: 'A', controller: 'stTableController', link: function (scope, element, attr, ctrl) { } }; }); })(angular); (function (ng) { 'use strict'; ng.module('smart-table') .directive('stSearch', ['$timeout', function ($timeout) { return { require: '^stTable', scope: { predicate: '=?stSearch' }, link: function (scope, element, attr, ctrl) { var tableCtrl = ctrl; var promise = null; var throttle = attr.stDelay || 400; scope.$watch('predicate', function (newValue, oldValue) { if (newValue !== oldValue) { ctrl.tableState().search = {}; tableCtrl.search(element[0].value || '', newValue); } }); //table state -> view scope.$watch(function () { return ctrl.tableState().search; }, function (newValue, oldValue) { var predicateExpression = scope.predicate || '$'; if (newValue.predicateObject && newValue.predicateObject[predicateExpression] !== element[0].value) { element[0].value = newValue.predicateObject[predicateExpression] || ''; } }, true); // view -> table state element.bind('input', function (evt) { evt = evt.originalEvent || evt; if (promise !== null) { $timeout.cancel(promise); } promise = $timeout(function () { tableCtrl.search(evt.target.value, scope.predicate || ''); promise = null; }, throttle); }); } }; }]); })(angular); (function (ng) { 'use strict'; ng.module('smart-table') .directive('stSelectRow', function () { return { restrict: 'A', require: '^stTable', scope: { row: '=stSelectRow' }, link: function (scope, element, attr, ctrl) { var mode = attr.stSelectMode || 'single'; element.bind('click', function () { scope.$apply(function () { ctrl.select(scope.row, mode); }); }); scope.$watch('row.isSelected', function (newValue, oldValue) { if (newValue === true) { element.addClass('st-selected'); } else { element.removeClass('st-selected'); } }); } }; }); })(angular); (function (ng, undefined) { 'use strict'; ng.module('smart-table') .directive('stSort', ['$parse', function ($parse) { return { restrict: 'A', require: '^stTable', link: function (scope, element, attr, ctrl) { var predicate = attr.stSort; var getter = $parse(predicate); var index = 0; var classAscent = attr.stClassAscent || 'st-sort-ascent'; var classDescent = attr.stClassDescent || 'st-sort-descent'; var stateClasses = [classAscent, classDescent]; //view --> table state function sort() { index++; if (index % 3 === 0 && attr.stSkipNatural === undefined) { //manual reset index = 0; ctrl.tableState().sort = {}; ctrl.tableState().pagination.start = 0; ctrl.pipe(); } else { ctrl.sortBy(predicate, index % 2 === 0); } } if (ng.isFunction(getter(scope))) { predicate = getter(scope); } element.bind('click', function sortClick() { if (predicate) { scope.$apply(sort); } }); if (attr.stSortDefault !== undefined) { index = attr.stSortDefault === 'reverse' ? 1 : 0; sort(); } //table state --> view scope.$watch(function () { return ctrl.tableState().sort; }, function (newValue) { if (newValue.predicate !== predicate) { index = 0; element .removeClass(classAscent) .removeClass(classDescent); } else { index = newValue.reverse === true ? 2 : 1; element .removeClass(stateClasses[index % 2]) .addClass(stateClasses[index - 1]); } }, true); } }; }]); })(angular); (function (ng) { 'use strict'; ng.module('smart-table') .directive('stPagination', function () { return { restrict: 'EA', require: '^stTable', scope: { stItemsByPage: '=?', stDisplayedPages: '=?' }, templateUrl: 'template/smart-table/pagination.html', link: function (scope, element, attrs, ctrl) { scope.stItemsByPage = scope.stItemsByPage ? +(scope.stItemsByPage) : 10; scope.stDisplayedPages = scope.stDisplayedPages ? +(scope.stDisplayedPages) : 5; scope.currentPage = 1; scope.pages = []; function redraw() { var paginationState = ctrl.tableState().pagination; var start = 1; var end; var i; scope.currentPage = Math.floor(paginationState.start / paginationState.number) + 1; start = Math.max(start, scope.currentPage - Math.abs(Math.floor(scope.stDisplayedPages / 2))); end = start + scope.stDisplayedPages; if (end > paginationState.numberOfPages) { end = paginationState.numberOfPages + 1; start = Math.max(1, end - scope.stDisplayedPages); } scope.pages = []; scope.numPages = paginationState.numberOfPages; for (i = start; i < end; i++) { scope.pages.push(i); } } //table state --> view scope.$watch(function () { return ctrl.tableState().pagination; }, redraw, true); //scope --> table state (--> view) scope.$watch('stItemsByPage', function () { scope.selectPage(1); }); scope.$watch('stDisplayedPages', redraw); //view -> table state scope.selectPage = function (page) { if (page > 0 && page <= scope.numPages) { ctrl.slice((page - 1) * scope.stItemsByPage, scope.stItemsByPage); } }; //select the first page ctrl.slice(0, scope.stItemsByPage); } }; }); })(angular); (function (ng) { 'use strict'; ng.module('smart-table') .directive('stPipe', function () { return { require: 'stTable', scope: { stPipe: '=' }, link: { pre: function (scope, element, attrs, ctrl) { if (ng.isFunction(scope.stPipe)) { ctrl.preventPipeOnWatch(); ctrl.pipe = ng.bind(ctrl, scope.stPipe, ctrl.tableState()); } } } }; }); })(angular);
import { isBlank, isPresent } from 'angular2/src/facade/lang'; import { BaseException } from 'angular2/src/facade/exceptions'; import { StringMapWrapper } from 'angular2/src/facade/collection'; import * as cd from 'angular2/src/core/change_detection/pipes'; export class ProtoPipes { constructor( /** * Map of {@link PipeMetadata} names to {@link PipeMetadata} implementations. */ config) { this.config = config; this.config = config; } static fromProviders(providers) { var config = {}; providers.forEach(b => config[b.name] = b); return new ProtoPipes(config); } get(name) { var provider = this.config[name]; if (isBlank(provider)) throw new BaseException(`Cannot find pipe '${name}'.`); return provider; } } export class Pipes { constructor(proto, injector) { this.proto = proto; this.injector = injector; /** @internal */ this._config = {}; } get(name) { var cached = StringMapWrapper.get(this._config, name); if (isPresent(cached)) return cached; var p = this.proto.get(name); var transform = this.injector.instantiateResolved(p); var res = new cd.SelectedPipe(transform, p.pure); if (p.pure) { StringMapWrapper.set(this._config, name, res); } return res; } }
/** * Source code: * function foo(): Bar { } */ exports.parse = () => ({ "type": "Program", "range": [ 0, 23 ], "loc": { "start": { "line": 1, "column": 0 }, "end": { "line": 1, "column": 23 } }, "body": [ { "type": "FunctionDeclaration", "range": [ 0, 23 ], "loc": { "start": { "line": 1, "column": 0 }, "end": { "line": 1, "column": 23 } }, "id": { "type": "Identifier", "range": [ 9, 12 ], "loc": { "start": { "line": 1, "column": 9 }, "end": { "line": 1, "column": 12 } }, "name": "foo" }, "generator": false, "expression": false, "async": false, "params": [], "body": { "type": "BlockStatement", "range": [ 20, 23 ], "loc": { "start": { "line": 1, "column": 20 }, "end": { "line": 1, "column": 23 } }, "body": [] }, "returnType": { "type": "TypeAnnotation", "loc": { "start": { "line": 1, "column": 16 }, "end": { "line": 1, "column": 19 } }, "range": [ 16, 19 ], "typeAnnotation": { "type": "TypeReference", "range": [ 16, 19 ], "loc": { "start": { "line": 1, "column": 16 }, "end": { "line": 1, "column": 19 } }, "typeName": { "type": "Identifier", "range": [ 16, 19 ], "loc": { "start": { "line": 1, "column": 16 }, "end": { "line": 1, "column": 19 } }, "name": "Bar" } } } } ], "sourceType": "script", "tokens": [ { "type": "Keyword", "value": "function", "start": 0, "end": 8, "range": [ 0, 8 ], "loc": { "start": { "line": 1, "column": 0 }, "end": { "line": 1, "column": 8 } } }, { "type": "Identifier", "value": "foo", "start": 9, "end": 12, "range": [ 9, 12 ], "loc": { "start": { "line": 1, "column": 9 }, "end": { "line": 1, "column": 12 } } }, { "type": "Punctuator", "value": "(", "start": 12, "end": 13, "range": [ 12, 13 ], "loc": { "start": { "line": 1, "column": 12 }, "end": { "line": 1, "column": 13 } } }, { "type": "Punctuator", "value": ")", "start": 13, "end": 14, "range": [ 13, 14 ], "loc": { "start": { "line": 1, "column": 13 }, "end": { "line": 1, "column": 14 } } }, { "type": "Punctuator", "value": ":", "start": 14, "end": 15, "range": [ 14, 15 ], "loc": { "start": { "line": 1, "column": 14 }, "end": { "line": 1, "column": 15 } } }, { "type": "Identifier", "value": "Bar", "start": 16, "end": 19, "range": [ 16, 19 ], "loc": { "start": { "line": 1, "column": 16 }, "end": { "line": 1, "column": 19 } } }, { "type": "Punctuator", "value": "{", "start": 20, "end": 21, "range": [ 20, 21 ], "loc": { "start": { "line": 1, "column": 20 }, "end": { "line": 1, "column": 21 } } }, { "type": "Punctuator", "value": "}", "start": 22, "end": 23, "range": [ 22, 23 ], "loc": { "start": { "line": 1, "column": 22 }, "end": { "line": 1, "column": 23 } } } ], "comments": [] });
/* -*- Mode: Javascript; indent-tabs-mode:nil; js-indent-level: 2 -*- */ /* vim: set ts=2 et sw=2 tw=80: */ /************************************************************* * * MathJax/extensions/TeX/newcommand.js * * Implements the \newcommand, \newenvironment and \def * macros, and is loaded automatically when needed. * * --------------------------------------------------------------------- * * Copyright (c) 2009-2016 The MathJax Consortium * * 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. */ MathJax.Extension["TeX/newcommand"] = { version: "2.7.0" }; MathJax.Hub.Register.StartupHook("TeX Jax Ready",function () { var TEX = MathJax.InputJax.TeX; var TEXDEF = TEX.Definitions; TEXDEF.Add({ macros: { newcommand: 'NewCommand', renewcommand: 'NewCommand', newenvironment: 'NewEnvironment', renewenvironment: 'NewEnvironment', def: 'MacroDef', let: 'Let' } },null,true); TEX.Parse.Augment({ /* * Implement \newcommand{\name}[n][default]{...} */ NewCommand: function (name) { var cs = this.trimSpaces(this.GetArgument(name)), n = this.GetBrackets(name), opt = this.GetBrackets(name), def = this.GetArgument(name); if (cs.charAt(0) === "\\") {cs = cs.substr(1)} if (!cs.match(/^(.|[a-z]+)$/i)) { TEX.Error(["IllegalControlSequenceName", "Illegal control sequence name for %1",name]); } if (n) { n = this.trimSpaces(n); if (!n.match(/^[0-9]+$/)) { TEX.Error(["IllegalParamNumber", "Illegal number of parameters specified in %1",name]); } } this.setDef(cs,['Macro',def,n,opt]); }, /* * Implement \newenvironment{name}[n][default]{begincmd}{endcmd} */ NewEnvironment: function (name) { var env = this.trimSpaces(this.GetArgument(name)), n = this.GetBrackets(name), opt = this.GetBrackets(name), bdef = this.GetArgument(name), edef = this.GetArgument(name); if (n) { n = this.trimSpaces(n); if (!n.match(/^[0-9]+$/)) { TEX.Error(["IllegalParamNumber", "Illegal number of parameters specified in %1",name]); } } this.setEnv(env,['BeginEnv',[null,'EndEnv'],bdef,edef,n,opt]); }, /* * Implement \def command */ MacroDef: function (name) { var cs = this.GetCSname(name), params = this.GetTemplate(name,"\\"+cs), def = this.GetArgument(name); if (!(params instanceof Array)) {this.setDef(cs,['Macro',def,params])} else {this.setDef(cs,['MacroWithTemplate',def].concat(params))} }, /* * Implements the \let command */ Let: function (name) { var cs = this.GetCSname(name), macro; var c = this.GetNext(); if (c === "=") {this.i++; c = this.GetNext()} // // All \let commands create entries in the macros array, but we // have to look in the various mathchar and delimiter arrays if // the source isn't a macro already, and attach the data to a // macro with the proper routine to process it. // // A command of the form \let\cs=char produces a macro equivalent // to \def\cs{char}, which is as close as MathJax can get for this. // So \let\bgroup={ is possible, but doesn't work as it does in TeX. // if (c === "\\") { name = this.GetCSname(name); macro = this.csFindMacro(name); if (!macro) { if (TEXDEF.mathchar0mi[name]) {macro = ["csMathchar0mi",TEXDEF.mathchar0mi[name]]} else if (TEXDEF.mathchar0mo[name]) {macro = ["csMathchar0mo",TEXDEF.mathchar0mo[name]]} else if (TEXDEF.mathchar7[name]) {macro = ["csMathchar7",TEXDEF.mathchar7[name]]} else if (TEXDEF.delimiter["\\"+name] != null) {macro = ["csDelimiter",TEXDEF.delimiter["\\"+name]]} else return; } } else {macro = ["Macro",c]; this.i++} this.setDef(cs,macro); }, /* * Routines to set the macro and environment definitions * (overridden by begingroup to make localized versions) */ setDef: function (name,value) {value.isUser = true; TEXDEF.macros[name] = value}, setEnv: function (name,value) {value.isUser = true; TEXDEF.environment[name] = value}, /* * Get a CS name or give an error */ GetCSname: function (cmd) { var c = this.GetNext(); if (c !== "\\") { TEX.Error(["MissingCS", "%1 must be followed by a control sequence", cmd]) } var cs = this.trimSpaces(this.GetArgument(cmd)); return cs.substr(1); }, /* * Get a \def parameter template */ GetTemplate: function (cmd,cs) { var c, params = [], n = 0; c = this.GetNext(); var i = this.i; while (this.i < this.string.length) { c = this.GetNext(); if (c === '#') { if (i !== this.i) {params[n] = this.string.substr(i,this.i-i)} c = this.string.charAt(++this.i); if (!c.match(/^[1-9]$/)) { TEX.Error(["CantUseHash2", "Illegal use of # in template for %1",cs]); } if (parseInt(c) != ++n) { TEX.Error(["SequentialParam", "Parameters for %1 must be numbered sequentially",cs]); } i = this.i+1; } else if (c === '{') { if (i !== this.i) {params[n] = this.string.substr(i,this.i-i)} if (params.length > 0) {return [n,params]} else {return n} } this.i++; } TEX.Error(["MissingReplacementString", "Missing replacement string for definition of %1",cmd]); }, /* * Process a macro with a parameter template */ MacroWithTemplate: function (name,text,n,params) { if (n) { var args = []; this.GetNext(); if (params[0] && !this.MatchParam(params[0])) { TEX.Error(["MismatchUseDef", "Use of %1 doesn't match its definition",name]); } for (var i = 0; i < n; i++) {args.push(this.GetParameter(name,params[i+1]))} text = this.SubstituteArgs(args,text); } this.string = this.AddArgs(text,this.string.slice(this.i)); this.i = 0; if (++this.macroCount > TEX.config.MAXMACROS) { TEX.Error(["MaxMacroSub1", "MathJax maximum macro substitution count exceeded; " + "is there a recursive macro call?"]); } }, /* * Process a user-defined environment */ BeginEnv: function (begin,bdef,edef,n,def) { if (n) { var args = []; if (def != null) { var optional = this.GetBrackets("\\begin{"+name+"}"); args.push(optional == null ? def : optional); } for (var i = args.length; i < n; i++) {args.push(this.GetArgument("\\begin{"+name+"}"))} bdef = this.SubstituteArgs(args,bdef); edef = this.SubstituteArgs([],edef); // no args, but get errors for #n in edef } this.string = this.AddArgs(bdef,this.string.slice(this.i)); this.i = 0; return begin; }, EndEnv: function (begin,bdef,edef,n) { var end = "\\end{\\end\\"+begin.name+"}"; // special version of \end for after edef this.string = this.AddArgs(edef,end+this.string.slice(this.i)); this.i = 0; return null; }, /* * Find a single parameter delimited by a trailing template */ GetParameter: function (name,param) { if (param == null) {return this.GetArgument(name)} var i = this.i, j = 0, hasBraces = 0; while (this.i < this.string.length) { var c = this.string.charAt(this.i); if (c === '{') { if (this.i === i) {hasBraces = 1} this.GetArgument(name); j = this.i - i; } else if (this.MatchParam(param)) { if (hasBraces) {i++; j -= 2} return this.string.substr(i,j); } else if (c === "\\") { this.i++; j++; hasBraces = 0; var match = this.string.substr(this.i).match(/[a-z]+|./i); if (match) {this.i += match[0].length; j = this.i - i} } else { this.i++; j++; hasBraces = 0; } } TEX.Error(["RunawayArgument","Runaway argument for %1?",name]); }, /* * Check if a template is at the current location. * (The match must be exact, with no spacing differences. TeX is * a little more forgiving than this about spaces after macro names) */ MatchParam: function (param) { if (this.string.substr(this.i,param.length) !== param) {return 0} if (param.match(/\\[a-z]+$/i) && this.string.charAt(this.i+param.length).match(/[a-z]/i)) {return 0} this.i += param.length; return 1; } }); TEX.Environment = function (name) { TEXDEF.environment[name] = ['BeginEnv',[null,'EndEnv']].concat([].slice.call(arguments,1)); TEXDEF.environment[name].isUser = true; } MathJax.Hub.Startup.signal.Post("TeX newcommand Ready"); }); MathJax.Ajax.loadComplete("[MathJax]/extensions/TeX/newcommand.js");
version https://git-lfs.github.com/spec/v1 oid sha256:1621564c0ec4863074aa1a97d46d239977f7898a5f6c4860f8299b893dcfdc3a size 5188
var Settings, ghostBookshelf = require('./base'), uuid = require('uuid'), _ = require('lodash'), errors = require('../errors'), Promise = require('bluebird'), validation = require('../data/validation'), events = require('../events'), internalContext = {context: {internal: true}}, i18n = require('../i18n'), defaultSettings; // For neatness, the defaults file is split into categories. // It's much easier for us to work with it as a single level // instead of iterating those categories every time function parseDefaultSettings() { var defaultSettingsInCategories = require('../data/schema/').defaultSettings, defaultSettingsFlattened = {}; _.each(defaultSettingsInCategories, function each(settings, categoryName) { _.each(settings, function each(setting, settingName) { setting.type = categoryName; setting.key = settingName; defaultSettingsFlattened[settingName] = setting; }); }); return defaultSettingsFlattened; } function getDefaultSettings() { if (!defaultSettings) { defaultSettings = parseDefaultSettings(); } return defaultSettings; } // Each setting is saved as a separate row in the database, // but the overlying API treats them as a single key:value mapping Settings = ghostBookshelf.Model.extend({ tableName: 'settings', defaults: function defaults() { return { uuid: uuid.v4(), type: 'core' }; }, emitChange: function emitChange(event) { events.emit('settings' + '.' + event, this); }, initialize: function initialize() { ghostBookshelf.Model.prototype.initialize.apply(this, arguments); this.on('created', function (model) { model.emitChange('added'); model.emitChange(model.attributes.key + '.' + 'added'); }); this.on('updated', function (model) { model.emitChange('edited'); model.emitChange(model.attributes.key + '.' + 'edited'); }); this.on('destroyed', function (model) { model.emitChange('deleted'); model.emitChange(model.attributes.key + '.' + 'deleted'); }); }, validate: function validate(model, attributes, options) { var self = this, setting = this.toJSON(); return validation.validateSchema(self.tableName, setting).then(function then() { return validation.validateSettings(getDefaultSettings(), self); }).then(function () { var themeName = setting.value || ''; if (setting.key !== 'activeTheme' || options.importing) { return; } return validation.validateActiveTheme(themeName, {showWarning: model.isNew()}); }); } }, { findOne: function (data, options) { if (_.isEmpty(data)) { options = data; } // Allow for just passing the key instead of attributes if (!_.isObject(data)) { data = {key: data}; } return Promise.resolve(ghostBookshelf.Model.findOne.call(this, data, options)); }, edit: function (data, options) { var self = this; options = this.filterOptions(options, 'edit'); if (!Array.isArray(data)) { data = [data]; } return Promise.map(data, function (item) { // Accept an array of models as input if (item.toJSON) { item = item.toJSON(); } if (!(_.isString(item.key) && item.key.length > 0)) { return Promise.reject(new errors.ValidationError(i18n.t('errors.models.settings.valueCannotBeBlank'))); } item = self.filterData(item); return Settings.forge({key: item.key}).fetch(options).then(function then(setting) { var saveData = {}; if (setting) { if (item.hasOwnProperty('value')) { saveData.value = item.value; } // Internal context can overwrite type (for fixture migrations) if (options.context && options.context.internal && item.hasOwnProperty('type')) { saveData.type = item.type; } // it's allowed to edit all attributes in case of importing/migrating if (options.importing) { saveData = item; } return setting.save(saveData, options); } return Promise.reject(new errors.NotFoundError(i18n.t('errors.models.settings.unableToFindSetting', {key: item.key}))); }, errors.logAndThrowError); }); }, populateDefault: function (key) { if (!getDefaultSettings()[key]) { return Promise.reject(new errors.NotFoundError(i18n.t('errors.models.settings.unableToFindDefaultSetting', {key: key}))); } return this.findOne({key: key}).then(function then(foundSetting) { if (foundSetting) { return foundSetting; } var defaultSetting = _.clone(getDefaultSettings()[key]); defaultSetting.value = defaultSetting.defaultValue; return Settings.forge(defaultSetting).save(null, internalContext); }); }, populateDefaults: function populateDefaults(options) { options = options || {}; options = _.merge({}, options, internalContext); return this.findAll(options).then(function then(allSettings) { var usedKeys = allSettings.models.map(function mapper(setting) { return setting.get('key'); }), insertOperations = []; _.each(getDefaultSettings(), function each(defaultSetting, defaultSettingKey) { var isMissingFromDB = usedKeys.indexOf(defaultSettingKey) === -1; // Temporary code to deal with old databases with currentVersion settings if (defaultSettingKey === 'databaseVersion' && usedKeys.indexOf('currentVersion') !== -1) { isMissingFromDB = false; } if (isMissingFromDB) { defaultSetting.value = defaultSetting.defaultValue; insertOperations.push(Settings.forge(defaultSetting).save(null, options)); } }); return Promise.all(insertOperations); }); } }); module.exports = { Settings: ghostBookshelf.model('Settings', Settings) };
/******/ (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; /******/ /******/ // identity function for calling harmony imports with the correct context /******/ __webpack_require__.i = function(value) { return value; }; /******/ /******/ // 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 = 94); /******/ }) /************************************************************************/ /******/ ({ /***/ 0: /***/ (function(module, exports) { module.exports = jQuery; /***/ }), /***/ 1: /***/ (function(module, exports) { module.exports = {Foundation: window.Foundation}; /***/ }), /***/ 12: /***/ (function(module, exports) { module.exports = {Touch: window.Foundation.Touch}; /***/ }), /***/ 2: /***/ (function(module, exports) { module.exports = {Plugin: window.Foundation.Plugin}; /***/ }), /***/ 28: /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; Object.defineProperty(__webpack_exports__, "__esModule", { value: true }); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__foundation_core__ = __webpack_require__(1); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__foundation_core___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_0__foundation_core__); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__foundation_slider__ = __webpack_require__(58); __WEBPACK_IMPORTED_MODULE_0__foundation_core__["Foundation"].plugin(__WEBPACK_IMPORTED_MODULE_1__foundation_slider__["a" /* Slider */], 'Slider'); /***/ }), /***/ 3: /***/ (function(module, exports) { module.exports = {rtl: window.Foundation.rtl, GetYoDigits: window.Foundation.GetYoDigits, transitionend: window.Foundation.transitionend}; /***/ }), /***/ 4: /***/ (function(module, exports) { module.exports = {Motion: window.Foundation.Motion, Move: window.Foundation.Move}; /***/ }), /***/ 5: /***/ (function(module, exports) { module.exports = {Keyboard: window.Foundation.Keyboard}; /***/ }), /***/ 58: /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return Slider; }); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_jquery__ = __webpack_require__(0); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_jquery___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_0_jquery__); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__foundation_util_keyboard__ = __webpack_require__(5); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__foundation_util_keyboard___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_1__foundation_util_keyboard__); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__foundation_util_motion__ = __webpack_require__(4); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__foundation_util_motion___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_2__foundation_util_motion__); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__foundation_util_core__ = __webpack_require__(3); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__foundation_util_core___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_3__foundation_util_core__); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__foundation_plugin__ = __webpack_require__(2); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__foundation_plugin___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_4__foundation_plugin__); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_5__foundation_util_touch__ = __webpack_require__(12); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_5__foundation_util_touch___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_5__foundation_util_touch__); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_6__foundation_util_triggers__ = __webpack_require__(7); 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"); } } function _possibleConstructorReturn(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; } function _inherits(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; } /** * Slider module. * @module foundation.slider * @requires foundation.util.motion * @requires foundation.util.triggers * @requires foundation.util.keyboard * @requires foundation.util.touch */ var Slider = function (_Plugin) { _inherits(Slider, _Plugin); function Slider() { _classCallCheck(this, Slider); return _possibleConstructorReturn(this, (Slider.__proto__ || Object.getPrototypeOf(Slider)).apply(this, arguments)); } _createClass(Slider, [{ key: '_setup', /** * Creates a new instance of a slider control. * @class * @name Slider * @param {jQuery} element - jQuery object to make into a slider control. * @param {Object} options - Overrides to the default plugin settings. */ value: function _setup(element, options) { this.$element = element; this.options = __WEBPACK_IMPORTED_MODULE_0_jquery___default.a.extend({}, Slider.defaults, this.$element.data(), options); this.className = 'Slider'; // ie9 back compat // Touch and Triggers inits are idempotent, we just need to make sure it's initialied. __WEBPACK_IMPORTED_MODULE_5__foundation_util_touch__["Touch"].init(__WEBPACK_IMPORTED_MODULE_0_jquery___default.a); __WEBPACK_IMPORTED_MODULE_6__foundation_util_triggers__["a" /* Triggers */].init(__WEBPACK_IMPORTED_MODULE_0_jquery___default.a); this._init(); __WEBPACK_IMPORTED_MODULE_1__foundation_util_keyboard__["Keyboard"].register('Slider', { 'ltr': { 'ARROW_RIGHT': 'increase', 'ARROW_UP': 'increase', 'ARROW_DOWN': 'decrease', 'ARROW_LEFT': 'decrease', 'SHIFT_ARROW_RIGHT': 'increase_fast', 'SHIFT_ARROW_UP': 'increase_fast', 'SHIFT_ARROW_DOWN': 'decrease_fast', 'SHIFT_ARROW_LEFT': 'decrease_fast', 'HOME': 'min', 'END': 'max' }, 'rtl': { 'ARROW_LEFT': 'increase', 'ARROW_RIGHT': 'decrease', 'SHIFT_ARROW_LEFT': 'increase_fast', 'SHIFT_ARROW_RIGHT': 'decrease_fast' } }); } /** * Initilizes the plugin by reading/setting attributes, creating collections and setting the initial position of the handle(s). * @function * @private */ }, { key: '_init', value: function _init() { this.inputs = this.$element.find('input'); this.handles = this.$element.find('[data-slider-handle]'); this.$handle = this.handles.eq(0); this.$input = this.inputs.length ? this.inputs.eq(0) : __WEBPACK_IMPORTED_MODULE_0_jquery___default()('#' + this.$handle.attr('aria-controls')); this.$fill = this.$element.find('[data-slider-fill]').css(this.options.vertical ? 'height' : 'width', 0); var isDbl = false, _this = this; if (this.options.disabled || this.$element.hasClass(this.options.disabledClass)) { this.options.disabled = true; this.$element.addClass(this.options.disabledClass); } if (!this.inputs.length) { this.inputs = __WEBPACK_IMPORTED_MODULE_0_jquery___default()().add(this.$input); this.options.binding = true; } this._setInitAttr(0); if (this.handles[1]) { this.options.doubleSided = true; this.$handle2 = this.handles.eq(1); this.$input2 = this.inputs.length > 1 ? this.inputs.eq(1) : __WEBPACK_IMPORTED_MODULE_0_jquery___default()('#' + this.$handle2.attr('aria-controls')); if (!this.inputs[1]) { this.inputs = this.inputs.add(this.$input2); } isDbl = true; // this.$handle.triggerHandler('click.zf.slider'); this._setInitAttr(1); } // Set handle positions this.setHandles(); this._events(); } }, { key: 'setHandles', value: function setHandles() { var _this3 = this; if (this.handles[1]) { this._setHandlePos(this.$handle, this.inputs.eq(0).val(), true, function () { _this3._setHandlePos(_this3.$handle2, _this3.inputs.eq(1).val(), true); }); } else { this._setHandlePos(this.$handle, this.inputs.eq(0).val(), true); } } }, { key: '_reflow', value: function _reflow() { this.setHandles(); } /** * @function * @private * @param {Number} value - floating point (the value) to be transformed using to a relative position on the slider (the inverse of _value) */ }, { key: '_pctOfBar', value: function _pctOfBar(value) { var pctOfBar = percent(value - this.options.start, this.options.end - this.options.start); switch (this.options.positionValueFunction) { case "pow": pctOfBar = this._logTransform(pctOfBar); break; case "log": pctOfBar = this._powTransform(pctOfBar); break; } return pctOfBar.toFixed(2); } /** * @function * @private * @param {Number} pctOfBar - floating point, the relative position of the slider (typically between 0-1) to be transformed to a value */ }, { key: '_value', value: function _value(pctOfBar) { switch (this.options.positionValueFunction) { case "pow": pctOfBar = this._powTransform(pctOfBar); break; case "log": pctOfBar = this._logTransform(pctOfBar); break; } var value = (this.options.end - this.options.start) * pctOfBar + this.options.start; return value; } /** * @function * @private * @param {Number} value - floating point (typically between 0-1) to be transformed using the log function */ }, { key: '_logTransform', value: function _logTransform(value) { return baseLog(this.options.nonLinearBase, value * (this.options.nonLinearBase - 1) + 1); } /** * @function * @private * @param {Number} value - floating point (typically between 0-1) to be transformed using the power function */ }, { key: '_powTransform', value: function _powTransform(value) { return (Math.pow(this.options.nonLinearBase, value) - 1) / (this.options.nonLinearBase - 1); } /** * Sets the position of the selected handle and fill bar. * @function * @private * @param {jQuery} $hndl - the selected handle to move. * @param {Number} location - floating point between the start and end values of the slider bar. * @param {Function} cb - callback function to fire on completion. * @fires Slider#moved * @fires Slider#changed */ }, { key: '_setHandlePos', value: function _setHandlePos($hndl, location, noInvert, cb) { // don't move if the slider has been disabled since its initialization if (this.$element.hasClass(this.options.disabledClass)) { return; } //might need to alter that slightly for bars that will have odd number selections. location = parseFloat(location); //on input change events, convert string to number...grumble. // prevent slider from running out of bounds, if value exceeds the limits set through options, override the value to min/max if (location < this.options.start) { location = this.options.start; } else if (location > this.options.end) { location = this.options.end; } var isDbl = this.options.doubleSided; if (isDbl) { //this block is to prevent 2 handles from crossing eachother. Could/should be improved. if (this.handles.index($hndl) === 0) { var h2Val = parseFloat(this.$handle2.attr('aria-valuenow')); location = location >= h2Val ? h2Val - this.options.step : location; } else { var h1Val = parseFloat(this.$handle.attr('aria-valuenow')); location = location <= h1Val ? h1Val + this.options.step : location; } } //this is for single-handled vertical sliders, it adjusts the value to account for the slider being "upside-down" //for click and drag events, it's weird due to the scale(-1, 1) css property if (this.options.vertical && !noInvert) { location = this.options.end - location; } var _this = this, vert = this.options.vertical, hOrW = vert ? 'height' : 'width', lOrT = vert ? 'top' : 'left', handleDim = $hndl[0].getBoundingClientRect()[hOrW], elemDim = this.$element[0].getBoundingClientRect()[hOrW], //percentage of bar min/max value based on click or drag point pctOfBar = this._pctOfBar(location), //number of actual pixels to shift the handle, based on the percentage obtained above pxToMove = (elemDim - handleDim) * pctOfBar, //percentage of bar to shift the handle movement = (percent(pxToMove, elemDim) * 100).toFixed(this.options.decimal); //fixing the decimal value for the location number, is passed to other methods as a fixed floating-point value location = parseFloat(location.toFixed(this.options.decimal)); // declare empty object for css adjustments, only used with 2 handled-sliders var css = {}; this._setValues($hndl, location); // TODO update to calculate based on values set to respective inputs?? if (isDbl) { var isLeftHndl = this.handles.index($hndl) === 0, //empty variable, will be used for min-height/width for fill bar dim, //percentage w/h of the handle compared to the slider bar handlePct = ~~(percent(handleDim, elemDim) * 100); //if left handle, the math is slightly different than if it's the right handle, and the left/top property needs to be changed for the fill bar if (isLeftHndl) { //left or top percentage value to apply to the fill bar. css[lOrT] = movement + '%'; //calculate the new min-height/width for the fill bar. dim = parseFloat(this.$handle2[0].style[lOrT]) - movement + handlePct; //this callback is necessary to prevent errors and allow the proper placement and initialization of a 2-handled slider //plus, it means we don't care if 'dim' isNaN on init, it won't be in the future. if (cb && typeof cb === 'function') { cb(); } //this is only needed for the initialization of 2 handled sliders } else { //just caching the value of the left/bottom handle's left/top property var handlePos = parseFloat(this.$handle[0].style[lOrT]); //calculate the new min-height/width for the fill bar. Use isNaN to prevent false positives for numbers <= 0 //based on the percentage of movement of the handle being manipulated, less the opposing handle's left/top position, plus the percentage w/h of the handle itself dim = movement - (isNaN(handlePos) ? (this.options.initialStart - this.options.start) / ((this.options.end - this.options.start) / 100) : handlePos) + handlePct; } // assign the min-height/width to our css object css['min-' + hOrW] = dim + '%'; } this.$element.one('finished.zf.animate', function () { /** * Fires when the handle is done moving. * @event Slider#moved */ _this.$element.trigger('moved.zf.slider', [$hndl]); }); //because we don't know exactly how the handle will be moved, check the amount of time it should take to move. var moveTime = this.$element.data('dragging') ? 1000 / 60 : this.options.moveTime; __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_2__foundation_util_motion__["Move"])(moveTime, $hndl, function () { // adjusting the left/top property of the handle, based on the percentage calculated above // if movement isNaN, that is because the slider is hidden and we cannot determine handle width, // fall back to next best guess. if (isNaN(movement)) { $hndl.css(lOrT, pctOfBar * 100 + '%'); } else { $hndl.css(lOrT, movement + '%'); } if (!_this.options.doubleSided) { //if single-handled, a simple method to expand the fill bar _this.$fill.css(hOrW, pctOfBar * 100 + '%'); } else { //otherwise, use the css object we created above _this.$fill.css(css); } }); /** * Fires when the value has not been change for a given time. * @event Slider#changed */ clearTimeout(_this.timeout); _this.timeout = setTimeout(function () { _this.$element.trigger('changed.zf.slider', [$hndl]); }, _this.options.changedDelay); } /** * Sets the initial attribute for the slider element. * @function * @private * @param {Number} idx - index of the current handle/input to use. */ }, { key: '_setInitAttr', value: function _setInitAttr(idx) { var initVal = idx === 0 ? this.options.initialStart : this.options.initialEnd; var id = this.inputs.eq(idx).attr('id') || __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_3__foundation_util_core__["GetYoDigits"])(6, 'slider'); this.inputs.eq(idx).attr({ 'id': id, 'max': this.options.end, 'min': this.options.start, 'step': this.options.step }); this.inputs.eq(idx).val(initVal); this.handles.eq(idx).attr({ 'role': 'slider', 'aria-controls': id, 'aria-valuemax': this.options.end, 'aria-valuemin': this.options.start, 'aria-valuenow': initVal, 'aria-orientation': this.options.vertical ? 'vertical' : 'horizontal', 'tabindex': 0 }); } /** * Sets the input and `aria-valuenow` values for the slider element. * @function * @private * @param {jQuery} $handle - the currently selected handle. * @param {Number} val - floating point of the new value. */ }, { key: '_setValues', value: function _setValues($handle, val) { var idx = this.options.doubleSided ? this.handles.index($handle) : 0; this.inputs.eq(idx).val(val); $handle.attr('aria-valuenow', val); } /** * Handles events on the slider element. * Calculates the new location of the current handle. * If there are two handles and the bar was clicked, it determines which handle to move. * @function * @private * @param {Object} e - the `event` object passed from the listener. * @param {jQuery} $handle - the current handle to calculate for, if selected. * @param {Number} val - floating point number for the new value of the slider. * TODO clean this up, there's a lot of repeated code between this and the _setHandlePos fn. */ }, { key: '_handleEvent', value: function _handleEvent(e, $handle, val) { var value, hasVal; if (!val) { //click or drag events e.preventDefault(); var _this = this, vertical = this.options.vertical, param = vertical ? 'height' : 'width', direction = vertical ? 'top' : 'left', eventOffset = vertical ? e.pageY : e.pageX, halfOfHandle = this.$handle[0].getBoundingClientRect()[param] / 2, barDim = this.$element[0].getBoundingClientRect()[param], windowScroll = vertical ? __WEBPACK_IMPORTED_MODULE_0_jquery___default()(window).scrollTop() : __WEBPACK_IMPORTED_MODULE_0_jquery___default()(window).scrollLeft(); var elemOffset = this.$element.offset()[direction]; // touch events emulated by the touch util give position relative to screen, add window.scroll to event coordinates... // best way to guess this is simulated is if clientY == pageY if (e.clientY === e.pageY) { eventOffset = eventOffset + windowScroll; } var eventFromBar = eventOffset - elemOffset; var barXY; if (eventFromBar < 0) { barXY = 0; } else if (eventFromBar > barDim) { barXY = barDim; } else { barXY = eventFromBar; } var offsetPct = percent(barXY, barDim); value = this._value(offsetPct); // turn everything around for RTL, yay math! if (__webpack_require__.i(__WEBPACK_IMPORTED_MODULE_3__foundation_util_core__["rtl"])() && !this.options.vertical) { value = this.options.end - value; } value = _this._adjustValue(null, value); //boolean flag for the setHandlePos fn, specifically for vertical sliders hasVal = false; if (!$handle) { //figure out which handle it is, pass it to the next function. var firstHndlPos = absPosition(this.$handle, direction, barXY, param), secndHndlPos = absPosition(this.$handle2, direction, barXY, param); $handle = firstHndlPos <= secndHndlPos ? this.$handle : this.$handle2; } } else { //change event on input value = this._adjustValue(null, val); hasVal = true; } this._setHandlePos($handle, value, hasVal); } /** * Adjustes value for handle in regard to step value. returns adjusted value * @function * @private * @param {jQuery} $handle - the selected handle. * @param {Number} value - value to adjust. used if $handle is falsy */ }, { key: '_adjustValue', value: function _adjustValue($handle, value) { var val, step = this.options.step, div = parseFloat(step / 2), left, prev_val, next_val; if (!!$handle) { val = parseFloat($handle.attr('aria-valuenow')); } else { val = value; } left = val % step; prev_val = val - left; next_val = prev_val + step; if (left === 0) { return val; } val = val >= prev_val + div ? next_val : prev_val; return val; } /** * Adds event listeners to the slider elements. * @function * @private */ }, { key: '_events', value: function _events() { this._eventsForHandle(this.$handle); if (this.handles[1]) { this._eventsForHandle(this.$handle2); } } /** * Adds event listeners a particular handle * @function * @private * @param {jQuery} $handle - the current handle to apply listeners to. */ }, { key: '_eventsForHandle', value: function _eventsForHandle($handle) { var _this = this, curHandle, timer; this.inputs.off('change.zf.slider').on('change.zf.slider', function (e) { var idx = _this.inputs.index(__WEBPACK_IMPORTED_MODULE_0_jquery___default()(this)); _this._handleEvent(e, _this.handles.eq(idx), __WEBPACK_IMPORTED_MODULE_0_jquery___default()(this).val()); }); if (this.options.clickSelect) { this.$element.off('click.zf.slider').on('click.zf.slider', function (e) { if (_this.$element.data('dragging')) { return false; } if (!__WEBPACK_IMPORTED_MODULE_0_jquery___default()(e.target).is('[data-slider-handle]')) { if (_this.options.doubleSided) { _this._handleEvent(e); } else { _this._handleEvent(e, _this.$handle); } } }); } if (this.options.draggable) { this.handles.addTouch(); var $body = __WEBPACK_IMPORTED_MODULE_0_jquery___default()('body'); $handle.off('mousedown.zf.slider').on('mousedown.zf.slider', function (e) { $handle.addClass('is-dragging'); _this.$fill.addClass('is-dragging'); // _this.$element.data('dragging', true); curHandle = __WEBPACK_IMPORTED_MODULE_0_jquery___default()(e.currentTarget); $body.on('mousemove.zf.slider', function (e) { e.preventDefault(); _this._handleEvent(e, curHandle); }).on('mouseup.zf.slider', function (e) { _this._handleEvent(e, curHandle); $handle.removeClass('is-dragging'); _this.$fill.removeClass('is-dragging'); _this.$element.data('dragging', false); $body.off('mousemove.zf.slider mouseup.zf.slider'); }); }) // prevent events triggered by touch .on('selectstart.zf.slider touchmove.zf.slider', function (e) { e.preventDefault(); }); } $handle.off('keydown.zf.slider').on('keydown.zf.slider', function (e) { var _$handle = __WEBPACK_IMPORTED_MODULE_0_jquery___default()(this), idx = _this.options.doubleSided ? _this.handles.index(_$handle) : 0, oldValue = parseFloat(_this.inputs.eq(idx).val()), newValue; // handle keyboard event with keyboard util __WEBPACK_IMPORTED_MODULE_1__foundation_util_keyboard__["Keyboard"].handleKey(e, 'Slider', { decrease: function () { newValue = oldValue - _this.options.step; }, increase: function () { newValue = oldValue + _this.options.step; }, decrease_fast: function () { newValue = oldValue - _this.options.step * 10; }, increase_fast: function () { newValue = oldValue + _this.options.step * 10; }, min: function () { newValue = _this.options.start; }, max: function () { newValue = _this.options.end; }, handled: function () { // only set handle pos when event was handled specially e.preventDefault(); _this._setHandlePos(_$handle, newValue, true); } }); /*if (newValue) { // if pressed key has special function, update value e.preventDefault(); _this._setHandlePos(_$handle, newValue); }*/ }); } /** * Destroys the slider plugin. */ }, { key: '_destroy', value: function _destroy() { this.handles.off('.zf.slider'); this.inputs.off('.zf.slider'); this.$element.off('.zf.slider'); clearTimeout(this.timeout); } }]); return Slider; }(__WEBPACK_IMPORTED_MODULE_4__foundation_plugin__["Plugin"]); Slider.defaults = { /** * Minimum value for the slider scale. * @option * @type {number} * @default 0 */ start: 0, /** * Maximum value for the slider scale. * @option * @type {number} * @default 100 */ end: 100, /** * Minimum value change per change event. * @option * @type {number} * @default 1 */ step: 1, /** * Value at which the handle/input *(left handle/first input)* should be set to on initialization. * @option * @type {number} * @default 0 */ initialStart: 0, /** * Value at which the right handle/second input should be set to on initialization. * @option * @type {number} * @default 100 */ initialEnd: 100, /** * Allows the input to be located outside the container and visible. Set to by the JS * @option * @type {boolean} * @default false */ binding: false, /** * Allows the user to click/tap on the slider bar to select a value. * @option * @type {boolean} * @default true */ clickSelect: true, /** * Set to true and use the `vertical` class to change alignment to vertical. * @option * @type {boolean} * @default false */ vertical: false, /** * Allows the user to drag the slider handle(s) to select a value. * @option * @type {boolean} * @default true */ draggable: true, /** * Disables the slider and prevents event listeners from being applied. Double checked by JS with `disabledClass`. * @option * @type {boolean} * @default false */ disabled: false, /** * Allows the use of two handles. Double checked by the JS. Changes some logic handling. * @option * @type {boolean} * @default false */ doubleSided: false, /** * Potential future feature. */ // steps: 100, /** * Number of decimal places the plugin should go to for floating point precision. * @option * @type {number} * @default 2 */ decimal: 2, /** * Time delay for dragged elements. */ // dragDelay: 0, /** * Time, in ms, to animate the movement of a slider handle if user clicks/taps on the bar. Needs to be manually set if updating the transition time in the Sass settings. * @option * @type {number} * @default 200 */ moveTime: 200, //update this if changing the transition time in the sass /** * Class applied to disabled sliders. * @option * @type {string} * @default 'disabled' */ disabledClass: 'disabled', /** * Will invert the default layout for a vertical<span data-tooltip title="who would do this???"> </span>slider. * @option * @type {boolean} * @default false */ invertVertical: false, /** * Milliseconds before the `changed.zf-slider` event is triggered after value change. * @option * @type {number} * @default 500 */ changedDelay: 500, /** * Basevalue for non-linear sliders * @option * @type {number} * @default 5 */ nonLinearBase: 5, /** * Basevalue for non-linear sliders, possible values are: `'linear'`, `'pow'` & `'log'`. Pow and Log use the nonLinearBase setting. * @option * @type {string} * @default 'linear' */ positionValueFunction: 'linear' }; function percent(frac, num) { return frac / num; } function absPosition($handle, dir, clickPos, param) { return Math.abs($handle.position()[dir] + $handle[param]() / 2 - clickPos); } function baseLog(base, value) { return Math.log(value) / Math.log(base); } /***/ }), /***/ 7: /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return Triggers; }); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_jquery__ = __webpack_require__(0); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_jquery___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_0_jquery__); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__foundation_util_motion__ = __webpack_require__(4); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__foundation_util_motion___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_1__foundation_util_motion__); var MutationObserver = function () { var prefixes = ['WebKit', 'Moz', 'O', 'Ms', '']; for (var i = 0; i < prefixes.length; i++) { if (prefixes[i] + 'MutationObserver' in window) { return window[prefixes[i] + 'MutationObserver']; } } return false; }(); var triggers = function (el, type) { el.data(type).split(' ').forEach(function (id) { __WEBPACK_IMPORTED_MODULE_0_jquery___default()('#' + id)[type === 'close' ? 'trigger' : 'triggerHandler'](type + '.zf.trigger', [el]); }); }; var Triggers = { Listeners: { Basic: {}, Global: {} }, Initializers: {} }; Triggers.Listeners.Basic = { openListener: function () { triggers(__WEBPACK_IMPORTED_MODULE_0_jquery___default()(this), 'open'); }, closeListener: function () { var id = __WEBPACK_IMPORTED_MODULE_0_jquery___default()(this).data('close'); if (id) { triggers(__WEBPACK_IMPORTED_MODULE_0_jquery___default()(this), 'close'); } else { __WEBPACK_IMPORTED_MODULE_0_jquery___default()(this).trigger('close.zf.trigger'); } }, toggleListener: function () { var id = __WEBPACK_IMPORTED_MODULE_0_jquery___default()(this).data('toggle'); if (id) { triggers(__WEBPACK_IMPORTED_MODULE_0_jquery___default()(this), 'toggle'); } else { __WEBPACK_IMPORTED_MODULE_0_jquery___default()(this).trigger('toggle.zf.trigger'); } }, closeableListener: function (e) { e.stopPropagation(); var animation = __WEBPACK_IMPORTED_MODULE_0_jquery___default()(this).data('closable'); if (animation !== '') { __WEBPACK_IMPORTED_MODULE_1__foundation_util_motion__["Motion"].animateOut(__WEBPACK_IMPORTED_MODULE_0_jquery___default()(this), animation, function () { __WEBPACK_IMPORTED_MODULE_0_jquery___default()(this).trigger('closed.zf'); }); } else { __WEBPACK_IMPORTED_MODULE_0_jquery___default()(this).fadeOut().trigger('closed.zf'); } }, toggleFocusListener: function () { var id = __WEBPACK_IMPORTED_MODULE_0_jquery___default()(this).data('toggle-focus'); __WEBPACK_IMPORTED_MODULE_0_jquery___default()('#' + id).triggerHandler('toggle.zf.trigger', [__WEBPACK_IMPORTED_MODULE_0_jquery___default()(this)]); } }; // Elements with [data-open] will reveal a plugin that supports it when clicked. Triggers.Initializers.addOpenListener = function ($elem) { $elem.off('click.zf.trigger', Triggers.Listeners.Basic.openListener); $elem.on('click.zf.trigger', '[data-open]', Triggers.Listeners.Basic.openListener); }; // Elements with [data-close] will close a plugin that supports it when clicked. // If used without a value on [data-close], the event will bubble, allowing it to close a parent component. Triggers.Initializers.addCloseListener = function ($elem) { $elem.off('click.zf.trigger', Triggers.Listeners.Basic.closeListener); $elem.on('click.zf.trigger', '[data-close]', Triggers.Listeners.Basic.closeListener); }; // Elements with [data-toggle] will toggle a plugin that supports it when clicked. Triggers.Initializers.addToggleListener = function ($elem) { $elem.off('click.zf.trigger', Triggers.Listeners.Basic.toggleListener); $elem.on('click.zf.trigger', '[data-toggle]', Triggers.Listeners.Basic.toggleListener); }; // Elements with [data-closable] will respond to close.zf.trigger events. Triggers.Initializers.addCloseableListener = function ($elem) { $elem.off('close.zf.trigger', Triggers.Listeners.Basic.closeableListener); $elem.on('close.zf.trigger', '[data-closeable], [data-closable]', Triggers.Listeners.Basic.closeableListener); }; // Elements with [data-toggle-focus] will respond to coming in and out of focus Triggers.Initializers.addToggleFocusListener = function ($elem) { $elem.off('focus.zf.trigger blur.zf.trigger', Triggers.Listeners.Basic.toggleFocusListener); $elem.on('focus.zf.trigger blur.zf.trigger', '[data-toggle-focus]', Triggers.Listeners.Basic.toggleFocusListener); }; // More Global/complex listeners and triggers Triggers.Listeners.Global = { resizeListener: function ($nodes) { if (!MutationObserver) { //fallback for IE 9 $nodes.each(function () { __WEBPACK_IMPORTED_MODULE_0_jquery___default()(this).triggerHandler('resizeme.zf.trigger'); }); } //trigger all listening elements and signal a resize event $nodes.attr('data-events', "resize"); }, scrollListener: function ($nodes) { if (!MutationObserver) { //fallback for IE 9 $nodes.each(function () { __WEBPACK_IMPORTED_MODULE_0_jquery___default()(this).triggerHandler('scrollme.zf.trigger'); }); } //trigger all listening elements and signal a scroll event $nodes.attr('data-events', "scroll"); }, closeMeListener: function (e, pluginId) { var plugin = e.namespace.split('.')[0]; var plugins = __WEBPACK_IMPORTED_MODULE_0_jquery___default()('[data-' + plugin + ']').not('[data-yeti-box="' + pluginId + '"]'); plugins.each(function () { var _this = __WEBPACK_IMPORTED_MODULE_0_jquery___default()(this); _this.triggerHandler('close.zf.trigger', [_this]); }); } }; // Global, parses whole document. Triggers.Initializers.addClosemeListener = function (pluginName) { var yetiBoxes = __WEBPACK_IMPORTED_MODULE_0_jquery___default()('[data-yeti-box]'), plugNames = ['dropdown', 'tooltip', 'reveal']; if (pluginName) { if (typeof pluginName === 'string') { plugNames.push(pluginName); } else if (typeof pluginName === 'object' && typeof pluginName[0] === 'string') { plugNames.concat(pluginName); } else { console.error('Plugin names must be strings'); } } if (yetiBoxes.length) { var listeners = plugNames.map(function (name) { return 'closeme.zf.' + name; }).join(' '); __WEBPACK_IMPORTED_MODULE_0_jquery___default()(window).off(listeners).on(listeners, Triggers.Listeners.Global.closeMeListener); } }; function debounceGlobalListener(debounce, trigger, listener) { var timer = void 0, args = Array.prototype.slice.call(arguments, 3); __WEBPACK_IMPORTED_MODULE_0_jquery___default()(window).off(trigger).on(trigger, function (e) { if (timer) { clearTimeout(timer); } timer = setTimeout(function () { listener.apply(null, args); }, debounce || 10); //default time to emit scroll event }); } Triggers.Initializers.addResizeListener = function (debounce) { var $nodes = __WEBPACK_IMPORTED_MODULE_0_jquery___default()('[data-resize]'); if ($nodes.length) { debounceGlobalListener(debounce, 'resize.zf.trigger', Triggers.Listeners.Global.resizeListener, $nodes); } }; Triggers.Initializers.addScrollListener = function (debounce) { var $nodes = __WEBPACK_IMPORTED_MODULE_0_jquery___default()('[data-scroll]'); if ($nodes.length) { debounceGlobalListener(debounce, 'scroll.zf.trigger', Triggers.Listeners.Global.scrollListener, $nodes); } }; Triggers.Initializers.addMutationEventsListener = function ($elem) { if (!MutationObserver) { return false; } var $nodes = $elem.find('[data-resize], [data-scroll], [data-mutate]'); //element callback var listeningElementsMutation = function (mutationRecordsList) { var $target = __WEBPACK_IMPORTED_MODULE_0_jquery___default()(mutationRecordsList[0].target); //trigger the event handler for the element depending on type switch (mutationRecordsList[0].type) { case "attributes": if ($target.attr("data-events") === "scroll" && mutationRecordsList[0].attributeName === "data-events") { $target.triggerHandler('scrollme.zf.trigger', [$target, window.pageYOffset]); } if ($target.attr("data-events") === "resize" && mutationRecordsList[0].attributeName === "data-events") { $target.triggerHandler('resizeme.zf.trigger', [$target]); } if (mutationRecordsList[0].attributeName === "style") { $target.closest("[data-mutate]").attr("data-events", "mutate"); $target.closest("[data-mutate]").triggerHandler('mutateme.zf.trigger', [$target.closest("[data-mutate]")]); } break; case "childList": $target.closest("[data-mutate]").attr("data-events", "mutate"); $target.closest("[data-mutate]").triggerHandler('mutateme.zf.trigger', [$target.closest("[data-mutate]")]); break; default: return false; //nothing } }; if ($nodes.length) { //for each element that needs to listen for resizing, scrolling, or mutation add a single observer for (var i = 0; i <= $nodes.length - 1; i++) { var elementObserver = new MutationObserver(listeningElementsMutation); elementObserver.observe($nodes[i], { attributes: true, childList: true, characterData: false, subtree: true, attributeFilter: ["data-events", "style"] }); } } }; Triggers.Initializers.addSimpleListeners = function () { var $document = __WEBPACK_IMPORTED_MODULE_0_jquery___default()(document); Triggers.Initializers.addOpenListener($document); Triggers.Initializers.addCloseListener($document); Triggers.Initializers.addToggleListener($document); Triggers.Initializers.addCloseableListener($document); Triggers.Initializers.addToggleFocusListener($document); }; Triggers.Initializers.addGlobalListeners = function () { var $document = __WEBPACK_IMPORTED_MODULE_0_jquery___default()(document); Triggers.Initializers.addMutationEventsListener($document); Triggers.Initializers.addResizeListener(); Triggers.Initializers.addScrollListener(); Triggers.Initializers.addClosemeListener(); }; Triggers.init = function ($, Foundation) { if (typeof $.triggersInitialized === 'undefined') { var $document = $(document); if (document.readyState === "complete") { Triggers.Initializers.addSimpleListeners(); Triggers.Initializers.addGlobalListeners(); } else { $(window).on('load', function () { Triggers.Initializers.addSimpleListeners(); Triggers.Initializers.addGlobalListeners(); }); } $.triggersInitialized = true; } if (Foundation) { Foundation.Triggers = Triggers; // Legacy included to be backwards compatible for now. Foundation.IHearYou = Triggers.Initializers.addGlobalListeners; } }; /***/ }), /***/ 94: /***/ (function(module, exports, __webpack_require__) { module.exports = __webpack_require__(28); /***/ }) /******/ });
'use strict'; /* * Make sure the process terminates when epoll is used and 'nothing' is * actually done. The epoll addon calls uv_ref and uv_unref to keep nodes * event loop alive. Here we make sure that the addon isn't keeping the event * loop alive unnecessarily long. If the process terminates, everything is ok. * If it hangs, there is a problem. */ var Epoll = require('../build/Release/epoll').Epoll, epoll0 = new Epoll(function () {}), epoll1 = new Epoll(function () {});
import isLaziable from './_isLaziable.js'; import setData from './_setData.js'; import setWrapToString from './_setWrapToString.js'; /** Used to compose bitmasks for function metadata. */ var BIND_FLAG = 1, BIND_KEY_FLAG = 2, CURRY_BOUND_FLAG = 4, CURRY_FLAG = 8, PARTIAL_FLAG = 32, PARTIAL_RIGHT_FLAG = 64; /** * Creates a function that wraps `func` to continue currying. * * @private * @param {Function} func The function to wrap. * @param {number} bitmask The bitmask flags. See `createWrap` for more details. * @param {Function} wrapFunc The function to create the `func` wrapper. * @param {*} placeholder The placeholder value. * @param {*} [thisArg] The `this` binding of `func`. * @param {Array} [partials] The arguments to prepend to those provided to * the new function. * @param {Array} [holders] The `partials` placeholder indexes. * @param {Array} [argPos] The argument positions of the new function. * @param {number} [ary] The arity cap of `func`. * @param {number} [arity] The arity of `func`. * @returns {Function} Returns the new wrapped function. */ function createRecurry(func, bitmask, wrapFunc, placeholder, thisArg, partials, holders, argPos, ary, arity) { var isCurry = bitmask & CURRY_FLAG, newHolders = isCurry ? holders : undefined, newHoldersRight = isCurry ? undefined : holders, newPartials = isCurry ? partials : undefined, newPartialsRight = isCurry ? undefined : partials; bitmask |= (isCurry ? PARTIAL_FLAG : PARTIAL_RIGHT_FLAG); bitmask &= ~(isCurry ? PARTIAL_RIGHT_FLAG : PARTIAL_FLAG); if (!(bitmask & CURRY_BOUND_FLAG)) { bitmask &= ~(BIND_FLAG | BIND_KEY_FLAG); } var newData = [ func, bitmask, thisArg, newPartials, newHolders, newPartialsRight, newHoldersRight, argPos, ary, arity ]; var result = wrapFunc.apply(undefined, newData); if (isLaziable(func)) { setData(result, newData); } result.placeholder = placeholder; return setWrapToString(result, func, bitmask); } export default createRecurry;
(function() { if (document.location.search.indexOf('min=true') > 0) { document.write('<script src="../jscripts/tiny_mce/tiny_mce.js"></script>'); } else { document.write('<script src="../jscripts/tiny_mce/tiny_mce_dev.js' + document.location.search + '"></script>'); } })();
function ob_get_contents() { // http://kevin.vanzonneveld.net // + original by: Brett Zamir (http://brett-zamir.me) // * example 1: ob_get_contents(); // * returns 1: 'some buffer contents' this.php_js = this.php_js || {}; var phpjs = this.php_js, ini = phpjs.ini, obs = phpjs.obs; if (!obs || !obs.length) { return (ini && ini.output_buffering && (typeof ini.output_buffering.local_value !== 'string' || ini.output_buffering.local_value.toLowerCase() !== 'off')) ? '' : false; // If output was already buffered, it would be available in obs } return obs[obs.length - 1].buffer; // Retrieve most recently added buffer contents }
class PropRegistry { constructor() { this.registry = {}; } save(screenInstanceId = '', passProps = {}) { this.registry[screenInstanceId] = passProps; } load(screenInstanceId = '') { return this.registry[screenInstanceId] || {}; } } module.exports = new PropRegistry();
var selftest = require('../selftest.js'); var Sandbox = selftest.Sandbox; var files = require('../files.js'); var testUtils = require('../test-utils.js'); var utils = require('../utils.js'); var _= require('underscore'); var packageClient = require("../package-client.js"); var catalog = require('../catalog.js'); var DEFAULT_RELEASE_TRACK = catalog.DEFAULT_TRACK; var username = "test"; var password = "testtest"; // Returns a random package name. var randomizedPackageName = function (username, start) { // We often use package names in long, wrapped string output, so having them // be a consistent length is very useful. var startStr = start ? start + "-" : ""; return username + ":" + startStr + utils.randomToken().substring(0, 6); } // Returns a random release name. var randomizedReleaseName = function (username) { // We often use package names in long, wrapped string output, so having them // be the same length is very useful. return username + ":TEST-" + utils.randomToken().substring(0, 6).toUpperCase(); } // Given a sandbox, that has the app as its currend cwd, read the packages file // and check that it contains exactly the packages specified, in order. // // sand: a sandbox, that has the main app directory as its cwd. // packages: an array of packages in order. Packages can be of the form: // // meteor-platform (ie: name), in which case this will match any // version of that package as long as it is included. // // awesome-pack@1.0.0 (ie: name@version) to match that name at that // version explicitly. This is for packages that we included at a specific // version. var checkPackages = selftest.markStack(function(sand, packages) { var lines = sand.read(".meteor/packages").split("\n"); var i = 0; _.each(lines, function(line) { if (!line) return; // If the specified package contains an @ sign, then it has a version // number, so we should match everything. if (packages[i].split('@').length > 1) { selftest.expectEqual(line, packages[i]); } else { var pack = line.split('@')[0]; selftest.expectEqual(pack, packages[i]); } i++; }); selftest.expectEqual(packages.length, i); }); // Given a sandbox, that has the app as its currend cwd, read the versions file // and check that it contains the packages that we are looking for. We don't // check the order, we just want to make sure that the right dependencies are // in. // // sand: a sandbox, that has the main app directory as its cwd. // packages: an array of packages in order. Packages can be of the form: // // meteor-platform (ie: name), in which case this will match any // version of that package as long as it is included. This is for packages // external to the app, since we don't want this test to fail when we push a // new version. // // awesome-pack@1.0.0 (ie: name@version) to match that name at that // version explicitly. This is for packages that only exist for the purpose // of this test (for example, packages local to this app), so we know exactly // what version we expect. var checkVersions = selftest.markStack(function(sand, packages) { var lines = sand.read(".meteor/versions").split("\n"); var depend = {}; _.each(lines, function(line) { if (!line) return; // Packages are stored of the form foo@1.0.0, so this should give us an // array [foo, 1.0.0]. var split = line.split('@'); var pack = split[0]; depend[pack] = split[1]; }); var i = 0; _.each(packages, function (pack) { var split = pack.split('@'); if (split.length > 1) { selftest.expectEqual(depend[split[0]], split[1]); } else { var exists = _.has(depend, split[0]); selftest.expectEqual(exists, true); } i++; }); selftest.expectEqual(packages.length, i); }); // Takes in a remote catalog. Returns an object that can sort of immitate the // catalog. We don't bother to copy all of the information for memory/efficiency // reasons; the new 'catalog' has the following methods, which correspond to the // same methods on the normal catalog. // // getAllPackageNames () - list of package names // getPackage (p) - given a package name, return its record // getSortedVersions (p) - given a package name, return a sorted list of its versions // getAllReleaseTracks () - list of release tracks // getSortedRecommendedReleaseVersions (t) - given a track name, get (see method name) // getReleaseVersion (t, v) - given track & version, return the document record var DataStub = function (remoteCatalog) { var self = this; var packageNames = remoteCatalog.getAllPackageNames(); self.packages = {}; _.each(packageNames, function (p) { var versions = remoteCatalog.getSortedVersions(p); var record = remoteCatalog.getPackage(p); self.packages[p] = { versions: versions, record: record }; }); var releaseTracks = remoteCatalog.getAllReleaseTracks(); self.releases = {}; _.each(releaseTracks, function (t) { var versions = remoteCatalog.getSortedRecommendedReleaseVersions(t); var records = {}; _.each(versions, function (v) { records[v] = remoteCatalog.getReleaseVersion(t, v); }); self.releases[t] = { versions: versions, records: records }; }); }; _.extend(DataStub.prototype, { getAllPackageNames: function () { return _.keys(this.packages); }, getSortedVersions: function (p) { var self = this; var rec = self.packages[p]; if (!rec) return null; return rec.versions; }, getPackage: function (p) { var self = this; var rec = self.packages[p]; if (!rec) return null; return rec.record; }, getAllReleaseTracks: function () { return _.keys(this.releases); }, getSortedRecommendedReleaseVersions: function (t) { var self = this; var rec = self.releases[t]; if (!rec) return null; return rec.versions; }, getReleaseVersion: function (t, v) { var self = this; var rec = self.releases[t]; if (!rec) return null; return rec.records[v]; } }); // Add packages to an app. Change the contents of the packages and their // dependencies, make sure that the app still refreshes. selftest.define("change packages during hot code push", [], function () { var s = new Sandbox(); var run; // Starting a run s.createApp("myapp", "package-tests"); s.cd("myapp"); run = s.run(); run.waitSecs(5); run.match("myapp"); run.match("proxy"); run.match("MongoDB"); run.waitSecs(5); run.match("your app"); run.waitSecs(5); run.match("running at"); run.match("localhost"); // Add the local package 'say-something'. It should print a message. s.write(".meteor/packages", "meteor-platform \n say-something"); run.waitSecs(3); run.match("initial"); // Modify the local package 'say-something'. s.cd("packages/say-something", function () { s.write("foo.js", "console.log(\"another\");"); }); run.waitSecs(12); run.match("another"); // Add a local package depends-on-plugin. s.write(".meteor/packages", "meteor-platform \n depends-on-plugin"); run.waitSecs(2); run.match("foobar"); // Change something in the plugin. s.cd("packages/contains-plugin/plugin", function () { s.write("plugin.js", "console.log(\"edit\");"); }); run.waitSecs(2); run.match("edit"); run.match("foobar!"); // In a local package, add a dependency on a different package. In this case, // package2.js contains an onUse call that tells it to use accounts-base (a // core package that is not already included in the app) s.cp('packages/contains-plugin/package2.js', 'packages/contains-plugin/package.js'); run.waitSecs(2); run.match("edit"); run.match("foobar!"); // Check that we are watching the versions file, as well as the packages file. s.unlink('.meteor/versions'); run.waitSecs(10); run.match("restarted"); // Switch back to say-something for a moment. s.write(".meteor/packages", "meteor-platform \n say-something"); run.waitSecs(3); run.match("another"); run.stop(); s.rename('packages/say-something', 'packages/shout-something'); s.write(".meteor/packages", "meteor-platform \n shout-something"); s.cd("packages/shout-something", function () { s.write("foo.js", "console.log(\"louder\");"); }); run = s.run(); run.waitSecs(5); run.match("myapp"); run.match("proxy"); run.match("MongoDB"); run.waitSecs(5); run.match("louder"); // the package actually loaded // How about breaking and fixing a package.js? s.cd("packages/shout-something", function () { var packageJs = s.read("package.js"); s.write("package.js", "]"); run.waitSecs(3); run.match("=> Errors prevented startup"); run.match("package.js:1:1: Unexpected token ]"); run.match("Waiting for file change"); s.write("package.js", packageJs); run.waitSecs(3); run.match("restarting"); run.match("restarted"); }); run.stop(); }); // Add packages through the command line. Make sure that the correct set of // changes is reflected in .meteor/packages, .meteor/versions and list. Make // sure that debugOnly packages don't show up in production mode. selftest.define("add packages to app", [], function () { var s = new Sandbox(); var run; // Starting a run s.createApp("myapp", "package-tests"); s.cd("myapp"); s.set("METEOR_OFFLINE_CATALOG", "t"); // This has legit version syntax, but accounts-base started with 1.0.0 and is // unlikely to backtrack. run = s.run("add", "accounts-base@0.123.123"); run.matchErr("no such version"); run.expectExit(1); // Adding a nonexistent package at a nonexistent version should print // only one error message, not two. (We used to print "no such // package" and "no such version".) run = s.run("add", "not-a-real-package-and-never-will-be@1.0.0"); run.matchErr("no such package"); run.expectExit(1); run.forbidAll("no such version"); run = s.run("add", "accounts-base"); run.match("accounts-base: A user account system"); run.expectExit(0); checkPackages(s, ["meteor-platform", "accounts-base"]); // Adding the nonexistent version now should still say "no such // version". Regression test for // https://github.com/meteor/meteor/issues/2898. run = s.run("add", "accounts-base@0.123.123"); run.matchErr("no such version"); run.expectExit(1); run.forbidAll("Currently using accounts-base"); run.forbidAll("will be changed to"); run = s.run("--once"); run = s.run("add", "say-something@1.0.0"); run.match("say-something: print to console"); run.expectExit(0); checkPackages(s, ["meteor-platform", "accounts-base", "say-something@1.0.0"]); run = s.run("add", "depends-on-plugin"); run.match(/depends-on-plugin.*added,/); run.expectExit(0); checkPackages(s, ["meteor-platform", "accounts-base", "say-something@1.0.0", "depends-on-plugin"]); checkVersions(s, ["accounts-base", "depends-on-plugin", "say-something", "meteor-platform", "contains-plugin@1.1.0"]); run = s.run("remove", "say-something"); run.match("say-something: removed dependency"); checkVersions(s, ["accounts-base", "depends-on-plugin", "meteor-platform", "contains-plugin"]); run = s.run("remove", "depends-on-plugin"); run.match(/contains-plugin.*removed from your project/); run.match(/depends-on-plugin.*removed from your project/); run.match("depends-on-plugin: removed dependency"); checkVersions(s, ["accounts-base", "meteor-platform"]); run = s.run("list"); run.match("accounts-base"); run.match("meteor-platform"); // Add a description-less package. Check that no weird things get // printed (like "added no-description: undefined"). run = s.run("add", "no-description"); run.match("no-description\n"); run.expectEnd(); run.expectExit(0); // Add a debugOnly package. It should work during a normal run, but print // nothing in production mode. run = s.run("add", "debug-only"); run.match("debug-only"); run.expectExit(0); s.mkdir("server"); s.write("server/debug.js", "process.exit(global.DEBUG_ONLY_LOADED ? 234 : 235)"); run = s.run("--once"); run.waitSecs(15); run.expectExit(234); run = s.run("--once", "--production"); run.waitSecs(15); run.expectExit(235); }); // Add a package that adds files to specific client architectures. selftest.define("add packages client archs", function (options) { var runTestWithArgs = function (clientType, args, port) { var s = new Sandbox({ clients: _.extend(options.clients, { port: port }) }); // Starting a run s.createApp("myapp", "package-tests"); s.cd("myapp"); s.set("METEOR_OFFLINE_CATALOG", "t"); var outerRun = s.run("add", "say-something-client-targets"); outerRun.match(/say-something-client-targets.*added,/); outerRun.expectExit(0); checkPackages(s, ["meteor-platform", "say-something-client-targets"]); var expectedLogNum = 0; s.testWithAllClients(function (run) { run.waitSecs(5); run.match("myapp"); run.match("proxy"); run.waitSecs(5); run.match("MongoDB"); run.waitSecs(5); run.match("running at"); run.match("localhost"); run.connectClient(); run.waitSecs(20); run.match("all clients " + (expectedLogNum++)); run.match(clientType + " client " + (expectedLogNum++)); run.stop(); }, args); }; runTestWithArgs("browser", [], 3000); }); // `packageName` should be a full package name (i.e. <username>:<package // name>), and the sandbox should be logged in as that username. var createAndPublishPackage = selftest.markStack(function (s, packageName) { var packageDirName = "package-of-two-versions"; s.createPackage(packageDirName, packageName, "package-of-two-versions"); s.cd(packageDirName, function (){ var run = s.run("publish", "--create"); run.waitSecs(25); run.expectExit(0); }); return packageDirName; }); selftest.define("release track defaults to METEOR", ["net", "test-package-server", "checkout"], function () { var s = new Sandbox(); testUtils.login(s, username, password); var fullPackageName = randomizedPackageName(username); var releaseVersion = utils.randomToken(); // Create a package that has a versionsFrom for the just-published // release, but without the release track present in the call to // `versionsFrom`. This implies that it should be prefixed // by "METEOR@" var newPack = fullPackageName; var newPackDirName = "random-package"; s.createPackage(newPackDirName, newPack, "package-of-two-versions"); s.cd(newPackDirName, function() { var packOpen = s.read("package.js"); packOpen = packOpen + "\nPackage.onUse(function(api) { \n" + "api.versionsFrom(\"" + releaseVersion + "\");\n" + "api.use(\"" + fullPackageName + "\"); });"; s.write("package.js", packOpen); }); // Try to publish the package. The error message should demonstrate // that we indeed default to the METEOR release track when not // specified. s.cd(newPackDirName, function() { var run = s.run("publish", "--create"); run.waitSecs(20); run.matchErr("Unknown release " + DEFAULT_RELEASE_TRACK + "@" + releaseVersion); run.expectExit(1); }); }); // // THIS TEST RELIES ON THE TEST SERVER HAVING THE SAME RELEASE AS THE PRODUCTION // SERVER. YOU *CAN* RUN IT FROM RELEASE IFF YOU PUBLISH A CORRESPONDING RELEASE // TO THE TEST SERVER. (XXX: fix this post-0.9.0) // // XXX: This test is going to take progressively more time as we run more // tests, and perhaps checks too much information. We should consider // rethinking it in the future. selftest.define("update server package data unit test", ["net", "test-package-server", "checkout", "slow"], function () { var s = new Sandbox(); var run; var packageStorageFileDir = files.mkdtemp("update-server-package-data"); var rC = require('../catalog-remote.js'); var config = require('../config.js'); var packageStorage = new rC.RemoteCatalog(); var packageStorageFile = config.getPackageStorage({ root: packageStorageFileDir, serverUrl: s.env.METEOR_PACKAGE_SERVER_URL }); packageStorage.initialize({ packageStorage : packageStorageFile, // Don't let this catalog refresh: we do that manually, and in any case the // catalog isn't smart enough to refresh with the right URL. offline: true }); testUtils.login(s, username, password); // Get the current data from the server. Once we publish new packages, // we'll check that all this data still appears on disk and hasn't // been overwritten. packageClient.updateServerPackageData(packageStorage, { packageServerUrl: selftest.testPackageServerUrl }); var oldStorage = new DataStub(packageStorage); var newPackageNames = []; // Publish more than a (small) page worth of packages. When we pass the // `useShortPages` option to updateServerPackageData, the server will send 3 // records at a time instead of 100, so this is more than a page. _.times(5, function (i) { var packageName = randomizedPackageName(username); createAndPublishPackage(s, packageName); newPackageNames.push(packageName); }); packageClient.updateServerPackageData(packageStorage, { packageServerUrl: selftest.testPackageServerUrl, useShortPages: true }); var packages = oldStorage.getAllPackageNames(); _.each(packages, function (p) { // We could be more pedantic about comparing all the records, but it // is a significant effort, time-wise to do that. selftest.expectEqual( packageStorage.getPackage(p), oldStorage.getPackage(p)); selftest.expectEqual( packageStorage.getSortedVersions(p), oldStorage.getSortedVersions(p)); }); var releaseTracks = oldStorage.getAllReleaseTracks; _.each(releaseTracks, function (t) { _.each(oldStorage.getSortedRecommendedReleaseVersions(t), function (v) { selftest.expectEqual( packageStorage.getReleaseVersion(t, v), oldStorage.getReleaseVersion(t, v)); }); }); // Check that our newly published packages appear in newData and on disk. _.each(newPackageNames, function (name) { var found = packageStorage.getPackage(name); selftest.expectEqual(!! found, true); }); }); // Add packages to an app. Change the contents of the packages and their // dependencies, make sure that the app still refreshes. selftest.define("package specifying a name", ['test-package-server', "checkout"], function () { var s = new Sandbox(); var run; // Starting a run; introducing a new package overriding a core package. s.createApp("myapp", "package-tests"); s.cd("myapp"); run = s.run("add", "accounts-base"); run.waitSecs(40); run.match("accounts-base"); // Pass --allow-incompatible-update so that when we create a package // that overrides accounts-base and has no version number (interpreted // as version 0.0.0), we don't get an error about downgrading a // a dependency. run = s.run("--allow-incompatible-update"); run.waitSecs(5); run.match("myapp"); run.match("proxy"); run.match("MongoDB.\n"); run.waitSecs(10); run.match("running at"); run.match("localhost"); s.cd("packages", function () { s.createPackage("ac-fake", "ac-fake", "fake-accounts-base"); }); run.waitSecs(5); run.match("overriding accounts-base!"); run.stop(); run = s.run('list'); run.match("accounts-base"); run.match("meteor"); // What about test-packages? s.cd('packages'); s.cd('ac-fake'); // note: use test-in-console because test-in-browser depends on bootstrap // and we don't need an atmosphere dependency. run = s.run('test-packages', './', '--driver-package=test-in-console'); run.waitSecs(15); run.match("overriding accounts-base!"); run.stop(); }); selftest.define("talk to package server with expired or no accounts token", ['net', 'test-package-server', 'slow'], function () { var s = new Sandbox(); testUtils.login(s, "test", "testtest"); // Revoke our credential by logging out. var session = s.readSessionFile(); testUtils.logout(s); testUtils.login(s, "testtest", "testtest"); var packageName = "testtest:" + utils.randomToken(); createAndPublishPackage(s, packageName); testUtils.logout(s); // When we are not logged in, we should get prompted to log in when we // run 'meteor admin maintainers --add'. var run = s.run("admin", "maintainers", packageName, "--add", "foo"); run.waitSecs(15); run.matchErr("Username:"); run.write("test\n"); run.matchErr("Password:"); run.write("testtest\n"); run.waitSecs(15); // The 'test' user should not be a maintainer of // meteor-platform. So this command should fail. run.matchErr("You are not an authorized maintainer"); run.expectExit(1); // Now restore our previous session, so that we now have an expired // accounts token. s.writeSessionFile(session); run = s.run("admin", "maintainers", packageName, "--add", "foo"); run.waitSecs(15); run.matchErr("have been logged out"); run.matchErr("Please log in"); run.matchErr("Username"); run.write("test\n"); run.matchErr("Password:"); run.write("testtest\n"); run.waitSecs(15); run.matchErr("You are not an authorized maintainer"); run.expectExit(1); }); // The cwd of 's' should be a package directory (i.e. with a package.js // file). Pass 'expectAuthorizationFailure' if you expect the publish // command to fail because the currently logged-in user is not an // authorized maintainer of the package. var changeVersionAndPublish = function (s, expectAuthorizationFailure) { var packageJs = s.read("package.js"); // XXX Hack var versionMatch = packageJs.match(/version: \"(\d\.\d\.\d)\"/); if (! versionMatch) { selftest.fail("package.js does not match version field: " + packageJs); } var version = versionMatch[1]; var versionParts = version.split("."); versionParts[0] = parseInt(versionParts[0]) + 1; packageJs = packageJs.replace(version, versionParts.join(".")); s.write("package.js", packageJs); var run = s.run("publish"); run.waitSecs(120); if (expectAuthorizationFailure) { run.matchErr("not an authorized maintainer"); run.expectExit(1); } else { run.match("Published"); run.expectExit(0); } }; selftest.define("packages with organizations", ["net", "test-package-server", "slow"], function () { var s = new Sandbox(); testUtils.login(s, "test", "testtest"); var orgName = testUtils.createOrganization("test", "testtest"); // Publish a package with 'orgName' as the prefix. var packageName = utils.randomToken(); var fullPackageName = orgName + ":" + packageName; var packageDirName = createAndPublishPackage(s, fullPackageName); s.cd(packageDirName); // 'test' should be a maintainer, as well as 'testtest', once // 'testtest' is added to the org. changeVersionAndPublish(s); testUtils.login(s, "testtest", "testtest"); changeVersionAndPublish(s, true /* expect authorization failure */); testUtils.login(s, "test", "testtest"); var run = s.run("admin", "members", orgName, "--add", "testtest"); run.waitSecs(15); run.expectExit(0); testUtils.login(s, "testtest", "testtest"); changeVersionAndPublish(s); // Removing 'orgName' as a maintainer should fail. run = s.run("admin", "maintainers", fullPackageName, "--remove", orgName); run.waitSecs(15); run.matchErr("remove the maintainer in the package"); run.expectExit(1); // Publish a package with 'test' as the prefix. s.cd(".."); testUtils.login(s, "test", "testtest"); fullPackageName = "test:" + utils.randomToken(); var packageDirName2 = createAndPublishPackage(s, fullPackageName); s.cd(packageDirName2); // Add 'orgName' as a maintainer. run = s.run("admin", "maintainers", fullPackageName, "--add", orgName); run.waitSecs(20); run.match("The maintainers for " + fullPackageName + " are"); run.match(orgName); run.expectExit(0); // 'testtest' should now be authorized. testUtils.login(s, "testtest", "testtest"); changeVersionAndPublish(s); // Remove 'orgName' as a maintainer: 'testtest' should no longer be // authorized. testUtils.login(s, "test", "testtest"); run = s.run("admin", "maintainers", fullPackageName, "--remove", orgName); run.waitSecs(15); run.match("The maintainers for " + fullPackageName + " are"); run.forbid(orgName); run.expectExit(0); testUtils.login(s, "testtest", "testtest"); changeVersionAndPublish(s, true /* expect authorization failure */); }); selftest.define("add package with no builds", ["net"], function () { var s = new Sandbox(); // This depends on glasser:binary-package-with-no-builds@1.0.0 existing with // no published builds. s.createApp("myapp", "empty"); s.cd("myapp"); var run = s.run("add", "glasser:binary-package-with-no-builds"); run.waitSecs(10); run.matchErr("glasser:binary-package-with-no-builds@1.0.0"); run.matchErr("No compatible binary build found"); run.expectExit(1); }); selftest.define("package skeleton creates correct versionsFrom", function () { var s = new Sandbox({ warehouse: { v1: { recommended: true } } }); var token = utils.randomToken(); var fullPackageName = "test:" + token; var fsPackageName = token; var run = s.run("create", "--package", fullPackageName); run.waitSecs(15); run.match(fullPackageName); run.expectExit(0); s.cd(fsPackageName); var packageJs = s.read("package.js"); if (! packageJs.match(/api.versionsFrom\('v1'\);/)) { selftest.fail("package.js missing correct 'api.versionsFrom':\n" + packageJs); } }); selftest.define("show unknown version of package", function () { var s = new Sandbox(); // This version doesn't exist and is unlikely to exist. var run = s.run("show", "meteor-platform@0.123.456"); run.waitSecs(5); run.matchErr("meteor-platform@0.123.456: not found"); run.expectExit(1); // This package exists in the server (we need it to publish the tool), but is // not a local package. run = s.run("show", "npm-bcrypt@local"); run.waitSecs(5); run.matchErr("npm-bcrypt@local: not found"); run.expectExit(1); }); selftest.define("circular dependency errors", function () { var s = new Sandbox(); // meteor add refreshes, but we don't need anything from the official catalog // here. s.set('METEOR_OFFLINE_CATALOG', 't'); var run; // This app contains some pairs of packages with circular dependencies The app // currently *uses* no packages, so it can be created successfully. s.createApp("myapp", "circular-deps"); s.cd("myapp"); // Try to add one of a pair of circularly-depending packages. See an error. run = s.run('add', 'first'); run.matchErr('error: circular dependency'); run.expectExit(1); // Note that the app still builds fine because 'first' didn't actually get // added. run = s.run('--prepare-app'); run.expectExit(0); // This pair has first-imply uses second-imply, second-imply implies // first-imply. run = s.run('add', 'first-imply'); run.matchErr('error: circular dependency'); run.expectExit(1); // This pair has first-weak uses second-weak, second-weak uses first-weak // weakly. Currently, it's possible to add a weak cycle to an app (ie, the // prepare-app step passes), but not to run the bundler. We don't want to // write a test that prevents us from making the weak cycle an error at // prepare-time, so let's skip straight to bundling. s.write('.meteor/packages', 'first-weak'); run = s.run('--once'); run.matchErr('error: circular dependency'); run.expectExit(254); // ... but we can add second-weak, which just doesn't pull in first-weak at // all. s.write('.meteor/packages', 'second-weak'); run = s.run('--once'); run.match(/first-weak.*removed from your project/); run.expectExit(123); // the app immediately calls process.exit(123) // This pair has first-unordered uses second-unordered, second-unordered uses // first-unordered unorderedly. This should work just fine: that's why // unordered exists! s.write('.meteor/packages', 'first-unordered'); run = s.run('--once'); run.match(/first-unordered.*added/); run.match(/second-unordered.*added/); run.match(/second-weak.*removed from your project/); run.expectExit(123); // the app immediately calls process.exit(123) }); // Runs 'meteor show <fullPackageName>' without a specified version and checks // that the output is correct. // // - s: sandbox in which to run commands // - fullPackageName: name of the package to show. // - options: // - summary: Expected summary of the latest version. // - description: longform description of the latest version // - maintainers: the string of maintainers // - homepage: Homepage url, if one was set. // - git: Git url, if one was set. // - exports: exports string // - implies: implies string // - defaultVersion: version that git/exports/etc come from // - versions: array of objects representing versions that we have // published, with keys: // - version: version number (ex: 0.9.9) // - date: string we expect to see as the date. // - label: string that we expect to see as the label. (ex: "installed") // - addendum: a message to display at the bottom. // - all: run 'meteor show' with the 'show-all' option. var testShowPackage = selftest.markStack(function (s, fullPackageName, options) { var run; if (options.all) { run = s.run("show", "--show-all", fullPackageName); } else { run = s.run("show", fullPackageName); } var packageName = options.defaultVersion ? fullPackageName + "@" + options.defaultVersion : fullPackageName; run.match("Package: " + packageName + "\n"); if (options.homepage) { run.read("Homepage: " + options.homepage + "\n"); } if (options.maintainers) { run.read("Maintainers: " + options.maintainers + "\n"); } if (options.git) { run.read("Git: " + options.git + "\n"); } if (options.exports) { run.read("Exports: " + options.exports + "\n"); } if (options.implies) { run.read("Implies: " + options.implies + "\n"); } run.read("\n"); if (_.has(options, "description")) { run.read(options.description + "\n"); } else if (_.has(options, "summary")) { run.read(options.summary + "\n"); } if (options.versions) { if (options.all) { run.match("Versions:"); } else { run.match("Recent versions:"); } _.each(options.versions, function (version) { run.match(version.version); if (version.directory) { run.match(version.directory + "\n"); } else { run.match(version.date); if (version.label) { run.match(version.label + "\n"); } else { run.match("\n"); } } }); run.read("\n"); } if (options.addendum) { run.read(options.addendum); } run.expectExit(0); }); // Runs 'meteor show <name>@<version> and checks that the output is correct. // // - s: sandbox // - options: // - packageName: name of the package. // - version: version string. // - summary: summary string of the package. // - description: long-form description of the package // - publishedBy: username of the publisher. // - publishedOn: string of the publication time. // - git: (optional) URL of the git repository. // - dependencies: (optional) an array of objects representing dependencies: // - name: package name // - constraint: constraint, such as "1.0.0" or "=1.0.0" or null. // - weak: true if this is a weak dependency. // - addendum: a message that we expect to display at the very bottom. var testShowPackageVersion = selftest.markStack(function (s, options) { var name = options.packageName; var version = options.version; var run = s.run("show", name + "@" + version); run.match("Package: " + name + "@" + version + "\n"); if (options.directory) { run.match("Directory: " + options.directory + "\n"); } if (options.exports) { run.read("Exports: " + options.exports + "\n"); } if (options.implies) { run.read("Implies: " + options.implies + "\n"); } if (options.git) { run.match("Git: " + options.git + "\n"); } if (_.has(options, "description")) { run.read("\n"); run.read(options.description + "\n"); } else if (_.has(options, "summary")) { run.read("\n"); run.read(options.summary + "\n"); } if (options.dependencies) { run.read("\n"); run.read("Depends on:\n"); // Use 'read' to ensure that these are the only dependencies listed. _.each(options.dependencies, function (dep) { var depStr = dep.name; if (dep.constraint) { depStr += "@" + dep.constraint; } if (dep.weak) { depStr += " (weak dependency)"; } run.read(" " + depStr + "\n"); }); } if (options.publishedBy) { run.match("\n"); run.match( "Published by " + options.publishedBy + " on " + options.publishedOn + ".\n"); } if (options.addendum) { run.read("\n" + options.addendum + "\n"); } // Make sure that we exit without printing anything else. run.expectEnd(0); }); // For local packages without a version, we want to replace version information // with the string "local". We also want to make sure that querying for // 'name@local' gives that local version. selftest.define("show local package w/o version", function () { var s = new Sandbox(); var name = "my-local-package" + utils.randomToken(); // Create a package without version or summary; check that we can show its // information without crashing. s.createPackage(name, name, "package-for-show"); var packageDir = files.pathJoin(s.root, "home", name); s.cd(name, function () { s.cp("package-completely-empty.js", "package.js"); testShowPackage(s, name, { defaultVersion: "local", versions: [{ version: "local", directory: packageDir }] }); testShowPackageVersion(s, { packageName: name, version: "local", directory: packageDir }); // Test that running without any arguments also shows this package. var run = s.run("show"); run.match("Package: " + name + "@local\n"); run.match("Directory: " + packageDir + "\n"); run.expectExit(0); }); // Test that running without any arguments outside of a package does not // work. var run = s.run("show"); run.matchErr("specify a package or release name"); run.expectExit(1); }); // Return a formatted string of today’s date. var longformToday = function () { var today = new Date(); return utils.longformDate(today); }; // Make sure that a local-only package shows up correctly in show and search // results. selftest.define("show and search local package", function () { // Setup: create an app, containing a package. This local package should show // up in the results of `meteor show` and `meteor search`. var s = new Sandbox(); var name = "my-local-package" + utils.randomToken(); s.createApp("myapp", "empty"); s.cd("myapp"); s.mkdir("packages"); s.cd("packages", function () { s.createPackage(name, name, "package-for-show"); }); var packageDir = files.pathJoin(s.root, "home", "myapp", "packages", name); s.cd(packageDir, function () { s.cp("package-with-git.js", "package.js"); }); var summary = 'This is a test package'; // Run `meteor show`, but don't add the package to the app yet. We should know // that the package exists, even though it hasn't been added to the app. testShowPackage(s, name, { summary: summary, defaultVersion: "local", git: 'www.github.com/meteor/meteor', versions: [{ version: "1.0.0", directory: packageDir }] }); // Add the package to the app. var run = s.run("add", name); run.waitSecs(5); run.expectExit(0); testShowPackage(s, name, { summary: summary, git: 'www.github.com/meteor/meteor', defaultVersion: "local", versions: [{ version: "1.0.0", directory: packageDir }] }); // When we run `meteor search`, we should be able to see the results for this // package, even though it does not exist on the server. run = s.run("search", name); run.waitSecs(15); run.match(name); run.match("You can use"); run.expectExit(0); // We can see exports on local packages. s.cd("packages"); summary = "This is a test package"; name = "my-local-exports"; packageDir = files.pathJoin(s.root, "home", "myapp", "packages", name); s.createPackage(name, name, "package-for-show"); s.cd(name, function () { s.cp("package-with-exports.js", "package.js"); }); var exportStr = "A, B (server), C (web.browser, web.cordova), D (web.browser), E (web.cordova), G (server, web.cordova)"; var description = "Test package."; testShowPackage(s, name, { summary: summary, git: "www.github.com/meteor/meteor", exports: exportStr, description: description, defaultVersion: "local", versions: [{ version: "1.0.1", directory: packageDir }] }); testShowPackageVersion(s, { packageName: name, version: "1.0.1", directory: packageDir, git: "www.github.com/meteor/meteor", summary: summary, exports: exportStr, description: description }); // Test showing implies. Since we are not going to build the package, we don't // have to publish any of the things that we imply. var impRaw = { A: "", B: "server", C: "web.browser, web.cordova", D: "web.browser", E: "web.cordova", G: "server, web.cordova" }; var impliesData = _.sortBy(_.map(impRaw, function (label, placeholder) { var name = randomizedPackageName(username, placeholder.toLowerCase()); return { placeholder: placeholder, name: name, label: label}; }), 'name'); s.cd(name, function () { s.cp("package-with-implies.js", "package.js"); var packOpen = s.read("package.js"); _.each(impliesData, function (d) { var repReg = new RegExp("~" + d.placeholder + "~", "g"); packOpen = packOpen.replace(repReg, d.name); }); s.write("package.js", packOpen); }); summary = "This is a test package"; description = "Test package."; var impArr = _.map(impliesData, function (d) { return d.label ? d.name + " (" + d.label + ")" : d.name; }); var impStr = impArr[0] + ", " + impArr[1] + ", " + impArr[2] + ", " + impArr[3] + ", " + impArr[4] + ", " + impArr[5]; testShowPackage(s, name, { summary: summary, description: description, implies: impStr, directory: packageDir, defaultVersion: "local", git: "www.github.com/meteor/meteor", versions: [{ version: "1.2.1", directory: packageDir }] }); // Implies are also dependencies. var deps = _.map(impliesData, function (d) { return { name: d.name, constraint: "1.0.0" }; }); testShowPackageVersion(s, { packageName: name, version: "1.2.1", directory: packageDir, description: description, summary: summary, git: "www.github.com/meteor/meteor", implies: impStr, dependencies: deps }); }); // Make sure that if a package exists both locally, and on the server, 'meteor // show' and 'meteor search' correctly assign precedence to the local package // (but still show that the server package exists). selftest.define("show and search local overrides server", ['net', 'test-package-server', 'slow'], function () { // Now, for something more interesting. We are going to publish a version of a // package, and have a local version available. We want to make sure that all // the commands handle this correctly. var s = new Sandbox(); // Technically, this could make our test a little flaky if run at exactly // 11:59:59 PM, since the day will switch over before the test is finished. We // will never eliminate that possibility completely though, and running this // every time we want to check a publication date is sort of expensive. var today = longformToday(); var run; testUtils.login(s, username, password); var fullPackageName = randomizedPackageName(username); // Publish the first version of this package. createAndPublishPackage(s, fullPackageName); var packageDirName = "packages-for-show"; // Create a second version of this package. Inside that package directory, we // should be able to see the local package. var packageDir = files.pathJoin(s.root, "home", packageDirName); s.createPackage(packageDirName, fullPackageName, "package-for-show"); s.cd(packageDirName, function() { s.cp("package-with-git.js", "package.js"); var summary = "This is a test package"; var git = "www.github.com/meteor/meteor"; testShowPackage(s, fullPackageName, { maintainers: username, summary: summary, git: git, defaultVersion: "local", versions: [ { version: "1.0.0", date: today }, { version: "1.0.0", directory: packageDir } ] }); // When we ask for version 1.0.0, we get the local version. var addendum = "This package version is built locally from source. " + "The same version of this package also exists on the package server. " + "To view its metadata, run 'meteor show " + fullPackageName + "@1.0.0' from outside the project."; testShowPackageVersion(s, { packageName: fullPackageName, version: "1.0.0", summary: summary, git: git, directory: packageDir, addendum: addendum }); // The description in 'search' should come from the local package. run = s.run("search", fullPackageName); run.waitSecs(15); run.match(summary); run.expectExit(0); // Test that running without any arguments still gives us the local version. run = s.run("show"); run.match("Package: " + fullPackageName + "@1.0.0\n"); run.match("Directory: " + packageDir + "\n"); run.match("Git: " + git + "\n"); run.read("\n" + summary + "\n"); run.read("\n" + addendum + "\n"); run.expectEnd(0); }); // When we run outside of the package directory, we do not see the local // versions of this package, and get our information from the server. var summary = "Test package."; testShowPackage(s, fullPackageName, { summary: summary, defaultVersion: "1.0.0", maintainers: username, versions: [ { version: "1.0.0", date: today } ] }); run = s.run("search", fullPackageName); run.waitSecs(15); run.match(summary); run.expectExit(0); }); // Make sure that we display server packages correctly. Various types of // packages can exist on the server (and be missing various fields). We should // be able to handle that properly. selftest.define("show server package", ['net', 'test-package-server', 'slow'], function () { // Technically, this could make our test a little flaky if run at exactly // 11:59:59 PM, since the day will switch over before the test is finished. We // could try to recalculate this after each publication, but we would still // run that risk and the test will take even longer. var today = longformToday(); var s = new Sandbox(); testUtils.login(s, username, password); var fullPackageName = randomizedPackageName(username); var versions = []; // Publish a version the package without git or any dependencies. Make sure // that 'show' renders it correctly. var packageDirName = "package-for-show"; s.createPackage(packageDirName, fullPackageName, "package-for-show"); s.cd(packageDirName, function () { var run = s.run("publish", "--create"); run.waitSecs(30); run.expectExit(0); }); var summary = "This is a test package"; versions.push({ version: "0.9.9", date: today }); testShowPackage(s, fullPackageName, { summary: summary, maintainers: username, versions: versions, defaultVersion: _.last(versions).version, description: "Test package." }); testShowPackageVersion(s, { packageName: fullPackageName, version: "0.9.9", publishedBy: username, publishedOn: today, summary: summary, description: "Test package." }); // Publish a version of the package with git, but without any dependencies. s.cd(packageDirName, function () { s.cp("package-with-git.js", "package.js"); var run = s.run("publish"); run.waitSecs(30); run.expectExit(0); }); versions.push({ version: "1.0.0", date: today }); testShowPackage(s, fullPackageName, { defaultVersion: _.last(versions).version, summary: summary, maintainers: username, git: "www.github.com/meteor/meteor", versions: versions }); testShowPackageVersion(s, { packageName: fullPackageName, version: "1.0.0", publishedBy: username, publishedOn: today, summary: summary, git: "www.github.com/meteor/meteor" }); // Publish a version of the package with exports, and see that they show up. s.cd(packageDirName, function () { s.cp("package-with-exports.js", "package.js"); var run = s.run("publish"); run.waitSecs(30); run.expectExit(0); }); versions.push({ version: "1.0.1", date: today }); var exportStr = "A, B (server), C (web.browser, web.cordova)," + " D (web.browser), " + "E (web.cordova), G (server, web.cordova)"; testShowPackage(s, fullPackageName, { summary: summary, maintainers: username, exports: exportStr, defaultVersion: _.last(versions).version, description: "Test package.", git: "www.github.com/meteor/meteor", versions: versions }); testShowPackageVersion(s, { packageName: fullPackageName, version: "1.0.1", publishedBy: username, publishedOn: today, exports: exportStr, summary: summary, git: "www.github.com/meteor/meteor", description: "Test package." }); // Publish a version of the package with git that depends on other // packages. To do this, we need to publish two other packages (since we don't // want to rely on specific packages existing on the test server). var baseDependency = randomizedPackageName(username, "base"); createAndPublishPackage(s, baseDependency); var weakDependency = randomizedPackageName(username, "weak"); createAndPublishPackage(s, weakDependency); s.cd(packageDirName, function () { // Replace the dependencies placeholders in the package.js file with the // packages that we have just published. s.cp("package-with-deps.js", "package.js"); var packOpen = s.read("package.js"); packOpen = packOpen.replace(/~baseDependency~/g, baseDependency); packOpen = packOpen.replace(/~weakDependency~/g, weakDependency); s.write("package.js", packOpen); var run = s.run("publish"); run.waitSecs(30); run.expectExit(0); }); var newVersions = _.union(versions, [{ version: "1.2.0", date: today }]); var newSummary = "This is a test package with dependencies"; testShowPackage(s, fullPackageName, { summary: newSummary, maintainers: username, defaultVersion: "1.2.0", git: "www.github.com/meteor/meteor", versions: newVersions }); testShowPackageVersion(s, { packageName: fullPackageName, version: "1.2.0", publishedBy: username, publishedOn: today, summary: newSummary, git: "www.github.com/meteor/meteor", dependencies: [ { name: baseDependency, constraint: "1.0.0" }, { name: weakDependency, constraint: "=1.0.0", weak: true } ] }); // Publish a version of the package with git that implies other packages. // Test showing implies. Since we are not going to build the package, we don't // have to publish any of the things that we imply. var impRaw = { A: "", B: "server", C: "web.browser, web.cordova", D: "web.browser", E: "web.cordova", G: "server, web.cordova" }; var impliesData = _.sortBy(_.map(impRaw, function (label, placeholder) { var name = randomizedPackageName(username, placeholder.toLowerCase()); createAndPublishPackage(s, name); return { placeholder: placeholder, name: name, label: label}; }), 'name'); s.cd(packageDirName, function () { // Replace the dependencies placeholders in the package.js file with the // packages that we have just published. s.cp("package-with-implies.js", "package.js"); var packOpen = s.read("package.js"); _.each(impliesData, function (d) { var repReg = new RegExp("~" + d.placeholder + "~", "g"); packOpen = packOpen.replace(repReg, d.name); }); s.write("package.js", packOpen); var run = s.run("publish"); run.waitSecs(30); run.expectExit(0); }); summary = "This is a test package"; var impArr = _.map(impliesData, function (d) { return d.label ? d.name + " (" + d.label + ")" : d.name; }); var impStr = impArr[0] + ", " + impArr[1] + ", " + impArr[2] + ", " + impArr[3] + ", " + impArr[4] + ", " + impArr[5]; // Implies are also dependencies. var deps = _.map(impliesData, function (d) { return { name: d.name, constraint: "1.0.0" }; }); versions.push({ version: "1.2.1", date: today }); newVersions.push({ version: "1.2.1", date: today }); summary = "This is a test package"; var description = "Test package."; testShowPackage(s, fullPackageName, { summary: summary, maintainers: username, defaultVersion: "1.2.1", implies: impStr, description: description, git: "www.github.com/meteor/meteor", versions: versions }); testShowPackageVersion(s, { packageName: fullPackageName, version: "1.2.1", publishedBy: username, publishedOn: today, summary: summary, description: description, git: "www.github.com/meteor/meteor", implies: impStr, dependencies: deps }); // Set a homepage. var run = s.run("admin", "change-homepage", fullPackageName, "www.meteor.com"); run.waitSecs(10); run.match("done"); run.expectExit(0); testShowPackage(s, fullPackageName, { summary: summary, maintainers: username, defaultVersion: "1.2.1", git: "www.github.com/meteor/meteor", homepage: "www.meteor.com", versions: versions, implies: impStr, description: description }); // Add this package to an app, forcing us to download the isopack. Check that // the version that we added is marked as installed. run = s.run("create", "myApp"); run.waitSecs(30); run.expectExit(0); s.cd("myApp", function () { var run = s.run("add", fullPackageName + "@1.2.0"); run.waitSecs(30); run.expectExit(0); }); versions = _.initial(versions); versions.push({ version: "1.2.1", date: today, label: "installed" }); testShowPackage(s, fullPackageName, { summary: summary, maintainers: username, defaultVersion: _.last(versions).version, git: "www.github.com/meteor/meteor", homepage: "www.meteor.com", versions: versions, implies: impStr, description: description }); // Publish a pre-release version of the package. s.cd(packageDirName, function () { s.cp("package-rc-version.js", "package.js"); var run = s.run("publish"); run.waitSecs(30); run.expectExit(0); }); // Mark a version of the package as unmigrated. run = s.run("admin", "set-unmigrated", fullPackageName + "@1.0.0"); run.waitSecs(10); run.expectExit(0); // Neither of these versions should show up. var moreAvailable = "Pre-release and unmigrated versions of " + fullPackageName + " have been hidden. To see all " + "6" + " versions, run 'meteor show --show-all " + fullPackageName + "'."; testShowPackage(s, fullPackageName, { summary: newSummary, maintainers: username, defaultVersion: _.last(versions).version, git: "www.github.com/meteor/meteor", homepage: "www.meteor.com", versions: [ { version: "0.9.9", date: today }, { version: "1.0.1", date: today }, { version: "1.2.0", date: today }, { version: "1.2.1", date: today, label: "installed" } ], implies: impStr, description: description, addendum: moreAvailable }); newVersions = _.union(versions, [{ version: "1.3.0-rc.1", date: today }]); // All the versions will show up when we run with the 'show-all' flag. testShowPackage(s, fullPackageName, { summary: newSummary, maintainers: username, git: "www.github.com/meteor/meteor", homepage: "www.meteor.com", versions: newVersions, all: true, implies: impStr, description: description, defaultVersion: "1.2.1" }); // If we just query for a specific version, it shows up. testShowPackageVersion(s, { packageName: fullPackageName, version: "1.3.0-rc.1", publishedBy: username, publishedOn: today, // This version is using a different git & description than the previous // versions. If this git and/or description ever shows up in the // non-version-specific show, that's wrong! summary: 'This is a pre-release version of this package!', git: "www.github.com/fake-user/meteor" }); }); // By default, we don't show unofficial package versions. Make sure that a // package with only hidden versions is shown in a reasonable manner. selftest.define("show rc-only package", ['net', 'test-package-server', 'slow'], function () { var s = new Sandbox(); testUtils.login(s, username, password); var fullPackageName = randomizedPackageName(username); var packageDirName = "package-for-show"; // Create a package that has only an rc version. s.createPackage(packageDirName, fullPackageName, "package-for-show"); s.cd(packageDirName, function () { s.cp("package-rc-version.js", "package.js"); var run = s.run("publish", "--create"); run.waitSecs(30); run.expectExit(0); }); // Run 'meteor show'. There should not be any versions showing up, or any sort // of a version header. But we should get an addendum saying that more // versions are available. var moreAvailable = "One pre-release version of " + fullPackageName + " has been hidden. To see " + "the hidden version, run 'meteor show --show-all " + fullPackageName + "'."; testShowPackage(s, fullPackageName, { maintainers: username, addendum: moreAvailable }); }); // Publishes a release. Takes in a sandbox, a release configuration, and options: // - new: create a new track with this release version var publishRelease = selftest.markStack(function (s, releaseConfig, options) { options = options || {}; var releaseFile = "relconf.json"; s.write(releaseFile, JSON.stringify(releaseConfig)); var run; if (options.new) { run = s.run("publish-release", releaseFile, "--create-track"); } else { run = s.run("publish-release", releaseFile); } run.match("Done"); run.expectExit(0); }); // Tests that 'meteor show <releaseName>' works properly. // Takes in the following options: // - name: release name // - maintainers: string of maintainers // - description: release description // - versions: array of versions that we expect to display, in order. Each // version is an object with the following keys: // - version (version number) // - date (date published) // - addendum: a message to display at the bottom. var testShowRelease = selftest.markStack(function (s, options) { var run = s.run("show", options.name); run.waitSecs(10); run.match("Release: " + options.name + "\n"); run.read("Maintainers: " + options.maintainers + "\n"); run.read("\n"); if (options.description) { run.read(options.description + "\n\n"); } if (options.versions) { run.read("Recommended versions:\n"); _.each(options.versions, function (v) { run.match(v.version); run.match(v.date + "\n"); }); run.read("\n"); } if (options.addendum) { var addendum = options.addendum; addendum = addendum.replace(/\s+/g, "\\s+") + "\\s+"; run.read(new RegExp(addendum)); } run.expectEnd(0); }); // Tests that 'meteor show --show-all <releaseName>' works properly. // Takes in the following options: // - name: release name // - maintainers: string of maintainers // - description: release description // - keyedVersions: array of versions with order keys that we expect to // display, in order. Each version is an object with the following keys: // - version (version number) // - date (date published) // - label (such as "(recommended")) // - experimentalVersions: an array of versions without order keys that we // expect to display, in order. Have the same keys as keyedVersions, except // without a label. // - addendum: a message to display at the bottom. var testShowLongRelease = selftest.markStack(function (s, options) { var run = s.run("show", "--show-all", options.name); run.waitSecs(10); run.match("Release: " + options.name + "\n"); run.read("Maintainers: " + options.maintainers + "\n"); if (options.description) { run.read("\n" + options.description + "\n"); } run.read("\n"); if (options.keyedVersions) { run.read("Versions:\n"); _.each(options.keyedVersions, function (v) { run.match(v.version); run.match(v.date); if (v.label) { run.match(v.label); } run.match("\n"); }); run.match("\n"); } if (options.experimentalVersions) { run.read("Experimental versions:\n"); _.each(options.experimentalVersions, function (v) { run.match(v.version); run.match(v.date); if (v.label) { run.match(v.label); } run.match("\n"); }); run.match("\n"); } run.expectEnd(0); }); // Tests that 'meteor show <track>@<version>' works and prints out reasonable // output. Takes in the following options: // - name: track name // - version: release version to test // - publishedBy: username of publisher // - publishedOn: date string of publication time // - tool: tool package string // - recommended: "yes" for recommended releases, "no" otherwise // - packages: an array of objects, with keys "name" (package name) and // "version (package version) representing the packages that belong to this // release. var testShowReleaseVersion = selftest.markStack(function (s, options) { var run = s.run( "show", options.name + "@" + options.version); run.waitSecs(10); run.match("Release: " + options.name + "@" + options.version + "\n"); run.read("Recommended: " + options.recommended + "\n"); run.read("Tool package: " + options.tool + "\n"); run.read("\n" + options.description + "\n"); run.read("\n"); if (options.packages) { run.read("Packages:\n"); _.each(options.packages, function (pkg) { run.read(" " + pkg.name + ": " + pkg.version + "\n"); }); run.read("\n"); }; run.read( "Published by " + options.publishedBy + " on " + options.publishedOn + "\n"); run.expectEnd(0); }); // Make sure that we show releases and release versions properly. selftest.define("show release", ['net', 'test-package-server', 'slow'], function () { var s = new Sandbox(); testUtils.login(s, username, password); // Technically, this could make our test a little flaky if run at exactly // 11:59:59 PM, since the day will switch over before the test is finished. We // will never eliminate that possibility completely though, and running this // every time we want to check a publication date is sort of expensive. var today = longformToday(); // In order to publish a release, we need a package to use as the // tool. Publish a package, and use it as the tool. (This release will not // actually run, but we are not testing that.) var fullPackageName = randomizedPackageName(username); createAndPublishPackage(s, fullPackageName); // Some base variables that we will use to create a release track. var releaseTrack = randomizedReleaseName(username); var tool = fullPackageName + "@1.0.0"; var packages = {}; packages[fullPackageName] = "1.0.0"; var baseConfig = { track: releaseTrack, tool: tool }; // Publish a new release track, and on it, a new recommended release version // with this tool and without any packages. var recommendedDesc = "first test version"; var releaseConfig = _.extend(baseConfig, { version: "0.0.1", recommended: true, description: recommendedDesc, packages: {} }); publishRelease(s, releaseConfig, { new: true }); testShowRelease(s, { name: releaseTrack, description: releaseConfig.description, maintainers: username, versions: [{ version: "0.0.1", date: today }] }); testShowReleaseVersion(s, { name: releaseTrack, version: "0.0.1", description: releaseConfig.description, publishedBy: username, publishedOn: today, tool: tool, recommended: "yes" }); // Publish a non-recommended release version on the same release track. Have // this release version contain some packages. (This version was published // second, but has a smaller orderKey, so it should show up above the previous // version in the results of ‘meteor show’). releaseConfig = _.extend(baseConfig, { version: "0.0.0.1", recommended: false, packages: packages, description: "second test version" }); publishRelease(s, releaseConfig); var moreVersions = "One non-recommended version of " + releaseConfig.track + " has been hidden. " + "To see all 2 " + "versions, run 'meteor show --show-all " + releaseConfig.track + "'."; testShowRelease(s, { name: releaseTrack, description: recommendedDesc, maintainers: username, versions: [{ version: "0.0.1", date: today }], addendum: moreVersions }); testShowLongRelease(s, { name: releaseTrack, description: recommendedDesc, maintainers: username, keyedVersions: [ { version: "0.0.0.1", date: today}, { version: "0.0.1", date: today, label: "(recommended)" } ] }); testShowReleaseVersion(s, { name: releaseTrack, version: "0.0.0.1", description: releaseConfig.description, publishedBy: username, publishedOn: today, tool: tool, recommended: "no", packages: [{ name: fullPackageName, version: "1.0.0" }] }); // Publish two experimental release versions (no order key at all) and check // that they are correctly shown by 'meteor show'. releaseConfig = _.extend(baseConfig, { version: "cheesecake", recommended: false, packages: packages, description: "just cake" }); publishRelease(s, releaseConfig); testShowReleaseVersion(s, { name: releaseTrack, version: "cheesecake", description: releaseConfig.description, publishedBy: username, publishedOn: today, tool: tool, recommended: "no", packages: [{ name: fullPackageName, version: "1.0.0" }] }); releaseConfig = _.extend(baseConfig, { version: "apricot", recommended: false, packages: packages, description: "nom nom nom" }); publishRelease(s, releaseConfig); testShowReleaseVersion(s, { name: releaseTrack, version: "apricot", description: releaseConfig.description, publishedBy: username, publishedOn: today, tool: tool, recommended: "no", packages: [{ name: fullPackageName, version: "1.0.0" }] }); moreVersions = "Non-recommended versions of " + releaseConfig.track + " have been hidden. To see all 4 " + "versions, run 'meteor show --show-all " + releaseConfig.track + "'."; testShowRelease(s, { name: releaseTrack, description: recommendedDesc, maintainers: username, versions: [{ version: "0.0.1", date: today }], addendum: moreVersions }); testShowLongRelease(s, { name: releaseTrack, description: recommendedDesc, maintainers: username, keyedVersions: [ { version: "0.0.0.1", date: today}, { version: "0.0.1", date: today, label: "(recommended)" } ], experimentalVersions: [ { version: "cheesecake", date: today}, { version: "apricot", date: today } ] }); }); selftest.define("show release w/o recommended versions", ['net', 'test-package-server', 'slow'], function () { var s = new Sandbox(); testUtils.login(s, username, password); // Technically, this could make our test a little flaky if run at exactly // 11:59:59 PM, since the day will switch over before the test is finished. We // will never eliminate that possibility completely though, and running this // every time we want to check a publication date is sort of expensive. var today = longformToday(); // In order to publish a release, we need a package to use as the // tool. Publish a package, and use it as the tool. (This release will not // actually run, but we are not testing that.) var fullPackageName = randomizedPackageName(username); createAndPublishPackage(s, fullPackageName); // Some base variables that we will use to create a release track. var releaseTrack = randomizedReleaseName(username); var tool = fullPackageName + "@1.0.0"; var packages = {}; packages[fullPackageName] = "1.0.0"; var baseConfig = { track: releaseTrack, packages: packages, tool: tool }; // Publish two experimental release versions (no order key at all) and check // that they are correctly shown by 'meteor show'. var releaseConfig = _.extend(baseConfig, { version: "cheesecake", recommended: false, description: "just cake" }); publishRelease(s, releaseConfig, { new: true }); releaseConfig = _.extend(releaseConfig, { version: "apricot", recommended: false, description: "nom nom nom" }); publishRelease(s, releaseConfig); var moreVersions = "Non-recommended versions of " + releaseConfig.track + " have been hidden. To see all 2 " + "versions, run 'meteor show --show-all " + releaseConfig.track + "'."; testShowRelease(s, { name: releaseTrack, maintainers: username, addendum: moreVersions }); testShowLongRelease(s, { name: releaseTrack, maintainers: username, experimentalVersions: [ { version: "cheesecake", date: today}, { version: "apricot", date: today } ] }); testShowReleaseVersion(s, { name: releaseTrack, version: "apricot", description: releaseConfig.description, publishedBy: username, publishedOn: today, tool: tool, recommended: "no", packages: [{ name: fullPackageName, version: "1.0.0" }] }); }); selftest.define("show package w/many versions", ['net', 'test-package-server', 'slow'], function () { var s = new Sandbox(); testUtils.login(s, username, password); // Technically, this could make our test a little flaky if run at exactly // 11:59:59 PM, since the day will switch over before the test is finished. We // will never eliminate that possibility completely though, and running this // every time we want to check a publication date is sort of expensive. var today = longformToday(); // Set package version and publish the package. var setVersionAndPublish = function (version) { var packOpen = s.read("package-version.js"); packOpen = packOpen.replace(/~version~/g, version); s.write("package.js", packOpen); var run = s.run("publish"); run.waitSecs(30); run.expectExit(0); }; var fullPackageName = randomizedPackageName(username); var packageDirName = "package-of-two-version"; s.createPackage(packageDirName, fullPackageName, "package-of-two-versions"); var packageDir = files.pathJoin(s.root, "home", packageDirName); s.cd(packageDirName, function () { var run = s.run("publish", "--create"); run.waitSecs(30); run.expectExit(0); // Publish a couple more versions. setVersionAndPublish("1.0.1"); setVersionAndPublish("1.0.2-rc.1"); setVersionAndPublish("1.0.5"); setVersionAndPublish("1.0.6"); setVersionAndPublish("1.0.7"); setVersionAndPublish("2.0.0"); setVersionAndPublish("2.0.1"); // Make sure that the right versions show up when the local package is visible. var moreAvailable = "Older versions of " + fullPackageName + " have been hidden. To see " + "all 9 versions, run 'meteor show --show-all " + fullPackageName + "'."; testShowPackage(s, fullPackageName, { maintainers: username, summary: "Test package.", addendum: moreAvailable, defaultVersion: "local", versions: [ { version: "1.0.5", date: today }, { version: "1.0.6", date: today }, { version: "1.0.7", date: today }, { version: "2.0.0", date: today }, { version: "2.0.1", date: today }, { version: "2.0.1", directory: packageDir } ] }); // Make sure that we list the pre-release version in the list of versions // that have been hidden. setVersionAndPublish("2.0.0-rc.1"); setVersionAndPublish("2.0.2"); moreAvailable = "Older and pre-release versions of " + fullPackageName + " have been hidden. To see all 11 " + "versions, run 'meteor show --show-all " + fullPackageName + "'."; testShowPackage(s, fullPackageName, { maintainers: username, summary: "Test package.", defaultVersion: "local", addendum: moreAvailable, versions: [ { version: "1.0.6", date: today }, { version: "1.0.7", date: today }, { version: "2.0.0", date: today }, { version: "2.0.1", date: today }, { version: "2.0.2", date: today }, { version: "2.0.2", directory: packageDir } ] }); }); // Make sure that the right versions show up when the local package is NOT visible. var moreAvailable = "Older and pre-release versions of " + fullPackageName + " have been hidden. " + "To see all 10 versions, run 'meteor show --show-all " + fullPackageName + "'."; testShowPackage(s, fullPackageName, { maintainers: username, summary: "Test package.", defaultVersion: "2.0.2", addendum: moreAvailable, versions: [ { version: "1.0.6", date: today }, { version: "1.0.7", date: today }, { version: "2.0.0", date: today }, { version: "2.0.1", date: today }, { version: "2.0.2", date: today } ] }); testShowPackage(s, fullPackageName, { all: true, maintainers: username, summary: "Test package.", defaultVersion: "2.0.2", versions: [ { version: "1.0.0", date: today }, { version: "1.0.1", date: today }, { version: "1.0.5", date: today }, { version: "1.0.6", date: today }, { version: "1.0.7", date: today }, { version: "2.0.0", date: today }, { version: "2.0.1", date: today }, { version: "2.0.2", date: today } ] }); }); // This tests that we get the right excerpt out of the Readme.md in different // combinations. It doesn't test publication, because publishing is slow -- // that's covered in a different test. selftest.define("show readme excerpt", function () { var s = new Sandbox(); var name = "my-local-package" + utils.randomToken(); // Create a package without version or summary; check that we can show its // information without crashing. s.createPackage(name, name, "package-for-show"); var packageDir = files.pathJoin(s.root, "home", name); // We are just going to change the description in the Readme. Some things // about this package are not going to change, and our test will be more // legible to factor them out here. var basePackageInfo = { summary: "This is a test package", defaultVersion: "local", versions: [{ version: "0.9.9", directory: packageDir }] }; var baseVersionInfo = { summary: "This is a test package", packageName: name, version: "0.9.9", directory: packageDir }; s.cd(name); // By default, we will use the README.md file for documentation. // Start with a blank file. Nothing should show up! s.write("README.md", ""); testShowPackage(s, name, basePackageInfo); testShowPackageVersion(s, baseVersionInfo); // An example of a standard readme. var readme = "Heading" + "\n" + "========" + "\n" + "foobar1" + "\n" + "\n" + "## Subheading" + "\n" + "You should not see this line!"; s.write("README.md", readme); testShowPackage( s, name, _.extend({ description: "foobar1" }, basePackageInfo)); testShowPackageVersion( s, _.extend({ description: "foobar1" }, baseVersionInfo)); // Another example -- we have hidden the excerpt under a different subheading. readme = "Heading" + "\n" + "========" + "\n" + "## Subheading" + "\n" + "foobar2" + "\n" + "## Another subheading" + "\n" + "You should not see this line!"; s.write("README.md", readme); testShowPackage( s, name, _.extend({ description: "foobar2" }, basePackageInfo)); testShowPackageVersion( s, _.extend({ description: "foobar2" }, baseVersionInfo)); // Generally, people skip a line between the header and the text, and // sometimes, even between headers. (It is part of markdown, in fact.) Let's // make sure that we handle that correctly. readme = "Heading" + "\n" + "========" + "\n" + "\n" + "## Subheading" + "\n" + "\n" + "foobaz" + "\n" + "\n" + "## Another subheading" + "\n" + "\n" + "You should not see this line!"; s.write("README.md", readme); testShowPackage( s, name, _.extend({ description: "foobaz" }, basePackageInfo)); testShowPackageVersion( s, _.extend({ description: "foobaz" }, baseVersionInfo)); // Some formatting in the text. var excerpt = "Here is a code sample:" + "\n\n" + "```foobar and foobar```"; readme = "Heading" + "\n" + "========" + "\n" + "\n" + excerpt + "\n\n" + "# Subheading" + "\n" + "\n" + "## Another subheading" + "\n" + "\n" + "You should not see this line!"; s.write("README.md", readme); testShowPackage( s, name, _.extend({ description: excerpt }, basePackageInfo)); testShowPackageVersion( s, _.extend({ description: excerpt }, baseVersionInfo)); // Now, let's try different file specifications for the documentation. var git = "https:ilovegit.git"; var summary = "Test summary"; var staging = s.read("package-customizable.js"); staging = staging.replace(/~version~/g, "1.0.0"); staging = staging.replace(/~git~/g, git); staging = staging.replace(/~summary~/g, summary); // If we specify null, we have no docs. s.write("package.js", staging.replace(/~documentation~/g, "null")); baseVersionInfo = { summary: summary, git: git, packageName: name, version: "1.0.0", directory: packageDir }; basePackageInfo = { git: git, summary: summary, defaultVersion: "local", versions: [{ version: "1.0.0", directory: packageDir }] }; testShowPackageVersion(s, baseVersionInfo); testShowPackage(s, name, basePackageInfo); // If we specify a different file, read that file. s.write("package.js", staging.replace(/~documentation~/g, "'Meteor-Readme.md'")); readme = "A special Readme, just for Meteor."; s.write("Meteor-Readme.md", "Title\n==\n" + readme); testShowPackageVersion(s, _.extend({ description: readme }, baseVersionInfo)); testShowPackage(s, name, _.extend({ description: readme }, basePackageInfo)); // If we specify a non-existent file, tell us. s.write("package.js", staging.replace(/~documentation~/g, "'NOTHING'")); var run = s.run("show", name); run.matchErr("Documentation not found"); run.expectExit(1); run = s.run("show", name + "@1.0.0"); run.matchErr("Documentation not found"); run.expectExit(1); }); // Show publication with different types of readme files. selftest.define("show server readme", ['net', 'test-package-server', 'slow'], function () { var s = new Sandbox(); testUtils.login(s, username, password); // Technically, this could make our test a little flaky if run at exactly // 11:59:59 PM, since the day will switch over before the test is finished. We // will never eliminate that possibility completely though, and running this // every time we want to check a publication date is sort of expensive. var today = longformToday(); var fullPackageName = username + ":" + utils.randomToken(); var packageDirName = "package-for-show"; s.createPackage(packageDirName, fullPackageName, "package-for-show"); var summary = "This is a test package"; // Publish fullPackageName. // - isNew: (optional) if true, no other versions of fullPackageName exist, so // run 'publish --create instad of 'publish'. var publish = function(isNew) { var run; if (isNew) { run = s.run("publish", "--create"); } else { run = s.run("publish"); } run.waitSecs(30); run.expectExit(0); }; // Default docs. s.cd(packageDirName, function () { publish(true); }); testShowPackageVersion(s, { summary: summary, publishedBy: username, publishedOn: today, packageName: fullPackageName, version: "0.9.9", description: "Test package." }); testShowPackage(s, fullPackageName, { summary: summary, defaultVersion: "0.9.9", maintainers: username, versions: [{ version: "0.9.9", date: today }], description: "Test package." }); // Custom Readme! Publish works. var git = "https:ilovegit.git"; var staging; s.cd(packageDirName, function () { staging = s.read("package-customizable.js"); staging = staging.replace(/~git~/g, git); staging = staging.replace(/~summary~/g, summary); var current = staging.replace(/~version~/g, "1.0.0"); s.write("package.js", current.replace(/~documentation~/g, "'MINE.md'")); s.write("MINE.md", "Foobar\n====\nNew test!\n\n# Something\n"); publish(); }); testShowPackageVersion(s, { summary: summary, git: git, publishedBy: username, publishedOn: today, packageName: fullPackageName, version: "1.0.0", description: "New test!" }); testShowPackage(s, fullPackageName, { summary: summary, git: git, defaultVersion: "1.0.0", maintainers: username, description: "New test!", versions: [ { version: "0.9.9", date: today }, { version: "1.0.0", date: today } ] }); // Null Readme! Publish works. s.cd(packageDirName, function () { var current = staging.replace(/~version~/g, "1.0.0_1"); s.write("package.js", current.replace(/~documentation~/g, "null")); publish(); }); testShowPackageVersion(s, { summary: summary, git: git, packageName: fullPackageName, version: "1.0.0_1", publishedBy: username, publishedOn: today }); testShowPackage(s, fullPackageName, { summary: summary, git: git, maintainers: username, defaultVersion: "1.0.0_1", versions: [ { version: "0.9.9", date: today }, { version: "1.0.0", date: today }, { version: "1.0.0_1", date: today } ] }); // These cause the publish to fail. s.cd(packageDirName, function () { // README is blank. var current = staging.replace(/~version~/g, "1.0.0_2"); s.write("package.js", current.replace(/~documentation~/g, "'blank'")); s.write("blank", ""); var run = s.run("publish"); run.matchErr("Your documentation file is blank"); run.expectExit(1); // README does not exist. s.write("package.js", current.replace(/~documentation~/g, "'none'")); run = s.run("publish"); run.matchErr("Documentation not found"); run.expectExit(1); // README is too long. s.write("package.js", current.replace(/~documentation~/g, "'long'")); var longReadme = Array(75).join(" please do not read me! "); s.write("long", "Heading\n===\n" + longReadme); run = s.run("publish"); run.matchErr("Longform package description is too long"); run.expectExit(1); }); // If you didn't format things properly, we will still publish and use that as // an excerpt. s.cd(packageDirName, function () { var current = staging.replace(/~version~/g, "1.0.0_2"); s.write("package.js", current.replace(/~documentation~/g, "'unformat'")); s.write("unformat", "I did not format this readme"); publish(); }); testShowPackageVersion(s, { summary: summary, git: git, packageName: fullPackageName, version: "1.0.0_2", description: "I did not format this readme", publishedBy: username, publishedOn: today }); testShowPackage(s, fullPackageName, { summary: summary, git: git, maintainers: username, defaultVersion: "1.0.0_2", description: "I did not format this readme", versions: [ { version: "0.9.9", date: today }, { version: "1.0.0", date: today }, { version: "1.0.0_1", date: today }, { version: "1.0.0_2", date: today } ] }); }); // Show publication with different types of readme files. selftest.define("update package metadata", ['net', 'test-package-server', 'slow'], function () { var s = new Sandbox(); testUtils.login(s, username, password); // Technically, this could make our test a little flaky if run at exactly // 11:59:59 PM, since the day will switch over before the test is finished. We // will never eliminate that possibility completely though, and running this // every time we want to check a publication date is sort of expensive. var today = longformToday(); var fullPackageName = username + ":" + utils.randomToken(); var packageDirName = "package-for-show"; s.createPackage(packageDirName, fullPackageName, "package-for-show"); var summary = "This is a test package"; var desc = "Test package."; var git = "www.iheartgit.git"; var basePackageVersion = { publishedBy: username, publishedOn: today, packageName: fullPackageName, version: "0.9.9" }; var basePackage = { maintainers: username, defaultVersion: "0.9.9", versions: [{ version: "0.9.9", date: today }] }; var update = function () { var run = s.run("publish", "--update"); run.waitSecs(30); run.match("Success."); run.expectExit(0); }; // Publish the basic show package, using the default settings. s.cd(packageDirName, function () { var run = s.run("publish", "--create"); run.waitSecs(30); run.expectExit(0); }); testShowPackageVersion(s, _.extend({ summary: summary, description: desc }, basePackageVersion)); testShowPackage(s, fullPackageName, _.extend({ summary: summary, description: desc }, basePackage)); // add git s.cd(packageDirName, function () { var staging = s.read("package-customizable.js"); staging = staging.replace(/~git~/g, git); staging = staging.replace(/~summary~/g, summary); staging = staging.replace(/~version~/g, "0.9.9"); staging = staging.replace(/~documentation~/g, "'README.md'"); s.write("package.js", staging); update(); }); testShowPackageVersion(s, _.extend({ summary: summary, git: git, description: desc }, basePackageVersion)); testShowPackage(s, fullPackageName, _.extend({ summary: summary, git: git, description: desc }, basePackage)); // change git & summary git = "https://www.idoNOTheartgit.com"; summary = "awesome test"; s.cd(packageDirName, function () { var staging = s.read("package-customizable.js"); staging = staging.replace(/~git~/g, git); staging = staging.replace(/~summary~/g, summary); staging = staging.replace(/~version~/g, "0.9.9"); staging = staging.replace(/~documentation~/g, "'README.md'"); s.write("package.js", staging); update(); }); testShowPackageVersion(s, _.extend({ summary: summary, git: git, description: desc }, basePackageVersion)); testShowPackage(s, fullPackageName, _.extend({ summary: summary, git: git, description: desc }, basePackage)); // change readme contents & summary desc = "This test package is super super awesome"; summary = "more awesome test"; s.cd(packageDirName, function () { var staging = s.read("package-customizable.js"); staging = staging.replace(/~git~/g, git); staging = staging.replace(/~summary~/g, summary); staging = staging.replace(/~version~/g, "0.9.9"); staging = staging.replace(/~documentation~/g, "'README.md'"); s.write("package.js", staging); s.write("README.md", "Test\n===\n"+ desc); update(); }); testShowPackageVersion(s, _.extend({ summary: summary, git: git, description: desc }, basePackageVersion)); testShowPackage(s, fullPackageName, _.extend({ summary: summary, git: git, description: desc }, basePackage)); // change readme contents desc = "Actually this test package is OK"; s.cd(packageDirName, function () { s.write("README.md", "OKTest\n===\n"+ desc); update(); }); testShowPackageVersion(s, _.extend({ summary: summary, git: git, description: desc }, basePackageVersion)); testShowPackage(s, fullPackageName, _.extend({ summary: summary, git: git, description: desc }, basePackage)); // change readme file desc = "description from new file"; s.cd(packageDirName, function () { var staging = s.read("package-customizable.js"); staging = staging.replace(/~git~/g, git); staging = staging.replace(/~summary~/g, summary); staging = staging.replace(/~version~/g, "0.9.9"); staging = staging.replace(/~documentation~/g, "'NEW-README.md'"); s.write("package.js", staging); s.write("NEW-README.md", "Test\n===\n"+ desc); update(); }); testShowPackageVersion(s, _.extend({ summary: summary, git: git, description: desc }, basePackageVersion)); testShowPackage(s, fullPackageName, _.extend({ summary: summary, git: git, description: desc }, basePackage)); // remove readme s.cd(packageDirName, function () { var staging = s.read("package-customizable.js"); staging = staging.replace(/~git~/g, git); staging = staging.replace(/~summary~/g, summary); staging = staging.replace(/~version~/g, "0.9.9"); staging = staging.replace(/~documentation~/g, "null"); s.write("package.js", staging); update(); }); testShowPackageVersion(s, _.extend({ summary: summary, git: git }, basePackageVersion)); testShowPackage(s, fullPackageName, _.extend({ summary: summary, git: git }, basePackage)); // try to set an invalid summary s.cd(packageDirName, function () { // Long summary var staging = s.read("package-customizable.js"); staging = staging.replace(/~git~/g, git); var longSummary = Array(30).join(summary); staging = staging.replace(/~summary~/g, longSummary); staging = staging.replace(/~version~/g, "0.9.9"); staging = staging.replace(/~documentation~/g, "null"); s.write("package.js", staging); var run = s.run("publish", "--update"); run.matchErr("Summary must be under"); run.expectExit(1); // Blank summary. staging = s.read("package-customizable.js"); staging = staging.replace(/~git~/g, git); staging = staging.replace(/~summary~/g, ""); staging = staging.replace(/~version~/g, "0.9.9"); staging = staging.replace(/~documentation~/g, "null"); s.write("package.js", staging); run = s.run("publish", "--update"); run.matchErr("Please provide"); run.expectExit(1); }); testShowPackageVersion(s, _.extend({ summary: summary, git: git }, basePackageVersion)); testShowPackage(s, fullPackageName, _.extend({ summary: summary, git: git }, basePackage)); // try to set an invalid readme s.cd(packageDirName, function () { var staging = s.read("package-customizable.js"); staging = staging.replace(/~git~/g, git); var longSummary = Array(30).join(summary); staging = staging.replace(/~summary~/g, summary); staging = staging.replace(/~version~/g, "0.9.9"); staging = staging.replace(/~documentation~/g, "'longReadme.md'"); s.write("package.js", staging); var longDesc = Array(75).join("this is a very long text "); s.write("longReadme.md", "Heading\n===\n" + longDesc); var run = s.run("publish", "--update"); run.matchErr("Longform package description is too long."); run.expectExit(1); }); // try to update non-existent version s.cd(packageDirName, function () { var staging = s.read("package-customizable.js"); staging = staging.replace(/~git~/g, git); staging = staging.replace(/~summary~/g, summary); staging = staging.replace(/~version~/g, "2.0.0"); staging = staging.replace(/~documentation~/g, "null"); s.write("package.js", staging); var run = s.run("publish", "--update"); run.matchErr("without publishing it first"); run.expectExit(1); }); // try to update non-existent package var newPackageName = username + ":" + utils.randomToken(); var newPackageDirName = "packages-for-show"; s.createPackage(newPackageDirName, newPackageName, "package-for-show"); s.cd(newPackageDirName, function () { var run = s.run("publish", "--update"); run.matchErr("without publishing it first"); run.expectExit(1); run = s.run("publish", "--create"); run.waitSecs(30); run.expectExit(0); }); // try to update dependencies, they don't get upated! (But it still goes // through, for now). s.cd(packageDirName, function () { var staging = s.read("package-customizable.js"); staging = staging.replace(/~git~/g, git); staging = staging.replace(/~summary~/g, summary); staging = staging.replace(/~version~/g, "0.9.9"); staging = staging.replace(/~documentation~/g, "null"); staging = staging + "\nPackage.onUse(function (api) {\n" + "api.use('" + newPackageName + "@1.0.0');\n})\n"; s.write("package.js", staging); update(); }); testShowPackageVersion(s, _.extend({ summary: summary, git: git }, basePackageVersion)); testShowPackage(s, fullPackageName, _.extend({ summary: summary, git: git }, basePackage)); // By the way, you can't update from outside a Meteor package directory. var run = s.run("publish", "--update"); run.matchErr("You're not in a Meteor package directory"); run.expectExit(1); }); // Regression test for #3676. selftest.define("publish prebuilt package", ["net", "test-package-server", "slow"], function () { var s = new Sandbox(); var fullPackageName = randomizedPackageName(username); s.createApp("myapp", "empty"); s.cd("myapp"); // This bug required the app to have a Cordova platform, so that the app's // cache would be built with the cordova unibuild which matches what we're // trying to publish. s.write('.meteor/platforms', 'server\nbrowser\nandroid\n'); s.mkdir('packages'); s.cd('packages'); s.createPackage('p', fullPackageName, 'package-for-show'); // This adds the package and saves a built version of it to the local // IsopackCache. var run = s.run('add', fullPackageName); run.expectExit(0); s.cd('p'); testUtils.login(s, username, password); // Before fixing #3676, this crashed because it didn't read the // pluginProviderPackageMap from the IsopackCache. var run = s.run('publish', '--create'); run.waitSecs(30); run.match('Published'); run.expectExit(0); });
/** * ag-grid - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components * @version v8.0.0 * @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 __param = (this && this.__param) || function (paramIndex, decorator) { return function (target, key) { decorator(target, key, paramIndex); } }; var utils_1 = require('./utils'); var context_1 = require("./context/context"); var context_2 = require("./context/context"); var logger_1 = require("./logger"); var eventService_1 = require("./eventService"); var events_1 = require("./events"); var context_3 = require("./context/context"); var gridOptionsWrapper_1 = require("./gridOptionsWrapper"); var context_4 = require("./context/context"); var constants_1 = require("./constants"); var SelectionController = (function () { function SelectionController() { } SelectionController.prototype.setBeans = function (loggerFactory) { this.logger = loggerFactory.create('SelectionController'); this.reset(); if (this.gridOptionsWrapper.isRowModelDefault()) { this.eventService.addEventListener(events_1.Events.EVENT_ROW_DATA_CHANGED, this.reset.bind(this)); } else { this.logger.log('dont know what to do here'); } }; SelectionController.prototype.init = function () { this.groupSelectsChildren = this.gridOptionsWrapper.isGroupSelectsChildren(); this.eventService.addEventListener(events_1.Events.EVENT_ROW_SELECTED, this.onRowSelected.bind(this)); }; SelectionController.prototype.setLastSelectedNode = function (rowNode) { this.lastSelectedNode = rowNode; }; SelectionController.prototype.getLastSelectedNode = function () { return this.lastSelectedNode; }; SelectionController.prototype.getSelectedNodes = function () { var selectedNodes = []; utils_1.Utils.iterateObject(this.selectedNodes, function (key, rowNode) { if (rowNode) { selectedNodes.push(rowNode); } }); return selectedNodes; }; SelectionController.prototype.getSelectedRows = function () { var selectedRows = []; utils_1.Utils.iterateObject(this.selectedNodes, function (key, rowNode) { if (rowNode) { selectedRows.push(rowNode.data); } }); return selectedRows; }; SelectionController.prototype.removeGroupsFromSelection = function () { var _this = this; utils_1.Utils.iterateObject(this.selectedNodes, function (key, rowNode) { if (rowNode && rowNode.group) { _this.selectedNodes[rowNode.id] = undefined; } }); }; // should only be called if groupSelectsChildren=true SelectionController.prototype.updateGroupsFromChildrenSelections = function () { if (this.rowModel.getType() !== constants_1.Constants.ROW_MODEL_TYPE_NORMAL) { console.warn('updateGroupsFromChildrenSelections not available when rowModel is not normal'); } var inMemoryRowModel = this.rowModel; inMemoryRowModel.getTopLevelNodes().forEach(function (rowNode) { rowNode.depthFirstSearch(function (rowNode) { if (rowNode.group) { rowNode.calculateSelectedFromChildren(); } }); }); }; SelectionController.prototype.getNodeForIdIfSelected = function (id) { return this.selectedNodes[id]; }; SelectionController.prototype.clearOtherNodes = function (rowNodeToKeepSelected) { var _this = this; var groupsToRefresh = {}; var updatedCount = 0; utils_1.Utils.iterateObject(this.selectedNodes, function (key, otherRowNode) { if (otherRowNode && otherRowNode.id !== rowNodeToKeepSelected.id) { var rowNode = _this.selectedNodes[otherRowNode.id]; updatedCount += rowNode.setSelectedParams({ newValue: false, clearSelection: false, tailingNodeInSequence: true }); if (_this.groupSelectsChildren && otherRowNode.parent) { groupsToRefresh[otherRowNode.parent.id] = otherRowNode.parent; } } }); utils_1.Utils.iterateObject(groupsToRefresh, function (key, group) { group.calculateSelectedFromChildren(); }); return updatedCount; }; SelectionController.prototype.onRowSelected = function (event) { var rowNode = event.node; // we do not store the group rows when the groups select children if (this.groupSelectsChildren && rowNode.group) { return; } if (rowNode.isSelected()) { this.selectedNodes[rowNode.id] = rowNode; } else { this.selectedNodes[rowNode.id] = undefined; } }; SelectionController.prototype.syncInRowNode = function (rowNode, oldNode) { this.syncInOldRowNode(rowNode, oldNode); this.syncInNewRowNode(rowNode); }; // if the id has changed for the node, then this means the rowNode // is getting used for a different data item, which breaks // our selectedNodes, as the node now is mapped by the old id // which is inconsistent. so to keep the old node as selected, // we swap in the clone (with the old id and old data). this means // the oldNode is effectively a daemon we keep a reference to, // so if client calls api.getSelectedNodes(), it gets the daemon // in the result. when the client un-selects, the reference to the // daemon is removed. the daemon, because it's an oldNode, is not // used by the grid for rendering, it's a copy of what the node used // to be like before the id was changed. SelectionController.prototype.syncInOldRowNode = function (rowNode, oldNode) { var oldNodeHasDifferentId = utils_1.Utils.exists(oldNode) && (rowNode.id !== oldNode.id); if (oldNodeHasDifferentId) { var oldNodeSelected = utils_1.Utils.exists(this.selectedNodes[oldNode.id]); if (oldNodeSelected) { this.selectedNodes[oldNode.id] = oldNode; } } }; SelectionController.prototype.syncInNewRowNode = function (rowNode) { if (utils_1.Utils.exists(this.selectedNodes[rowNode.id])) { rowNode.setSelectedInitialValue(true); this.selectedNodes[rowNode.id] = rowNode; } else { rowNode.setSelectedInitialValue(false); } }; SelectionController.prototype.reset = function () { this.logger.log('reset'); this.selectedNodes = {}; this.lastSelectedNode = null; }; // returns a list of all nodes at 'best cost' - a feature to be used // with groups / trees. if a group has all it's children selected, // then the group appears in the result, but not the children. // Designed for use with 'children' as the group selection type, // where groups don't actually appear in the selection normally. SelectionController.prototype.getBestCostNodeSelection = function () { if (this.rowModel.getType() !== constants_1.Constants.ROW_MODEL_TYPE_NORMAL) { console.warn('getBestCostNodeSelection is only avilable when using normal row model'); } var inMemoryRowModel = this.rowModel; var topLevelNodes = inMemoryRowModel.getTopLevelNodes(); if (topLevelNodes === null) { console.warn('selectAll not available doing rowModel=virtual'); return; } var result = []; // recursive function, to find the selected nodes function traverse(nodes) { for (var i = 0, l = nodes.length; i < l; i++) { var node = nodes[i]; if (node.isSelected()) { result.push(node); } else { // if not selected, then if it's a group, and the group // has children, continue to search for selections if (node.group && node.children) { traverse(node.children); } } } } traverse(topLevelNodes); return result; }; SelectionController.prototype.setRowModel = function (rowModel) { this.rowModel = rowModel; }; SelectionController.prototype.isEmpty = function () { var count = 0; utils_1.Utils.iterateObject(this.selectedNodes, function (nodeId, rowNode) { if (rowNode) { count++; } }); return count === 0; }; SelectionController.prototype.deselectAllRowNodes = function (justFiltered) { if (justFiltered === void 0) { justFiltered = false; } var inMemoryRowModel = this.rowModel; var callback = function (rowNode) { return rowNode.selectThisNode(false); }; if (justFiltered) { inMemoryRowModel.forEachNodeAfterFilter(callback); } else { inMemoryRowModel.forEachNode(callback); } // the above does not clean up the parent rows if they are selected if (this.rowModel.getType() === constants_1.Constants.ROW_MODEL_TYPE_NORMAL && this.groupSelectsChildren) { this.updateGroupsFromChildrenSelections(); } // we should not have to do this, as deselecting the nodes fires events // that we pick up, however it's good to clean it down, as we are still // left with entries pointing to 'undefined' if (!justFiltered) { this.selectedNodes = {}; } this.eventService.dispatchEvent(events_1.Events.EVENT_SELECTION_CHANGED); }; SelectionController.prototype.selectAllRowNodes = function (justFiltered) { if (justFiltered === void 0) { justFiltered = false; } if (this.rowModel.getType() !== constants_1.Constants.ROW_MODEL_TYPE_NORMAL) { throw "selectAll only available with normal row model, ie not " + this.rowModel.getType(); } var inMemoryRowModel = this.rowModel; var callback = function (rowNode) { return rowNode.selectThisNode(true); }; if (justFiltered) { inMemoryRowModel.forEachNodeAfterFilter(callback); } else { inMemoryRowModel.forEachNode(callback); } // the above does not clean up the parent rows if they are selected if (this.rowModel.getType() === constants_1.Constants.ROW_MODEL_TYPE_NORMAL && this.groupSelectsChildren) { this.updateGroupsFromChildrenSelections(); } this.eventService.dispatchEvent(events_1.Events.EVENT_SELECTION_CHANGED); }; // Deprecated method SelectionController.prototype.selectNode = function (rowNode, tryMulti) { rowNode.setSelectedParams({ newValue: true, clearSelection: !tryMulti }); }; // Deprecated method SelectionController.prototype.deselectIndex = function (rowIndex) { var node = this.rowModel.getRow(rowIndex); this.deselectNode(node); }; // Deprecated method SelectionController.prototype.deselectNode = function (rowNode) { rowNode.setSelectedParams({ newValue: false, clearSelection: false }); }; // Deprecated method SelectionController.prototype.selectIndex = function (index, tryMulti) { var node = this.rowModel.getRow(index); this.selectNode(node, tryMulti); }; __decorate([ context_3.Autowired('eventService'), __metadata('design:type', eventService_1.EventService) ], SelectionController.prototype, "eventService", void 0); __decorate([ context_3.Autowired('rowModel'), __metadata('design:type', Object) ], SelectionController.prototype, "rowModel", void 0); __decorate([ context_3.Autowired('gridOptionsWrapper'), __metadata('design:type', gridOptionsWrapper_1.GridOptionsWrapper) ], SelectionController.prototype, "gridOptionsWrapper", void 0); __decorate([ __param(0, context_2.Qualifier('loggerFactory')), __metadata('design:type', Function), __metadata('design:paramtypes', [logger_1.LoggerFactory]), __metadata('design:returntype', void 0) ], SelectionController.prototype, "setBeans", null); __decorate([ context_4.PostConstruct, __metadata('design:type', Function), __metadata('design:paramtypes', []), __metadata('design:returntype', void 0) ], SelectionController.prototype, "init", null); SelectionController = __decorate([ context_1.Bean('selectionController'), __metadata('design:paramtypes', []) ], SelectionController); return SelectionController; }()); exports.SelectionController = SelectionController;
var Collection = require('../../../lib/waterline/collection'), assert = require('assert'); describe('Collection', function() { /** * Test to ensure API compatibility methods * are correctly added to the Collection prototype */ describe('Query Methods', function() { var person; // Setup Fixture Model before(function() { var collection = Collection.extend({ identity: 'test' }); var schema = { schema: { test: { attributes: {} }}}; person = new collection(schema, { test: {} }); }); describe('Basic Finders', function() { it('should have .findOne() method', function() { assert(typeof person.findOne === 'function'); }); it('should have .find() method', function() { assert(typeof person.find === 'function'); }); it('should have .where() method', function() { assert(typeof person.where === 'function'); }); it('should have .select() method', function() { assert(typeof person.select === 'function'); }); it('should have .findOneLike() method', function() { assert(typeof person.findOneLike === 'function'); }); it('should have .findLike() method', function() { assert(typeof person.findLike === 'function'); }); it('should have .startsWith() method', function() { assert(typeof person.startsWith === 'function'); }); it('should have .endsWith() method', function() { assert(typeof person.endsWith === 'function'); }); it('should have .contains() method', function() { assert(typeof person.contains === 'function'); }); }); describe('DDL Functions', function() { it('should have .describe() method', function() { assert(typeof person.describe === 'function'); }); it('should have .alter() method', function() { assert(typeof person.alter === 'function'); }); it('should have .drop() method', function() { assert(typeof person.drop === 'function'); }); }); describe('DQL Functions', function() { it('should have .join() method', function() { assert(typeof person.join === 'function'); }); it('should have .create() method', function() { assert(typeof person.create === 'function'); }); it('should have .update() method', function() { assert(typeof person.update === 'function'); }); it('should have .destroy() method', function() { assert(typeof person.destroy === 'function'); }); it('should have .count() method', function() { assert(typeof person.count === 'function'); }); }); describe('Composite Functions', function() { it('should have .findOrCreate() method', function() { assert(typeof person.findOrCreate === 'function'); }); }); describe('Aggregate Functions', function() { it('should have .createEach() method', function() { assert(typeof person.createEach === 'function'); }); it('should have .findOrCreateEach() method', function() { assert(typeof person.findOrCreateEach === 'function'); }); }); }); });
'use strict'; var lint = require('./_lint'); ////////////////////////////// // SCSS syntax tests ////////////////////////////// describe('property sort order - scss', function () { var file = lint.file('property-sort-order.scss'); it('[order: alphabetical]', function (done) { lint.test(file, { 'property-sort-order': 1 }, function (data) { lint.assert.equal(15, data.warningCount); done(); }); }); it('[order: alphabetical, ignore-custom-properties: true]', function (done) { lint.test(file, { 'property-sort-order': [ 1, { 'ignore-custom-properties': true } ] }, function (data) { lint.assert.equal(12, data.warningCount); done(); }); }); it('[order: custom]', function (done) { lint.test(file, { 'property-sort-order': [ 1, { 'order': [ 'height', 'width', 'display', 'color' ] } ] }, function (data) { lint.assert.equal(8, data.warningCount); done(); }); }); it('[order: custom + composes, ignore-custom-properties: false]', function (done) { lint.test(file, { 'property-sort-order': [ 1, { 'order': [ 'height', 'composes', 'width', 'display', 'color' ], 'ignore-custom-properties': false } ] }, function (data) { lint.assert.equal(10, data.warningCount); done(); }); }); it('[order: custom + composes, ignore-custom-properties: true]', function (done) { lint.test(file, { 'property-sort-order': [ 1, { 'order': [ 'height', 'width', 'display', 'color' ], 'ignore-custom-properties': true } ] }, function (data) { lint.assert.equal(8, data.warningCount); done(); }); }); it('[order: recess]', function (done) { lint.test(file, { 'property-sort-order': [ 1, { 'order': 'recess' } ] }, function (data) { lint.assert.equal(12, data.warningCount); done(); }); }); it('[order: smacss]', function (done) { lint.test(file, { 'property-sort-order': [ 1, { 'order': 'smacss' } ] }, function (data) { lint.assert.equal(12, data.warningCount); done(); }); }); it('[order: concentric]', function (done) { lint.test(file, { 'property-sort-order': [ 1, { 'order': 'concentric' } ] }, function (data) { lint.assert.equal(14, data.warningCount); done(); }); }); }); ////////////////////////////// // Sass syntax tests ////////////////////////////// describe('property sort order - sass', function () { var file = lint.file('property-sort-order.sass'); it('[order: alphabetical]', function (done) { lint.test(file, { 'property-sort-order': 1 }, function (data) { lint.assert.equal(15, data.warningCount); done(); }); }); it('[order: alphabetical, ignore-custom-properties: true]', function (done) { lint.test(file, { 'property-sort-order': [ 1, { 'ignore-custom-properties': true } ] }, function (data) { lint.assert.equal(12, data.warningCount); done(); }); }); it('[order: custom]', function (done) { lint.test(file, { 'property-sort-order': [ 1, { 'order': [ 'height', 'width', 'display', 'color' ] } ] }, function (data) { lint.assert.equal(8, data.warningCount); done(); }); }); it('[order: custom + composes, ignore-custom-properties: false]', function (done) { lint.test(file, { 'property-sort-order': [ 1, { 'order': [ 'height', 'composes', 'width', 'display', 'color' ], 'ignore-custom-properties': false } ] }, function (data) { lint.assert.equal(10, data.warningCount); done(); }); }); it('[order: custom + composes, ignore-custom-properties: true]', function (done) { lint.test(file, { 'property-sort-order': [ 1, { 'order': [ 'height', 'width', 'display', 'color' ], 'ignore-custom-properties': true } ] }, function (data) { lint.assert.equal(8, data.warningCount); done(); }); }); it('[order: recess]', function (done) { lint.test(file, { 'property-sort-order': [ 1, { 'order': 'recess' } ] }, function (data) { lint.assert.equal(12, data.warningCount); done(); }); }); it('[order: smacss]', function (done) { lint.test(file, { 'property-sort-order': [ 1, { 'order': 'smacss' } ] }, function (data) { lint.assert.equal(12, data.warningCount); done(); }); }); it('[order: concentric]', function (done) { lint.test(file, { 'property-sort-order': [ 1, { 'order': 'concentric' } ] }, function (data) { lint.assert.equal(14, data.warningCount); done(); }); }); });
var _curry3 = require('./internal/_curry3'); var mergeWithKey = require('./mergeWithKey'); /** * Creates a new object with the own properties of the two provided objects. If * a key exists in both objects, the provided function is applied to the values * associated with the key in each object, with the result being used as the * value associated with the key in the returned object. The key will be * excluded from the returned object if the resulting value is `undefined`. * * @func * @memberOf R * @since v0.19.0 * @category Object * @sig (a -> a -> a) -> {a} -> {a} -> {a} * @param {Function} fn * @param {Object} l * @param {Object} r * @return {Object} * @see R.merge, R.mergeWithKey * @example * * R.mergeWith(R.concat, * { a: true, values: [10, 20] }, * { b: true, values: [15, 35] }); * //=> { a: true, b: true, values: [10, 20, 15, 35] } */ module.exports = _curry3(function mergeWith(fn, l, r) { return mergeWithKey(function(_, _l, _r) { return fn(_l, _r); }, l, r); });
'use strict'; var semver = require('semver'); var debug = require('debug')('google-cdn'); var replacements = require('./lib/data').replacements; var versions = require('./lib/data').versions; var bowerUtil = require('./util/bower'); var hoist = require('./util/hoist'); var CDN_AJAX_PATH = '//ajax.googleapis.com/ajax/libs/'; function getVersionStr(bowerJson, name) { var versionStr; if (bowerJson.dependencies) { versionStr = bowerJson.dependencies[name]; } if (!versionStr && bowerJson.devDependencies && bowerJson.devDependencies[name]) { versionStr = bowerJson.devDependencies[name]; } return versionStr; } module.exports = function cdnify(content, bowerJson, options) { options = options || {}; options.componentsPath = options.componentsPath || 'bower_components'; Object.keys(replacements).forEach(function (item) { var replacement = replacements[item]; var versionStr = getVersionStr(bowerJson, item); if (!versionStr) { return; } var version = semver.maxSatisfying(versions[item], versionStr); if (version) { debug('Choosing version %s for dependency %s', version, item); var from = bowerUtil.joinComponent(options.componentsPath, replacement.from); var to = replacement.to(version); content = content.replace(from, to); debug('Replaced %s with %s', from, to); } else { debug('Could not find satisfying version for %s %s', item, versionStr); } }); var linesToMove = []; content.split('\n').forEach(function (line) { if (line.indexOf(CDN_AJAX_PATH) !== -1) { linesToMove.push(line); } }); try { content = hoist({ body: content, marker: '<!-- build:js scripts/scripts.js -->', move: linesToMove }); } catch (e) { debug('Hoisting failed: %s', e); } return content; };
var falseFunc = require("boolbase").falseFunc; //https://github.com/slevithan/XRegExp/blob/master/src/xregexp.js#L469 var reChars = /[-[\]{}()*+?.,\\^$|#\s]/g; /* attribute selectors */ var attributeRules = { __proto__: null, equals: function(next, data, options) { var name = data.name; var value = data.value; var adapter = options.adapter; if (data.ignoreCase) { value = value.toLowerCase(); return function equalsIC(elem) { var attr = adapter.getAttributeValue(elem, name); return attr != null && attr.toLowerCase() === value && next(elem); }; } return function equals(elem) { return adapter.getAttributeValue(elem, name) === value && next(elem); }; }, hyphen: function(next, data, options) { var name = data.name; var value = data.value; var len = value.length; var adapter = options.adapter; if (data.ignoreCase) { value = value.toLowerCase(); return function hyphenIC(elem) { var attr = adapter.getAttributeValue(elem, name); return ( attr != null && (attr.length === len || attr.charAt(len) === "-") && attr.substr(0, len).toLowerCase() === value && next(elem) ); }; } return function hyphen(elem) { var attr = adapter.getAttributeValue(elem, name); return ( attr != null && attr.substr(0, len) === value && (attr.length === len || attr.charAt(len) === "-") && next(elem) ); }; }, element: function(next, data, options) { var name = data.name; var value = data.value; var adapter = options.adapter; if (/\s/.test(value)) { return falseFunc; } value = value.replace(reChars, "\\$&"); var pattern = "(?:^|\\s)" + value + "(?:$|\\s)", flags = data.ignoreCase ? "i" : "", regex = new RegExp(pattern, flags); return function element(elem) { var attr = adapter.getAttributeValue(elem, name); return attr != null && regex.test(attr) && next(elem); }; }, exists: function(next, data, options) { var name = data.name; var adapter = options.adapter; return function exists(elem) { return adapter.hasAttrib(elem, name) && next(elem); }; }, start: function(next, data, options) { var name = data.name; var value = data.value; var len = value.length; var adapter = options.adapter; if (len === 0) { return falseFunc; } if (data.ignoreCase) { value = value.toLowerCase(); return function startIC(elem) { var attr = adapter.getAttributeValue(elem, name); return attr != null && attr.substr(0, len).toLowerCase() === value && next(elem); }; } return function start(elem) { var attr = adapter.getAttributeValue(elem, name); return attr != null && attr.substr(0, len) === value && next(elem); }; }, end: function(next, data, options) { var name = data.name; var value = data.value; var len = -value.length; var adapter = options.adapter; if (len === 0) { return falseFunc; } if (data.ignoreCase) { value = value.toLowerCase(); return function endIC(elem) { var attr = adapter.getAttributeValue(elem, name); return attr != null && attr.substr(len).toLowerCase() === value && next(elem); }; } return function end(elem) { var attr = adapter.getAttributeValue(elem, name); return attr != null && attr.substr(len) === value && next(elem); }; }, any: function(next, data, options) { var name = data.name; var value = data.value; var adapter = options.adapter; if (value === "") { return falseFunc; } if (data.ignoreCase) { var regex = new RegExp(value.replace(reChars, "\\$&"), "i"); return function anyIC(elem) { var attr = adapter.getAttributeValue(elem, name); return attr != null && regex.test(attr) && next(elem); }; } return function any(elem) { var attr = adapter.getAttributeValue(elem, name); return attr != null && attr.indexOf(value) >= 0 && next(elem); }; }, not: function(next, data, options) { var name = data.name; var value = data.value; var adapter = options.adapter; if (value === "") { return function notEmpty(elem) { return !!adapter.getAttributeValue(elem, name) && next(elem); }; } else if (data.ignoreCase) { value = value.toLowerCase(); return function notIC(elem) { var attr = adapter.getAttributeValue(elem, name); return attr != null && attr.toLowerCase() !== value && next(elem); }; } return function not(elem) { return adapter.getAttributeValue(elem, name) !== value && next(elem); }; } }; module.exports = { compile: function(next, data, options) { if (options && options.strict && (data.ignoreCase || data.action === "not")) { throw new Error("Unsupported attribute selector"); } return attributeRules[data.action](next, data, options); }, rules: attributeRules };
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let HardwareWatch = (props) => ( <SvgIcon {...props}> <path d="M20 12c0-2.54-1.19-4.81-3.04-6.27L16 0H8l-.95 5.73C5.19 7.19 4 9.45 4 12s1.19 4.81 3.05 6.27L8 24h8l.96-5.73C18.81 16.81 20 14.54 20 12zM6 12c0-3.31 2.69-6 6-6s6 2.69 6 6-2.69 6-6 6-6-2.69-6-6z"/> </SvgIcon> ); HardwareWatch = pure(HardwareWatch); HardwareWatch.displayName = 'HardwareWatch'; HardwareWatch.muiName = 'SvgIcon'; export default HardwareWatch;
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionChromeReaderMode = (props) => ( <SvgIcon {...props}> <path d="M13 12h7v1.5h-7zm0-2.5h7V11h-7zm0 5h7V16h-7zM21 4H3c-1.1 0-2 .9-2 2v13c0 1.1.9 2 2 2h18c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2zm0 15h-9V6h9v13z"/> </SvgIcon> ); ActionChromeReaderMode = pure(ActionChromeReaderMode); ActionChromeReaderMode.displayName = 'ActionChromeReaderMode'; ActionChromeReaderMode.muiName = 'SvgIcon'; export default ActionChromeReaderMode;
YUI.add('view', function(Y) { /** Represents a logical piece of an application's user interface, and provides a lightweight, overridable API for rendering content and handling delegated DOM events on a container element. @module app @submodule view @since 3.4.0 **/ /** Represents a logical piece of an application's user interface, and provides a lightweight, overridable API for rendering content and handling delegated DOM events on a container element. The View class imposes little structure and provides only minimal functionality of its own: it's basically just an overridable API interface that helps you implement custom views. As of YUI 3.5.0, View allows ad-hoc attributes to be specified at instantiation time, so you don't need to subclass `Y.View` to add custom attributes. Just pass them to the constructor: var view = new Y.View({foo: 'bar'}); view.get('foo'); // => "bar" @class View @constructor @extends Base @since 3.4.0 **/ function View() { View.superclass.constructor.apply(this, arguments); } Y.View = Y.extend(View, Y.Base, { // -- Public Properties ---------------------------------------------------- /** Template for this view's container. @property containerTemplate @type String @default "<div/>" @since 3.5.0 **/ containerTemplate: '<div/>', /** Hash of CSS selectors mapped to events to delegate to elements matching those selectors. CSS selectors are relative to the `container` element. Events are attached to the container, and delegation is used so that subscribers are only notified of events that occur on elements inside the container that match the specified selectors. This allows the container's contents to be re- rendered as needed without losing event subscriptions. Event handlers can be specified either as functions or as strings that map to function names on this view instance or its prototype. The `this` object in event handlers will refer to this view instance. If you'd prefer `this` to be something else, use `Y.bind()` to bind a custom `this` object. @example var view = new Y.View({ events: { // Call `this.toggle()` whenever the element with the id // "toggle-button" is clicked. '#toggle-button': {click: 'toggle'}, // Call `this.hoverOn()` when the mouse moves over any element // with the "hoverable" class, and `this.hoverOff()` when the // mouse moves out of any element with the "hoverable" class. '.hoverable': { mouseover: 'hoverOn', mouseout : 'hoverOff' } } }); @property events @type Object @default {} **/ events: {}, /** Template for this view's contents. This is a convenience property that has no default behavior of its own. It's only provided as a convention to allow you to store whatever you consider to be a template, whether that's an HTML string, a `Y.Node` instance, a Mustache template, or anything else your little heart desires. How this template gets used is entirely up to you and your custom `render()` method. @property template @type mixed @default '' **/ template: '', // -- Protected Properties ------------------------------------------------- /** This tells `Y.Base` that it should create ad-hoc attributes for config properties passed to View's constructor. This makes it possible to instantiate a view and set a bunch of attributes without having to subclass `Y.View` and declare all those attributes first. @property _allowAdHocAttrs @type Boolean @default true @protected @since 3.5.0 **/ _allowAdHocAttrs: true, // -- Lifecycle Methods ---------------------------------------------------- initializer: function (config) { config || (config = {}); // Set instance properties specified in the config. config.containerTemplate && (this.containerTemplate = config.containerTemplate); config.template && (this.template = config.template); // Merge events from the config into events in `this.events`. this.events = config.events ? Y.merge(this.events, config.events) : this.events; // When the container node changes (or when it's set for the first // time), we'll attach events to it, but not until then. This allows the // container to be created lazily the first time it's accessed rather // than always on init. this.after('containerChange', this._afterContainerChange); }, /** Destroys this View, detaching any DOM events and optionally also destroying its container node. By default, the container node will not be destroyed. Pass an _options_ object with a truthy `remove` property to destroy the container as well. @method destroy @param {Object} [options] Options. @param {Boolean} [options.remove=false] If `true`, this View's container will be removed from the DOM and destroyed as well. @chainable */ destroy: function (options) { // We also accept `delete` as a synonym for `remove`. if (options && (options.remove || options['delete'])) { // Attaching an event handler here because the `destroy` event is // preventable. If we destroyed the container before calling the // superclass's `destroy()` method and the event was prevented, the // class would end up in a broken state. this.onceAfter('destroy', function () { this._destroyContainer(); }); } return View.superclass.destroy.call(this); }, destructor: function () { this.detachEvents(); delete this._container; }, // -- Public Methods ------------------------------------------------------- /** Attaches delegated event handlers to this view's container element. This method is called internally to subscribe to events configured in the `events` attribute when the view is initialized. You may override this method to customize the event attaching logic. @method attachEvents @param {Object} [events] Hash of events to attach. See the docs for the `events` attribute for details on the format. If not specified, this view's `events` property will be used. @chainable @see detachEvents **/ attachEvents: function (events) { var container = this.get('container'), owns = Y.Object.owns, handler, handlers, name, selector; this.detachEvents(); events || (events = this.events); for (selector in events) { if (!owns(events, selector)) { continue; } handlers = events[selector]; for (name in handlers) { if (!owns(handlers, name)) { continue; } handler = handlers[name]; if (typeof handler === 'string') { handler = this[handler]; } this._attachedViewEvents.push( container.delegate(name, handler, selector, this)); } } return this; }, /** Creates and returns a container node for this view. By default, the container is created from the HTML template specified in the `containerTemplate` property, and is _not_ added to the DOM automatically. You may override this method to customize how the container node is created (such as by rendering it from a custom template format). Your method must return a `Y.Node` instance. @method create @param {HTMLElement|Node|String} [container] Selector string, `Y.Node` instance, or DOM element to use at the container node. @return {Node} Node instance of the created container node. **/ create: function (container) { return container ? Y.one(container) : Y.Node.create(this.containerTemplate); }, /** Detaches DOM events that have previously been attached to the container by `attachEvents()`. @method detachEvents @chainable @see attachEvents **/ detachEvents: function () { Y.Array.each(this._attachedViewEvents, function (handle) { handle.detach(); }); this._attachedViewEvents = []; return this; }, /** Removes this view's container element from the DOM (if it's in the DOM), but doesn't destroy it or any event listeners attached to it. @method remove @chainable **/ remove: function () { var container = this.get('container'); container && container.remove(); return this; }, /** Renders this view. This method is a noop by default. Override it to provide a custom implementation that renders this view's content and appends it to the container element. Ideally your `render` method should also return `this` as the end to allow chaining, but that's up to you. Since there's no default renderer, you're free to render your view however you see fit, whether that means manipulating the DOM directly, dumping strings into `innerHTML`, or using a template language of some kind. For basic templating needs, `Y.Node.create()` and `Y.Lang.sub()` may suffice, but there are no restrictions on what tools or techniques you can use to render your view. All you need to do is append something to the container element at some point, and optionally append the container to the DOM if it's not there already. @method render @chainable **/ render: function () { return this; }, // -- Protected Methods ---------------------------------------------------- /** Removes the `container` from the DOM and purges all its event listeners. @method _destroyContainer @protected **/ _destroyContainer: function () { var container = this.get('container'); container && container.remove(true); }, /** Getter for the `container` attribute. @method _getContainer @param {Node|null} value Current attribute value. @return {Node} Container node. @protected @since 3.5.0 **/ _getContainer: function (value) { // This wackiness is necessary to enable fully lazy creation of the // container node both when no container is specified and when one is // specified via a valueFn. if (!this._container) { if (value) { // Attach events to the container when it's specified via a // valueFn, which won't fire the containerChange event. this._container = value; this.attachEvents(); } else { // Create a default container and set that as the new attribute // value. The `this._container` property prevents infinite // recursion. value = this._container = this.create(); this._set('container', value); } } return value; }, // -- Protected Event Handlers --------------------------------------------- /** Handles `containerChange` events. Detaches event handlers from the old container (if any) and attaches them to the new container. Right now the `container` attr is initOnly so this event should only ever fire the first time the container is created, but in the future (once Y.App can handle it) we may allow runtime container changes. @method _afterContainerChange @protected @since 3.5.0 **/ _afterContainerChange: function () { this.attachEvents(this.events); } }, { NAME: 'view', ATTRS: { /** Container node into which this view's content will be rendered. The container node serves as the host for all DOM events attached by the view. Delegation is used to handle events on children of the container, allowing the container's contents to be re-rendered at any time without losing event subscriptions. The default container is a `<div>` Node, but you can override this in a subclass, or by passing in a custom `container` config value at instantiation time. If you override the default container in a subclass using `ATTRS`, you must use the `valueFn` property. The view's constructor will ignore any assignments using `value`. When `container` is overridden by a subclass or passed as a config option at instantiation time, you can provide it as a selector string, a DOM element, a `Y.Node` instance, or (if you are subclassing and modifying the attribute), a `valueFn` function that returns a `Y.Node` instance. The value will be converted into a `Y.Node` instance if it isn't one already. The container is not added to the page automatically. This allows you to have full control over how and when your view is actually rendered to the page. @attribute container @type HTMLElement|Node|String @default Y.Node.create(this.containerTemplate) @writeOnce **/ container: { getter : '_getContainer', setter : Y.one, writeOnce: true } }, /** Properties that shouldn't be turned into ad-hoc attributes when passed to View's constructor. @property _NON_ATTRS_CFG @type Array @static @protected @since 3.5.0 **/ _NON_ATTRS_CFG: [ 'containerTemplate', 'events', 'template' ] }); }, '@VERSION@' ,{requires:['base-build', 'node-event-delegate']});
/* Copyright (c) 2014, Yahoo! Inc. All rights reserved. Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms. */ (function (root, factory) { 'use strict'; var Intl = root.Intl || root.IntlPolyfill, MessageFormat = factory(Intl); // register in -all- the module systems (at once) if (typeof define === 'function' && define.amd) { define(MessageFormat); } if (typeof module === 'object' && typeof module.exports === 'object') { module.exports = MessageFormat; } if (root) { root.IntlMessageFormat = MessageFormat; } })(typeof global !== 'undefined' ? global : this, function (Intl) { 'use strict'; if (!Intl) { throw new ReferenceError ('Intl must be available'); } // -- ES5 Built-ins -------------------------------------------------------- // Purposely using the same implementation as the Intl.js `Intl` polyfill. // Copyright 2013 Andy Earnshaw, MIT License // Used for proto-less objects which won't have this method. var hop = Object.prototype.hasOwnProperty; var realDefineProp = (function () { try { return !!Object.defineProperty({}, 'a', {}); } catch (e) { return false; } })(); var es3 = !realDefineProp && !Object.prototype.__defineGetter__; var defineProperty = realDefineProp ? Object.defineProperty : function (obj, name, desc) { if ('get' in desc && obj.__defineGetter__) { obj.__defineGetter__(name, desc.get); } else if (!hop.call(obj, name) || 'value' in desc) { obj[name] = desc.value; } }; var objCreate = Object.create || function (proto, props) { var obj, k; function F() {} F.prototype = proto; obj = new F(); for (k in props) { if (hop.call(props, k)) { defineProperty(obj, k, props[k]); } } return obj; }; var fnBind = Function.prototype.bind || function (thisObj) { var fn = this, args = [].slice.call(arguments, 1); return function () { fn.apply(thisObj, args.concat([].slice.call(arguments))); }; }; // -- MessageFormat -------------------------------------------------------- function MessageFormat(pattern, locales, formats) { // Parse string messages into a tokenized JSON structure for traversal. if (typeof pattern === 'string') { pattern = MessageFormat.__parse(pattern); } if (!(pattern && typeof pattern.length === 'number')) { throw new TypeError('A pattern must be provided as a String or Array.'); } // Creates a new object with the specified `formats` merged with the // default formats. formats = this._mergeFormats(MessageFormat.FORMATS, formats); // Defined first because it's used to build the format pattern. defineProperty(this, '_locale', {value: this._resolveLocale(locales)}); // Define the `pattern` property, a compiled pattern that is highly // optimized for repeated `format()` invocations. **Note:** This passes // the `locales` set provided to the constructor instead of just the // resolved locale. pattern = this._compilePattern(pattern, locales, formats); defineProperty(this, '_pattern', {value: pattern}); // Bind `format()` method to `this` so it can be passed by reference // like the other `Intl` APIs. this.format = fnBind.call(this.format, this); } // Default format options used as the prototype of the `formats` provided to // the constructor. These are used when constructing the internal // Intl.NumberFormat and Intl.DateTimeFormat instances. defineProperty(MessageFormat, 'FORMATS', { enumerable: true, value: { number: { 'currency': { style: 'currency' }, 'percent': { style: 'percent' } }, date: { 'short': { month: 'numeric', day : 'numeric', year : '2-digit' }, 'medium': { month: 'short', day : 'numeric', year : 'numeric' }, 'long': { month: 'long', day : 'numeric', year : 'numeric' }, 'full': { weekday: 'long', month : 'long', day : 'numeric', year : 'numeric' } }, time: { 'short': { hour : 'numeric', minute: 'numeric' }, 'medium': { hour : 'numeric', minute: 'numeric', second: 'numeric' }, 'long': { hour : 'numeric', minute : 'numeric', second : 'numeric', timeZoneName: 'short' }, 'full': { hour : 'numeric', minute : 'numeric', second : 'numeric', timeZoneName: 'short' } } } }); // Define internal private properties for dealing with locale data. defineProperty(MessageFormat, '__availableLocales__', {value: []}); defineProperty(MessageFormat, '__localeData__', {value: objCreate(null)}); defineProperty(MessageFormat, '__addLocaleData', {value: function (data) { if (!(data && data.locale)) { throw new Error('Object passed does not identify itself with a valid language tag'); } if (!data.messageformat) { throw new Error('Object passed does not contain locale data for IntlMessageFormat'); } var availableLocales = MessageFormat.__availableLocales__, localeData = MessageFormat.__localeData__; // Message format locale data only requires the first part of the tag. var locale = data.locale.toLowerCase().split('-')[0]; availableLocales.push(locale); localeData[locale] = data.messageformat; if (MessageFormat.defaultLocale === undefined) { MessageFormat.defaultLocale = locale; } }}); // Defines `__parse()` static method as an exposed private. defineProperty(MessageFormat, '__parse', {value: parse}); // Define public `defaultLocale` property which is set when the first bundle // of locale data is added. defineProperty(MessageFormat, 'defaultLocale', { enumerable: true, writable : true }); MessageFormat.prototype.format = function (values) { return this._format(this._pattern, values); }; MessageFormat.prototype.resolvedOptions = function () { // TODO: Provide anything else? return { locale: this._locale }; }; MessageFormat.prototype._compilePattern = function (pattern, locales, formats) { // Wrap string patterns with an array for iteration control flow. if (typeof pattern === 'string') { pattern = [pattern]; } var locale = this._locale, localeData = MessageFormat.__localeData__, formatPattern = [], i, len, part, type, valueName, format, pluralFunction, options, key, optionsParts, option; for (i = 0, len = pattern.length; i < len; i += 1) { part = pattern[i]; // Checks if string part is a simple string, or if it has a // tokenized place-holder that needs to be substituted. if (typeof part === 'string') { formatPattern.push(createStringPart(part)); continue; } type = part.type; valueName = part.valueName; options = part.options; // Handles plural and select parts' options by building format // patterns for each option. if (options) { optionsParts = {}; for (key in options) { if (!hop.call(options, key)) { continue; } option = options[key]; // Early exit and special handling for plural options with a // "${#}" token. These options will have this token replaced // with NumberFormat wrap with optional prefix and suffix. if (type === 'plural' && typeof option === 'string' && option.indexOf('${#}') >= 0) { option = option.match(/(.*)\${#}(.*)/); optionsParts[key] = [ option[1], // prefix { valueName: valueName, format : new Intl.NumberFormat(locales).format }, option[2] // suffix ]; continue; } // Recursively compiles a format pattern for the option. optionsParts[key] = this._compilePattern(option, locales, formats); } } // Create a specialized format part for each type. This creates a // common interface for the `format()` method and encapsulates the // relevant data need for each type of formatting. switch (type) { case 'date': format = formats.date[part.format]; formatPattern.push({ valueName: valueName, format : new Intl.DateTimeFormat(locales, format).format }); break; case 'time': format = formats.time[part.format]; formatPattern.push({ valueName: valueName, format : new Intl.DateTimeFormat(locales, format).format }); break; case 'number': format = formats.number[part.format]; formatPattern.push({ valueName: valueName, format : new Intl.NumberFormat(locales, format).format }); break; case 'plural': pluralFunction = localeData[locale].pluralFunction; formatPattern.push(new PluralPart(valueName, optionsParts, pluralFunction)); break; case 'select': formatPattern.push(new SelectPart(valueName, optionsParts)); break; default: throw new Error('Message pattern part at index ' + i + ' does not have a valid type'); } } return formatPattern; }; MessageFormat.prototype._format = function (pattern, values) { var result = '', i, len, part, valueName, value, options; for (i = 0, len = pattern.length; i < len; i += 1) { part = pattern[i]; // Exist early for string parts. if (typeof part === 'string') { result += part; continue; } valueName = part.valueName; // Enforce that all required values are provided by the caller. if (!(values && hop.call(values, valueName))) { throw new Error('A value must be provided for: ' + valueName); } value = values[valueName]; options = part.options; // Recursively format plural and select parts' option — which can be // a nested pattern structure. The choosing of the option to use is // abstracted-by and delegated-to the part helper object. if (options) { result += this._format(part.getOption(value), values); } else { result += part.format(value); } } return result; }; MessageFormat.prototype._mergeFormats = function (defaults, formats) { var mergedFormats = {}, type, mergedType; for (type in defaults) { if (!hop.call(defaults, type)) { continue; } mergedFormats[type] = mergedType = objCreate(defaults[type]); if (formats && hop.call(formats, type)) { extend(mergedType, formats[type]); } } return mergedFormats; }; MessageFormat.prototype._resolveLocale = function (locales) { var availableLocales = MessageFormat.__availableLocales__, locale, parts, i, len; if (availableLocales.length === 0) { throw new Error('No locale data has been provided for IntlMessageFormat yet'); } if (typeof locales === 'string') { locales = [locales]; } if (locales && locales.length) { for (i = 0, len = locales.length; i < len; i += 1) { locale = locales[i].toLowerCase().split('-')[0]; // Make sure the first part of the locale that we care about is // structurally valid. if (!/[a-z]{2,3}/i.test(locale)) { throw new RangeError('"' + locales[i] + '" is not a structurally valid language tag'); } if (availableLocales.indexOf(locale) >= 0) { break; } } } return locale || MessageFormat.defaultLocale; }; // -- MessageFormat Helpers ------------------------------------------------ var RE_PARSED_TOKEN = /^\${([-\w]+)}$/; function createStringPart(str) { var token = str.match(RE_PARSED_TOKEN); return token ? new StringPart(token[1]) : str; } function StringPart(valueName) { this.valueName = valueName; } StringPart.prototype.format = function (value) { if (!value) { return ''; } return typeof value === 'string' ? value : String(value); }; function SelectPart(valueName, options) { this.valueName = valueName; this.options = options; } SelectPart.prototype.getOption = function (value) { var options = this.options; return options[value] || options.other; }; function PluralPart(valueName, options, pluralFunction) { this.valueName = valueName; this.options = options; this.pluralFunction = pluralFunction; } PluralPart.prototype.getOption = function (value) { var options = this.options, option = this.pluralFunction(value); return options[option] || options.other; }; // -- MessageFormat Parser ------------------------------------------------- // Copied from: https://github.com/yahoo/locator-lang // `type` (required): The name of the message format type. // `regex` (required): The regex used to check if this formatter can parse the message. // `parse` (required): The main parse method which is given the full message. // `tokenParser` (optional): Used to parse the remaining tokens of a message (what remains after the variable and the format type). // `postParser` (optional): Used to format the output before returning from the main `parse` method. // `outputFormatter` (optional): Used to format the fully parsed string returned from the base case of the recursive parser. var FORMATTERS = [ { type: 'string', regex: /^{\s*([-\w]+)\s*}$/, parse: formatElementParser, postParser: function (parsed) { return '${' + parsed.valueName + '}'; } }, { type: 'select', regex: /^{\s*([-\w]+)\s*,\s*select\s*,\s*(.*)\s*}$/, parse: formatElementParser, tokenParser: pairedOptionsParser }, { type: 'plural', regex: /^{\s*([-\w]+)\s*,\s*plural\s*,\s*(.*)\s*}$/, parse: formatElementParser, tokenParser: pairedOptionsParser, outputFormatter: function (str) { return str.replace(/#/g, '${#}'); } }, { type: 'time', regex: /^{\s*([-\w]+)\s*,\s*time(?:,(.*))?\s*}$/, parse: formatElementParser, tokenParser: formatOptionParser, postParser: function (parsed) { parsed.format = parsed.format || 'medium'; return parsed; } }, { type: 'date', regex: /^{\s*([-\w]+)\s*,\s*date(?:,(.*))?\s*}$/, parse: formatElementParser, tokenParser: formatOptionParser, postParser: function (parsed) { parsed.format = parsed.format || 'medium'; return parsed; } }, { type: 'number', regex: /^{\s*([-\w]+)\s*,\s*number(?:,(.*))?\s*}$/, parse: formatElementParser, tokenParser: formatOptionParser }, { type: 'custom', regex: /^{\s*([-\w]+)\s*,\s*([a-zA-Z]*)(?:,(.*))?\s*}$/, parse: formatElementParser, tokenParser:formatOptionParser } ]; /** Tokenizes a MessageFormat pattern. @method tokenize @param {String} pattern A pattern @param {Boolean} trim Whether or not the tokens should be trimmed of whitespace @return {Array} Tokens **/ function tokenize (pattern, trim) { var bracketRE = /[{}]/g, tokens = [], balance = 0, startIndex = 0, endIndex, substr, match, i, len; match = bracketRE.exec(pattern); while (match) { // Keep track of balanced brackets balance += match[0] === '{' ? 1 : -1; // Imbalanced brackets detected (e.g. "}hello{", "{hello}}") if (balance < 0) { throw new Error('Imbalanced bracket detected at index ' + match.index + ' for message "' + pattern + '"'); } // Tokenize a pair of balanced brackets if (balance === 0) { endIndex = match.index + 1; tokens.push( pattern.slice(startIndex, endIndex) ); startIndex = endIndex; } // Tokenize any text that comes before the first opening bracket if (balance === 1 && startIndex !== match.index) { substr = pattern.slice(startIndex, match.index); if (substr.indexOf('{') === -1) { tokens.push(substr); startIndex = match.index; } } match = bracketRE.exec(pattern); } // Imbalanced brackets detected (e.g. "{{hello}") if (balance !== 0) { throw new Error('Brackets were not properly closed: ' + pattern); } // Tokenize any remaining non-empty string if (startIndex !== pattern.length) { tokens.push( pattern.slice(startIndex) ); } if (trim) { for (i = 0, len = tokens.length; i < len; i++) { tokens[i] = tokens[i].replace(/^\s+|\s+$/gm, ''); } } return tokens; } /** Gets the content of the format element by peeling off the outermost pair of brackets. @method getFormatElementContent @param {String} formatElement Format element @return {String} Contents of format element **/ function getFormatElementContent (formatElement) { return formatElement.replace(/^\{\s*/,'').replace(/\s*\}$/, ''); } /** Checks if the pattern contains a format element. @method containsFormatElement @param {String} pattern Pattern @return {Boolean} Whether or not the pattern contains a format element **/ function containsFormatElement (pattern) { return pattern.indexOf('{') >= 0; } /** Parses a list of tokens into paired options where the key is the option name and the value is the pattern. @method pairedOptionsParser @param {Object} parsed Parsed object @param {Array} tokens Remaining tokens that come after the value name and the format id @return {Object} Parsed object with added options **/ function pairedOptionsParser (parsed, tokens) { var hasDefault, value, name, l, i; parsed.options = {}; if (tokens.length % 2) { throw new Error('Options must come in pairs: ' + tokens.join(', ')); } for (i = 0, l = tokens.length; i < l; i += 2) { name = tokens[i]; value = tokens[i + 1]; parsed.options[name] = value; hasDefault = hasDefault || name === 'other'; } if (!hasDefault) { throw new Error('Options must include default "other" option: ' + tokens.join(', ')); } return parsed; } function formatOptionParser (parsed, tokens) { parsed.format = tokens[0]; return parsed; } /** Parses a format element. Format elements are surrounded by curly braces, and contain at least a value name. @method formatElementParser @param {String} formatElement A format element @param {Object} match The result of a String.match() that has at least the value name at index 1 and a subformat at index 2 @return {Object} Parsed object **/ function formatElementParser (formatElement, match, formatter) { var parsed = { type: formatter.type, valueName: match[1] }, tokens = match[2] && tokenize(match[2], true); // If there are any additional tokens to parse, it should be done here if (formatter.tokenParser && tokens) { parsed = formatter.tokenParser(parsed, tokens); } // Any final modifications to the parsed output should be done here if (formatter.postParser) { parsed = formatter.postParser(parsed); } return parsed; } /** For each formatter, test it on the token in order. Exit early on first token matched. @method parseToken @param {Array} tokens @param {Number} index @return {String|Object} Parsed token or original token */ function parseToken (tokens, index) { var i, len; for (i = 0, len = FORMATTERS.length; i < len; i++) { if (parseFormatTokens(FORMATTERS[i], tokens, index)) { return tokens[index]; } } return tokens[index]; } /** Attempts to parse a token at the given index with the provided formatter. If the token fails the `formatter.regex`, `false` is returned. Otherwise, the token is parsed with `formatter.parse`. Then if the token contains options due to the parsing process, it has each option processed. Then it returns `true` alerting the caller the token was parsed. @method parseFormatTokens @param {Object} formatter @param {Array} tokens @param {Number} tokenIndex @return {Boolean} */ function parseFormatTokens (formatter, tokens, tokenIndex) { var token = tokens[tokenIndex], match = token.match(formatter.regex), parsedToken, parsedKeys = [], key, i, len; if (match) { parsedToken = formatter.parse(token, match, formatter); tokens[tokenIndex] = parsedToken; // if we have options, each option must be parsed if (parsedToken && parsedToken.options && typeof parsedToken.options === 'object') { for (key in parsedToken.options) { if (parsedToken.options.hasOwnProperty(key)) { parsedKeys.push(key); } } } for (i = 0, len = parsedKeys.length; i < len; i++) { parseFormatOptions(parsedToken, parsedKeys[i], formatter); } return true; } return !!match; } /** @method parseFormatOptions @param {Object} */ function parseFormatOptions (parsedToken, key, formatter) { var value = parsedToken.options && parsedToken.options[key]; value = getFormatElementContent(value); parsedToken.options[key] = parse(value, formatter.outputFormatter); } /** Parses a pattern that may contain nested format elements. @method parse @param {String} pattern A pattern @return {Object|Array} Parsed output **/ function parse (pattern, outputFormatter) { var tokens, i, len; // base case (plain string) if (!containsFormatElement(pattern)) { // Final chance to format the string before the parser spits it out return outputFormatter ? outputFormatter(pattern) : [pattern]; } tokens = tokenize(pattern); for (i = 0, len = tokens.length; i < len; i++) { if (tokens[i].charAt(0) === '{') { // tokens must start with a { tokens[i] = parseToken(tokens, i); } } return tokens; } // -- Utilities ------------------------------------------------------------ function extend(obj) { var sources = Array.prototype.slice.call(arguments, 1), i, len, source, key; for (i = 0, len = sources.length; i < len; i += 1) { source = sources[i]; if (!source) { continue; } for (key in source) { if (source.hasOwnProperty(key)) { obj[key] = source[key]; } } } return obj; } return MessageFormat; }); IntlMessageFormat.__addLocaleData({locale:"nnh", messageformat:{pluralFunction:function (n) { n=Math.floor(n);if(n===1)return"one";return"other"; }}});
(function webpackUniversalModuleDefinition(root, factory) { if(typeof exports === 'object' && typeof module === 'object') module.exports = factory(require("react")); else if(typeof define === 'function' && define.amd) define(["react"], factory); else if(typeof exports === 'object') exports["ReactDataGrid"] = factory(require("react")); else root["ReactDataGrid"] = factory(root["React"]); })(this, function(__WEBPACK_EXTERNAL_MODULE_18__) { 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__) { 'use strict'; module.exports = __webpack_require__(1); module.exports.Editors = __webpack_require__(85); module.exports.Formatters = __webpack_require__(89); module.exports.Toolbar = __webpack_require__(91); module.exports.Row = __webpack_require__(49); /***/ }, /* 1 */ /***/ function(module, exports, __webpack_require__) { /** * @jsx React.DOM */ 'use strict'; var _extends = __webpack_require__(2)['default']; var _Object$assign = __webpack_require__(3)['default']; var React = __webpack_require__(18); var BaseGrid = __webpack_require__(19); var Row = __webpack_require__(49); var ExcelColumn = __webpack_require__(42); var KeyboardHandlerMixin = __webpack_require__(52); var CheckboxEditor = __webpack_require__(80); var FilterableHeaderCell = __webpack_require__(81); var cloneWithProps = __webpack_require__(30); var DOMMetrics = __webpack_require__(78); var ColumnMetricsMixin = __webpack_require__(82); var RowUtils = __webpack_require__(84); var ColumnUtils = __webpack_require__(25); if (!_Object$assign) { Object.assign = __webpack_require__(83); } var ReactDataGrid = React.createClass({ displayName: 'ReactDataGrid', mixins: [ColumnMetricsMixin, DOMMetrics.MetricsComputatorMixin, KeyboardHandlerMixin], propTypes: { rowHeight: React.PropTypes.number.isRequired, headerRowHeight: React.PropTypes.number, minHeight: React.PropTypes.number.isRequired, minWidth: React.PropTypes.number, enableRowSelect: React.PropTypes.bool, onRowUpdated: React.PropTypes.func, rowGetter: React.PropTypes.func.isRequired, rowsCount: React.PropTypes.number.isRequired, toolbar: React.PropTypes.element, enableCellSelect: React.PropTypes.bool, columns: React.PropTypes.oneOfType([React.PropTypes.object, React.PropTypes.array]).isRequired, onFilter: React.PropTypes.func, onCellCopyPaste: React.PropTypes.func, onCellsDragged: React.PropTypes.func, onAddFilter: React.PropTypes.func, onGridSort: React.PropTypes.func }, getDefaultProps: function getDefaultProps() { return { enableCellSelect: false, tabIndex: -1, rowHeight: 35, enableRowSelect: false, minHeight: 350 }; }, getInitialState: function getInitialState() { var columnMetrics = this.createColumnMetrics(); var initialState = { columnMetrics: columnMetrics, selectedRows: this.getInitialSelectedRows(), copied: null, expandedRows: [], canFilter: false, columnFilters: {}, sortDirection: null, sortColumn: null, dragged: null, scrollOffset: 0 }; if (this.props.enableCellSelect) { initialState.selected = { rowIdx: 0, idx: 0 }; } else { initialState.selected = { rowIdx: -1, idx: -1 }; } return initialState; }, componentWillReceiveProps: function componentWillReceiveProps(nextProps) { if (nextProps.rowsCount === this.props.rowsCount + 1) { this.onAfterAddRow(nextProps.rowsCount + 1); } }, onSelect: function onSelect(selected) { if (this.props.enableCellSelect) { if (this.state.selected.rowIdx !== selected.rowIdx || this.state.selected.idx !== selected.idx || this.state.selected.active === false) { var _idx = selected.idx; var _rowIdx = selected.rowIdx; if (_idx >= 0 && _rowIdx >= 0 && _idx < ColumnUtils.getSize(this.state.columnMetrics.columns) && _rowIdx < this.props.rowsCount) { this.setState({ selected: selected }); } } } }, onCellClick: function onCellClick(cell) { this.onSelect({ rowIdx: cell.rowIdx, idx: cell.idx }); }, onCellDoubleClick: function onCellDoubleClick(cell) { this.onSelect({ rowIdx: cell.rowIdx, idx: cell.idx }); this.setActive('Enter'); }, onViewportDoubleClick: function onViewportDoubleClick() { this.setActive(); }, onPressArrowUp: function onPressArrowUp(e) { this.moveSelectedCell(e, -1, 0); }, onPressArrowDown: function onPressArrowDown(e) { this.moveSelectedCell(e, 1, 0); }, onPressArrowLeft: function onPressArrowLeft(e) { this.moveSelectedCell(e, 0, -1); }, onPressArrowRight: function onPressArrowRight(e) { this.moveSelectedCell(e, 0, 1); }, onPressTab: function onPressTab(e) { this.moveSelectedCell(e, 0, e.shiftKey ? -1 : 1); }, onPressEnter: function onPressEnter(e) { this.setActive(e.key); }, onPressDelete: function onPressDelete(e) { this.setActive(e.key); }, onPressEscape: function onPressEscape(e) { this.setInactive(e.key); }, onPressBackspace: function onPressBackspace(e) { this.setActive(e.key); }, onPressChar: function onPressChar(e) { if (this.isKeyPrintable(e.keyCode)) { this.setActive(e.keyCode); } }, onPressKeyWithCtrl: function onPressKeyWithCtrl(e) { var keys = { KeyCode_c: 99, KeyCode_C: 67, KeyCode_V: 86, KeyCode_v: 118 }; var idx = this.state.selected.idx; if (this.canEdit(idx)) { if (e.keyCode === keys.KeyCode_c || e.keyCode === keys.KeyCode_C) { var _value = this.getSelectedValue(); this.handleCopy({ value: _value }); } else if (e.keyCode === keys.KeyCode_v || e.keyCode === keys.KeyCode_V) { this.handlePaste(); } } }, onCellCommit: function onCellCommit(commit) { var selected = _Object$assign({}, this.state.selected); selected.active = false; if (commit.key === 'Tab') { selected.idx += 1; } var expandedRows = this.state.expandedRows; // if(commit.changed && commit.changed.expandedHeight){ // expandedRows = this.expandRow(commit.rowIdx, commit.changed.expandedHeight); // } this.setState({ selected: selected, expandedRows: expandedRows }); this.props.onRowUpdated(commit); }, onDragStart: function onDragStart(e) { var value = this.getSelectedValue(); this.handleDragStart({ idx: this.state.selected.idx, rowIdx: this.state.selected.rowIdx, value: value }); // need to set dummy data for FF if (e && e.dataTransfer && e.dataTransfer.setData) e.dataTransfer.setData('text/plain', 'dummy'); }, onAfterAddRow: function onAfterAddRow(numberOfRows) { this.setState({ selected: { idx: 1, rowIdx: numberOfRows - 2 } }); }, onToggleFilter: function onToggleFilter() { this.setState({ canFilter: !this.state.canFilter }); }, handleDragStart: function handleDragStart(dragged) { if (!this.dragEnabled()) { return; } var idx = dragged.idx; var rowIdx = dragged.rowIdx; if (idx >= 0 && rowIdx >= 0 && idx < this.getSize() && rowIdx < this.props.rowsCount) { this.setState({ dragged: dragged }); } }, handleDragEnd: function handleDragEnd() { if (!this.dragEnabled()) { return; } var fromRow = undefined; var toRow = undefined; var selected = this.state.selected; var dragged = this.state.dragged; var cellKey = this.getColumn(this.state.selected.idx).key; fromRow = selected.rowIdx < dragged.overRowIdx ? selected.rowIdx : dragged.overRowIdx; toRow = selected.rowIdx > dragged.overRowIdx ? selected.rowIdx : dragged.overRowIdx; if (this.props.onCellsDragged) { this.props.onCellsDragged({ cellKey: cellKey, fromRow: fromRow, toRow: toRow, value: dragged.value }); } this.setState({ dragged: { complete: true } }); }, handleDragEnter: function handleDragEnter(row) { if (!this.dragEnabled()) { return; } var dragged = this.state.dragged; dragged.overRowIdx = row; this.setState({ dragged: dragged }); }, handleTerminateDrag: function handleTerminateDrag() { if (!this.dragEnabled()) { return; } this.setState({ dragged: null }); }, handlePaste: function handlePaste() { if (!this.copyPasteEnabled()) { return; } var selected = this.state.selected; var cellKey = this.getColumn(this.state.selected.idx).key; if (this.props.onCellCopyPaste) { this.props.onCellCopyPaste({ cellKey: cellKey, rowIdx: selected.rowIdx, value: this.state.textToCopy, fromRow: this.state.copied.rowIdx, toRow: selected.rowIdx }); } this.setState({ copied: null }); }, handleCopy: function handleCopy(args) { if (!this.copyPasteEnabled()) { return; } var textToCopy = args.value; var selected = this.state.selected; var copied = { idx: selected.idx, rowIdx: selected.rowIdx }; this.setState({ textToCopy: textToCopy, copied: copied }); }, handleSort: function handleSort(columnKey, direction) { this.setState({ sortDirection: direction, sortColumn: columnKey }, function () { this.props.onGridSort(columnKey, direction); }); }, // columnKey not used here as this function will select the whole row, // but needed to match the function signature in the CheckboxEditor handleRowSelect: function handleRowSelect(rowIdx, columnKey, e) { e.stopPropagation(); if (this.state.selectedRows !== null && this.state.selectedRows.length > 0) { var _selectedRows = this.state.selectedRows.slice(); if (_selectedRows[rowIdx] === null || _selectedRows[rowIdx] === false) { _selectedRows[rowIdx] = true; } else { _selectedRows[rowIdx] = false; } this.setState({ selectedRows: _selectedRows }); } }, handleCheckboxChange: function handleCheckboxChange(e) { var allRowsSelected = undefined; if (e.currentTarget instanceof HTMLInputElement && e.currentTarget.checked === true) { allRowsSelected = true; } else { allRowsSelected = false; } var selectedRows = []; for (var i = 0; i < this.props.rowsCount; i++) { selectedRows.push(allRowsSelected); } this.setState({ selectedRows: selectedRows }); }, getScrollOffSet: function getScrollOffSet() { var scrollOffset = 0; var canvas = this.getDOMNode().querySelector('.react-grid-Canvas'); if (canvas) { scrollOffset = canvas.offsetWidth - canvas.clientWidth; } this.setState({ scrollOffset: scrollOffset }); }, getRowOffsetHeight: function getRowOffsetHeight() { var offsetHeight = 0; this.getHeaderRows().forEach(function (row) { return offsetHeight += parseFloat(row.height, 10); }); return offsetHeight; }, getHeaderRows: function getHeaderRows() { var rows = [{ ref: 'row', height: this.props.headerRowHeight || this.props.rowHeight }]; if (this.state.canFilter === true) { rows.push({ ref: 'filterRow', headerCellRenderer: React.createElement(FilterableHeaderCell, { onChange: this.props.onAddFilter }), height: 45 }); } return rows; }, getInitialSelectedRows: function getInitialSelectedRows() { var selectedRows = []; for (var i = 0; i < this.props.rowsCount; i++) { selectedRows.push(false); } return selectedRows; }, getSelectedValue: function getSelectedValue() { var rowIdx = this.state.selected.rowIdx; var idx = this.state.selected.idx; var cellKey = this.getColumn(idx).key; var row = this.props.rowGetter(rowIdx); return RowUtils.get(row, cellKey); }, moveSelectedCell: function moveSelectedCell(e, rowDelta, cellDelta) { // we need to prevent default as we control grid scroll // otherwise it moves every time you left/right which is janky e.preventDefault(); var rowIdx = this.state.selected.rowIdx + rowDelta; var idx = this.state.selected.idx + cellDelta; this.onSelect({ idx: idx, rowIdx: rowIdx }); }, setActive: function setActive(keyPressed) { var rowIdx = this.state.selected.rowIdx; var idx = this.state.selected.idx; if (this.canEdit(idx) && !this.isActive()) { var _selected = _Object$assign(this.state.selected, { idx: idx, rowIdx: rowIdx, active: true, initialKeyCode: keyPressed }); this.setState({ selected: _selected }); } }, setInactive: function setInactive() { var rowIdx = this.state.selected.rowIdx; var idx = this.state.selected.idx; if (this.canEdit(idx) && this.isActive()) { var _selected2 = _Object$assign(this.state.selected, { idx: idx, rowIdx: rowIdx, active: false }); this.setState({ selected: _selected2 }); } }, canEdit: function canEdit(idx) { var col = this.getColumn(idx); return this.props.enableCellSelect === true && (col.editor != null || col.editable); }, isActive: function isActive() { return this.state.selected.active === true; }, setupGridColumns: function setupGridColumns() { var props = arguments.length <= 0 || arguments[0] === undefined ? this.props : arguments[0]; var cols = props.columns.slice(0); var unshiftedCols = {}; if (props.enableRowSelect) { var selectColumn = { key: 'select-row', name: '', formatter: React.createElement(CheckboxEditor, null), onCellChange: this.handleRowSelect, filterable: false, headerRenderer: React.createElement('input', { type: 'checkbox', onChange: this.handleCheckboxChange }), width: 60, locked: true }; unshiftedCols = cols.unshift(selectColumn); cols = unshiftedCols > 0 ? cols : unshiftedCols; } return cols; }, copyPasteEnabled: function copyPasteEnabled() { return this.props.onCellCopyPaste !== null; }, dragEnabled: function dragEnabled() { return this.props.onCellsDragged !== null; }, renderToolbar: function renderToolbar() { var Toolbar = this.props.toolbar; if (React.isValidElement(Toolbar)) { return cloneWithProps(Toolbar, { onToggleFilter: this.onToggleFilter, numberOfRows: this.props.rowsCount }); } }, render: function render() { var cellMetaData = { selected: this.state.selected, dragged: this.state.dragged, onCellClick: this.onCellClick, onCellDoubleClick: this.onCellDoubleClick, onCommit: this.onCellCommit, onCommitCancel: this.setInactive, copied: this.state.copied, handleDragEnterRow: this.handleDragEnter, handleTerminateDrag: this.handleTerminateDrag }; var toolbar = this.renderToolbar(); var containerWidth = this.props.minWidth || this.DOMMetrics.gridWidth(); var gridWidth = containerWidth - this.state.scrollOffset; return React.createElement( 'div', { className: 'react-grid-Container', style: { width: containerWidth } }, toolbar, React.createElement( 'div', { className: 'react-grid-Main' }, React.createElement(BaseGrid, _extends({ ref: 'base' }, this.props, { headerRows: this.getHeaderRows(), columnMetrics: this.state.columnMetrics, rowGetter: this.props.rowGetter, rowsCount: this.props.rowsCount, rowHeight: this.props.rowHeight, cellMetaData: cellMetaData, selectedRows: this.state.selectedRows, expandedRows: this.state.expandedRows, rowOffsetHeight: this.getRowOffsetHeight(), sortColumn: this.state.sortColumn, sortDirection: this.state.sortDirection, onSort: this.handleSort, minHeight: this.props.minHeight, totalWidth: gridWidth, onViewportKeydown: this.onKeyDown, onViewportDragStart: this.onDragStart, onViewportDragEnd: this.handleDragEnd, onViewportDoubleClick: this.onViewportDoubleClick, onColumnResize: this.onColumnResize })) ) ); } }); module.exports = ReactDataGrid; /***/ }, /* 2 */ /***/ function(module, exports, __webpack_require__) { "use strict"; var _Object$assign = __webpack_require__(3)["default"]; exports["default"] = _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; }; exports.__esModule = true; /***/ }, /* 3 */ /***/ function(module, exports, __webpack_require__) { module.exports = { "default": __webpack_require__(4), __esModule: true }; /***/ }, /* 4 */ /***/ function(module, exports, __webpack_require__) { __webpack_require__(5); module.exports = __webpack_require__(8).Object.assign; /***/ }, /* 5 */ /***/ function(module, exports, __webpack_require__) { // 19.1.3.1 Object.assign(target, source) var $export = __webpack_require__(6); $export($export.S + $export.F, 'Object', {assign: __webpack_require__(11)}); /***/ }, /* 6 */ /***/ function(module, exports, __webpack_require__) { var global = __webpack_require__(7) , core = __webpack_require__(8) , ctx = __webpack_require__(9) , 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] = {}) , 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 && key in target; 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(param){ return this instanceof C ? new C(param) : C(param); }; F[PROTOTYPE] = C[PROTOTYPE]; return F; // make static versions for prototype methods })(out) : IS_PROTO && typeof out == 'function' ? ctx(Function.call, out) : out; if(IS_PROTO)(exports[PROTOTYPE] || (exports[PROTOTYPE] = {}))[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 module.exports = $export; /***/ }, /* 7 */ /***/ 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 /***/ }, /* 8 */ /***/ function(module, exports) { var core = module.exports = {version: '1.2.6'}; if(typeof __e == 'number')__e = core; // eslint-disable-line no-undef /***/ }, /* 9 */ /***/ function(module, exports, __webpack_require__) { // optional / simple context binding var aFunction = __webpack_require__(10); 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); }; }; /***/ }, /* 10 */ /***/ function(module, exports) { module.exports = function(it){ if(typeof it != 'function')throw TypeError(it + ' is not a function!'); return it; }; /***/ }, /* 11 */ /***/ function(module, exports, __webpack_require__) { // 19.1.2.1 Object.assign(target, source, ...) var $ = __webpack_require__(12) , toObject = __webpack_require__(13) , IObject = __webpack_require__(15); // should work with symbols and should have deterministic property order (V8 bug) module.exports = __webpack_require__(17)(function(){ var a = Object.assign , A = {} , B = {} , S = Symbol() , K = 'abcdefghijklmnopqrst'; A[S] = 7; K.split('').forEach(function(k){ B[k] = k; }); return a({}, A)[S] != 7 || Object.keys(a({}, B)).join('') != K; }) ? function assign(target, source){ // eslint-disable-line no-unused-vars var T = toObject(target) , $$ = arguments , $$len = $$.length , index = 1 , getKeys = $.getKeys , getSymbols = $.getSymbols , isEnum = $.isEnum; while($$len > index){ var S = IObject($$[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; } : Object.assign; /***/ }, /* 12 */ /***/ function(module, exports) { var $Object = Object; module.exports = { create: $Object.create, getProto: $Object.getPrototypeOf, isEnum: {}.propertyIsEnumerable, getDesc: $Object.getOwnPropertyDescriptor, setDesc: $Object.defineProperty, setDescs: $Object.defineProperties, getKeys: $Object.keys, getNames: $Object.getOwnPropertyNames, getSymbols: $Object.getOwnPropertySymbols, each: [].forEach }; /***/ }, /* 13 */ /***/ function(module, exports, __webpack_require__) { // 7.1.13 ToObject(argument) var defined = __webpack_require__(14); module.exports = function(it){ return Object(defined(it)); }; /***/ }, /* 14 */ /***/ 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; }; /***/ }, /* 15 */ /***/ function(module, exports, __webpack_require__) { // fallback for non-array-like ES3 and non-enumerable old V8 strings var cof = __webpack_require__(16); module.exports = Object('z').propertyIsEnumerable(0) ? Object : function(it){ return cof(it) == 'String' ? it.split('') : Object(it); }; /***/ }, /* 16 */ /***/ function(module, exports) { var toString = {}.toString; module.exports = function(it){ return toString.call(it).slice(8, -1); }; /***/ }, /* 17 */ /***/ function(module, exports) { module.exports = function(exec){ try { return !!exec(); } catch(e){ return true; } }; /***/ }, /* 18 */ /***/ function(module, exports) { module.exports = __WEBPACK_EXTERNAL_MODULE_18__; /***/ }, /* 19 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _extends = __webpack_require__(2)['default']; var React = __webpack_require__(18); var PropTypes = React.PropTypes; var Header = __webpack_require__(20); var Viewport = __webpack_require__(46); var GridScrollMixin = __webpack_require__(79); var DOMMetrics = __webpack_require__(78); var cellMetaDataShape = __webpack_require__(75); var Grid = React.createClass({ displayName: 'Grid', propTypes: { rowGetter: PropTypes.oneOfType([PropTypes.array, PropTypes.func]).isRequired, columns: PropTypes.oneOfType([PropTypes.array, PropTypes.object]), columnMetrics: PropTypes.shape, minHeight: PropTypes.number, totalWidth: PropTypes.number, headerRows: PropTypes.oneOfType([PropTypes.array, PropTypes.func]), rowHeight: PropTypes.number, rowRenderer: PropTypes.func, emptyRowsView: PropTypes.func, expandedRows: PropTypes.oneOfType([PropTypes.array, PropTypes.func]), selectedRows: PropTypes.oneOfType([PropTypes.array, PropTypes.func]), rowsCount: PropTypes.number, onRows: PropTypes.func, sortColumn: React.PropTypes.string, sortDirection: React.PropTypes.oneOf(['ASC', 'DESC', 'NONE']), rowOffsetHeight: PropTypes.number.isRequired, onViewportKeydown: PropTypes.func.isRequired, onViewportDragStart: PropTypes.func.isRequired, onViewportDragEnd: PropTypes.func.isRequired, onViewportDoubleClick: PropTypes.func.isRequired, onColumnResize: PropTypes.func, onSort: PropTypes.func, cellMetaData: PropTypes.shape(cellMetaDataShape) }, mixins: [GridScrollMixin, DOMMetrics.MetricsComputatorMixin], getDefaultProps: function getDefaultProps() { return { rowHeight: 35, minHeight: 350 }; }, getStyle: function getStyle() { return { overflow: 'hidden', outline: 0, position: 'relative', minHeight: this.props.minHeight }; }, render: function render() { var headerRows = this.props.headerRows || [{ ref: 'row' }]; var EmptyRowsView = this.props.emptyRowsView; return React.createElement( 'div', _extends({}, this.props, { style: this.getStyle(), className: 'react-grid-Grid' }), React.createElement(Header, { ref: 'header', columnMetrics: this.props.columnMetrics, onColumnResize: this.props.onColumnResize, height: this.props.rowHeight, totalWidth: this.props.totalWidth, headerRows: headerRows, sortColumn: this.props.sortColumn, sortDirection: this.props.sortDirection, onSort: this.props.onSort }), this.props.rowsCount >= 1 || this.props.rowsCount === 0 && !this.props.emptyRowsView ? React.createElement( 'div', { ref: 'viewPortContainer', onKeyDown: this.props.onViewportKeydown, onDoubleClick: this.props.onViewportDoubleClick, onDragStart: this.props.onViewportDragStart, onDragEnd: this.props.onViewportDragEnd }, React.createElement(Viewport, { ref: 'viewport', width: this.props.columnMetrics.width, rowHeight: this.props.rowHeight, rowRenderer: this.props.rowRenderer, rowGetter: this.props.rowGetter, rowsCount: this.props.rowsCount, selectedRows: this.props.selectedRows, expandedRows: this.props.expandedRows, columnMetrics: this.props.columnMetrics, totalWidth: this.props.totalWidth, onScroll: this.onScroll, onRows: this.props.onRows, cellMetaData: this.props.cellMetaData, rowOffsetHeight: this.props.rowOffsetHeight || this.props.rowHeight * headerRows.length, minHeight: this.props.minHeight }) ) : React.createElement( 'div', { ref: 'emptyView', className: 'react-grid-Empty' }, React.createElement(EmptyRowsView, null) ) ); } }); module.exports = Grid; /***/ }, /* 20 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _extends = __webpack_require__(2)['default']; var React = __webpack_require__(18); var joinClasses = __webpack_require__(21); var shallowCloneObject = __webpack_require__(22); var ColumnMetrics = __webpack_require__(23); var ColumnUtils = __webpack_require__(25); var HeaderRow = __webpack_require__(27); var PropTypes = React.PropTypes; var Header = React.createClass({ displayName: 'Header', propTypes: { columnMetrics: PropTypes.shape({ width: PropTypes.number.isRequired, columns: PropTypes.any }).isRequired, totalWidth: PropTypes.number, height: PropTypes.number.isRequired, headerRows: PropTypes.array.isRequired, sortColumn: PropTypes.string, sortDirection: PropTypes.oneOf(['ASC', 'DESC', 'NONE']), onSort: PropTypes.func, onColumnResize: PropTypes.func }, getInitialState: function getInitialState() { return { resizing: null }; }, componentWillReceiveProps: function componentWillReceiveProps() { this.setState({ resizing: null }); }, shouldComponentUpdate: function shouldComponentUpdate(nextProps, nextState) { var update = !ColumnMetrics.sameColumns(this.props.columnMetrics.columns, nextProps.columnMetrics.columns, ColumnMetrics.sameColumn) || this.props.totalWidth !== nextProps.totalWidth || this.props.headerRows.length !== nextProps.headerRows.length || this.state.resizing !== nextState.resizing || this.props.sortColumn !== nextProps.sortColumn || this.props.sortDirection !== nextProps.sortDirection; return update; }, onColumnResize: function onColumnResize(column, width) { var state = this.state.resizing || this.props; var pos = this.getColumnPosition(column); if (pos != null) { var _resizing = { columnMetrics: shallowCloneObject(state.columnMetrics) }; _resizing.columnMetrics = ColumnMetrics.resizeColumn(_resizing.columnMetrics, pos, width); // we don't want to influence scrollLeft while resizing if (_resizing.columnMetrics.totalWidth < state.columnMetrics.totalWidth) { _resizing.columnMetrics.totalWidth = state.columnMetrics.totalWidth; } _resizing.column = ColumnUtils.getColumn(_resizing.columnMetrics.columns, pos); this.setState({ resizing: _resizing }); } }, onColumnResizeEnd: function onColumnResizeEnd(column, width) { var pos = this.getColumnPosition(column); if (pos !== null && this.props.onColumnResize) { this.props.onColumnResize(pos, width || column.width); } }, getHeaderRows: function getHeaderRows() { var _this = this; var columnMetrics = this.getColumnMetrics(); var resizeColumn = undefined; if (this.state.resizing) { resizeColumn = this.state.resizing.column; } var headerRows = []; this.props.headerRows.forEach(function (row, index) { var headerRowStyle = { position: 'absolute', top: _this.getCombinedHeaderHeights(index), left: 0, width: _this.props.totalWidth, overflow: 'hidden' }; headerRows.push(React.createElement(HeaderRow, { key: row.ref, ref: row.ref, style: headerRowStyle, onColumnResize: _this.onColumnResize, onColumnResizeEnd: _this.onColumnResizeEnd, width: columnMetrics.width, height: row.height || _this.props.height, columns: columnMetrics.columns, resizing: resizeColumn, headerCellRenderer: row.headerCellRenderer, sortColumn: _this.props.sortColumn, sortDirection: _this.props.sortDirection, onSort: _this.props.onSort })); }); return headerRows; }, getColumnMetrics: function getColumnMetrics() { var columnMetrics = undefined; if (this.state.resizing) { columnMetrics = this.state.resizing.columnMetrics; } else { columnMetrics = this.props.columnMetrics; } return columnMetrics; }, getColumnPosition: function getColumnPosition(column) { var columnMetrics = this.getColumnMetrics(); var pos = -1; columnMetrics.columns.forEach(function (c, idx) { if (c.key === column.key) { pos = idx; } }); return pos === -1 ? null : pos; }, getCombinedHeaderHeights: function getCombinedHeaderHeights(until) { var stopAt = this.props.headerRows.length; if (typeof until !== 'undefined') { stopAt = until; } var height = 0; for (var index = 0; index < stopAt; index++) { height += this.props.headerRows[index].height || this.props.height; } return height; }, getStyle: function getStyle() { return { position: 'relative', height: this.getCombinedHeaderHeights(), overflow: 'hidden' }; }, setScrollLeft: function setScrollLeft(scrollLeft) { var node = this.refs.row.getDOMNode(); node.scrollLeft = scrollLeft; this.refs.row.setScrollLeft(scrollLeft); if (this.refs.filterRow) { var nodeFilters = this.refs.filterRow.getDOMNode(); nodeFilters.scrollLeft = scrollLeft; this.refs.filterRow.setScrollLeft(scrollLeft); } }, render: function render() { var className = joinClasses({ 'react-grid-Header': true, 'react-grid-Header--resizing': !!this.state.resizing }); var headerRows = this.getHeaderRows(); return React.createElement( 'div', _extends({}, this.props, { style: this.getStyle(), className: className }), headerRows ); } }); module.exports = Header; /***/ }, /* 21 */ /***/ function(module, exports, __webpack_require__) { var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/*! Copyright (c) 2015 Jed Watson. Licensed under the MIT License (MIT), see http://jedwatson.github.io/classnames */ function classNames() { var classes = ''; var arg; for (var i = 0; i < arguments.length; i++) { arg = arguments[i]; if (!arg) { continue; } if ('string' === typeof arg || 'number' === typeof arg) { classes += ' ' + arg; } else if (Object.prototype.toString.call(arg) === '[object Array]') { classes += ' ' + classNames.apply(null, arg); } else if ('object' === typeof arg) { for (var key in arg) { if (!arg.hasOwnProperty(key) || !arg[key]) { continue; } classes += ' ' + key; } } } return classes.substr(1); } // safely export classNames for node / browserify if (typeof module !== 'undefined' && module.exports) { module.exports = classNames; } // safely export classNames for RequireJS if (true) { !(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_RESULT__ = function() { return classNames; }.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); } /***/ }, /* 22 */ /***/ function(module, exports) { "use strict"; function shallowCloneObject(obj) { var result = {}; for (var k in obj) { if (obj.hasOwnProperty(k)) { result[k] = obj[k]; } } return result; } module.exports = shallowCloneObject; /***/ }, /* 23 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _Object$assign = __webpack_require__(3)['default']; var shallowCloneObject = __webpack_require__(22); var sameColumn = __webpack_require__(24); var ColumnUtils = __webpack_require__(25); var getScrollbarSize = __webpack_require__(26); function setColumnWidths(columns, totalWidth) { return columns.map(function (column) { var colInfo = _Object$assign({}, column); if (column.width) { if (/^([0-9]+)%$/.exec(column.width.toString())) { colInfo.width = Math.floor(column.width / 100 * totalWidth); } } return colInfo; }); } function setDefferedColumnWidths(columns, unallocatedWidth, minColumnWidth) { var defferedColumns = columns.filter(function (c) { return !c.width; }); return columns.map(function (column) { if (!column.width) { if (unallocatedWidth <= 0) { column.width = minColumnWidth; } else { column.width = Math.floor(unallocatedWidth / ColumnUtils.getSize(defferedColumns)); } } return column; }); } function setColumnOffsets(columns) { var left = 0; return columns.map(function (column) { column.left = left; left += column.width; return column; }); } /** * Update column metrics calculation. * * @param {ColumnMetricsType} metrics */ function recalculate(metrics) { // compute width for columns which specify width var columns = setColumnWidths(metrics.columns, metrics.totalWidth); var unallocatedWidth = columns.filter(function (c) { return c.width; }).reduce(function (w, column) { return w - column.width; }, metrics.totalWidth); unallocatedWidth -= getScrollbarSize(); var width = columns.filter(function (c) { return c.width; }).reduce(function (w, column) { return w + column.width; }, 0); // compute width for columns which doesn't specify width columns = setDefferedColumnWidths(columns, unallocatedWidth, metrics.minColumnWidth); // compute left offset columns = setColumnOffsets(columns); return { columns: columns, width: width, totalWidth: metrics.totalWidth, minColumnWidth: metrics.minColumnWidth }; } /** * Update column metrics calculation by resizing a column. * * @param {ColumnMetricsType} metrics * @param {Column} column * @param {number} width */ function resizeColumn(metrics, index, width) { var column = ColumnUtils.getColumn(metrics.columns, index); var metricsClone = shallowCloneObject(metrics); metricsClone.columns = metrics.columns.slice(0); var updatedColumn = shallowCloneObject(column); updatedColumn.width = Math.max(width, metricsClone.minColumnWidth); metricsClone = ColumnUtils.spliceColumn(metricsClone, index, updatedColumn); return recalculate(metricsClone); } function areColumnsImmutable(prevColumns, nextColumns) { return typeof Immutable !== 'undefined' && prevColumns instanceof Immutable.List && nextColumns instanceof Immutable.List; } function compareEachColumn(prevColumns, nextColumns, isSameColumn) { var i = undefined; var len = undefined; var column = undefined; var prevColumnsByKey = {}; var nextColumnsByKey = {}; if (ColumnUtils.getSize(prevColumns) !== ColumnUtils.getSize(nextColumns)) { return false; } for (i = 0, len = ColumnUtils.getSize(prevColumns); i < len; i++) { column = prevColumns[i]; prevColumnsByKey[column.key] = column; } for (i = 0, len = ColumnUtils.getSize(nextColumns); i < len; i++) { column = nextColumns[i]; nextColumnsByKey[column.key] = column; var prevColumn = prevColumnsByKey[column.key]; if (prevColumn === undefined || !isSameColumn(prevColumn, column)) { return false; } } for (i = 0, len = ColumnUtils.getSize(prevColumns); i < len; i++) { column = prevColumns[i]; var nextColumn = nextColumnsByKey[column.key]; if (nextColumn === undefined) { return false; } } return true; } function sameColumns(prevColumns, nextColumns, isSameColumn) { if (areColumnsImmutable(prevColumns, nextColumns)) { return prevColumns === nextColumns; } return compareEachColumn(prevColumns, nextColumns, isSameColumn); } module.exports = { recalculate: recalculate, resizeColumn: resizeColumn, sameColumn: sameColumn, sameColumns: sameColumns }; /***/ }, /* 24 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var isValidElement = __webpack_require__(18).isValidElement; module.exports = function sameColumn(a, b) { var k = undefined; for (k in a) { if (a.hasOwnProperty(k)) { if (typeof a[k] === 'function' && typeof b[k] === 'function' || isValidElement(a[k]) && isValidElement(b[k])) { continue; } if (!b.hasOwnProperty(k) || a[k] !== b[k]) { return false; } } } for (k in b) { if (b.hasOwnProperty(k) && !a.hasOwnProperty(k)) { return false; } } return true; }; /***/ }, /* 25 */ /***/ function(module, exports) { 'use strict'; module.exports = { getColumn: function getColumn(columns, idx) { if (Array.isArray(columns)) { return columns[idx]; } else if (typeof Immutable !== 'undefined') { return columns.get(idx); } }, spliceColumn: function spliceColumn(metrics, idx, column) { if (Array.isArray(metrics.columns)) { metrics.columns.splice(idx, 1, column); } else if (typeof Immutable !== 'undefined') { metrics.columns = metrics.columns.splice(idx, 1, column); } return metrics; }, getSize: function getSize(columns) { if (Array.isArray(columns)) { return columns.length; } else if (typeof Immutable !== 'undefined') { return columns.size; } } }; /***/ }, /* 26 */ /***/ function(module, exports) { 'use strict'; var size = undefined; function getScrollbarSize() { if (size === undefined) { var outer = document.createElement('div'); outer.style.width = '50px'; outer.style.height = '50px'; outer.style.position = 'absolute'; outer.style.top = '-200px'; outer.style.left = '-200px'; var inner = document.createElement('div'); inner.style.height = '100px'; inner.style.width = '100%'; outer.appendChild(inner); document.body.appendChild(outer); var _outerWidth = outer.clientWidth; outer.style.overflowY = 'scroll'; var _innerWidth = inner.clientWidth; document.body.removeChild(outer); size = _outerWidth - _innerWidth; } return size; } module.exports = getScrollbarSize; /***/ }, /* 27 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _extends = __webpack_require__(2)['default']; var React = __webpack_require__(18); var shallowEqual = __webpack_require__(28); var HeaderCell = __webpack_require__(29); var getScrollbarSize = __webpack_require__(26); var ExcelColumn = __webpack_require__(42); var ColumnUtilsMixin = __webpack_require__(25); var SortableHeaderCell = __webpack_require__(45); var PropTypes = React.PropTypes; var HeaderRowStyle = { overflow: React.PropTypes.string, width: PropTypes.oneOfType([PropTypes.number, PropTypes.string]), height: React.PropTypes.number, position: React.PropTypes.string }; var DEFINE_SORT = ['ASC', 'DESC', 'NONE']; var HeaderRow = React.createClass({ displayName: 'HeaderRow', propTypes: { width: PropTypes.oneOfType([PropTypes.number, PropTypes.string]), height: PropTypes.number.isRequired, columns: PropTypes.oneOfType([PropTypes.array, PropTypes.object]), onColumnResize: PropTypes.func, onSort: PropTypes.func.isRequired, onColumnResizeEnd: PropTypes.func, style: PropTypes.shape(HeaderRowStyle), sortColumn: PropTypes.string, sortDirection: React.PropTypes.oneOf(DEFINE_SORT), cellRenderer: PropTypes.func, headerCellRenderer: PropTypes.func, resizing: PropTypes.func }, mixins: [ColumnUtilsMixin], shouldComponentUpdate: function shouldComponentUpdate(nextProps) { return nextProps.width !== this.props.width || nextProps.height !== this.props.height || nextProps.columns !== this.props.columns || !shallowEqual(nextProps.style, this.props.style) || this.props.sortColumn !== nextProps.sortColumn || this.props.sortDirection !== nextProps.sortDirection; }, getHeaderRenderer: function getHeaderRenderer(column) { if (column.sortable) { var sortDirection = this.props.sortColumn === column.key ? this.props.sortDirection : DEFINE_SORT.NONE; return React.createElement(SortableHeaderCell, { columnKey: column.key, onSort: this.props.onSort, sortDirection: sortDirection }); } return this.props.headerCellRenderer || column.headerRenderer || this.props.cellRenderer; }, getStyle: function getStyle() { return { overflow: 'hidden', width: '100%', height: this.props.height, position: 'absolute' }; }, getCells: function getCells() { var cells = []; var lockedCells = []; for (var i = 0, len = this.getSize(this.props.columns); i < len; i++) { var column = this.getColumn(this.props.columns, i); var cell = React.createElement(HeaderCell, { ref: i, key: i, height: this.props.height, column: column, renderer: this.getHeaderRenderer(column), resizing: this.props.resizing === column, onResize: this.props.onColumnResize, onResizeEnd: this.props.onColumnResizeEnd }); if (column.locked) { lockedCells.push(cell); } else { cells.push(cell); } } return cells.concat(lockedCells); }, setScrollLeft: function setScrollLeft(scrollLeft) { var _this = this; this.props.columns.forEach(function (column, i) { if (column.locked) { _this.refs[i].setScrollLeft(scrollLeft); } }); }, render: function render() { var cellsStyle = { width: this.props.width ? this.props.width + getScrollbarSize() : '100%', height: this.props.height, whiteSpace: 'nowrap', overflowX: 'hidden', overflowY: 'hidden' }; var cells = this.getCells(); return React.createElement( 'div', _extends({}, this.props, { className: 'react-grid-HeaderRow' }), React.createElement( 'div', { style: cellsStyle }, cells ) ); } }); module.exports = HeaderRow; /***/ }, /* 28 */ /***/ function(module, exports) { /** * 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. * * @providesModule shallowEqual */ 'use strict'; /** * Performs equality by iterating through keys on an object and returning * false when any key has values which are not strictly equal between * objA and objB. Returns true when the values of all keys are strictly equal. * * @return {boolean} */ function shallowEqual(objA, objB) { if (objA === objB) { return true; } var key; // Test for A's keys different from B. for (key in objA) { if (objA.hasOwnProperty(key) && (!objB.hasOwnProperty(key) || objA[key] !== objB[key])) { return false; } } // Test for B's keys missing from A. for (key in objB) { if (objB.hasOwnProperty(key) && !objA.hasOwnProperty(key)) { return false; } } return true; } module.exports = shallowEqual; /***/ }, /* 29 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var React = __webpack_require__(18); var joinClasses = __webpack_require__(21); var cloneWithProps = __webpack_require__(30); var ExcelColumn = __webpack_require__(42); var ResizeHandle = __webpack_require__(43); var PropTypes = React.PropTypes; function simpleCellRenderer(objArgs) { return React.createElement( 'div', { className: 'widget-HeaderCell__value' }, objArgs.column.name ); } var HeaderCell = React.createClass({ displayName: 'HeaderCell', propTypes: { renderer: PropTypes.oneOfType([PropTypes.func, PropTypes.element]).isRequired, column: PropTypes.shape(ExcelColumn).isRequired, onResize: PropTypes.func.isRequired, height: PropTypes.number.isRequired, onResizeEnd: PropTypes.func.isRequired, className: PropTypes.string }, getDefaultProps: function getDefaultProps() { return { renderer: simpleCellRenderer }; }, getInitialState: function getInitialState() { return { resizing: false }; }, onDragStart: function onDragStart(e) { this.setState({ resizing: true }); // need to set dummy data for FF if (e && e.dataTransfer && e.dataTransfer.setData) e.dataTransfer.setData('text/plain', 'dummy'); }, onDrag: function onDrag(e) { var resize = this.props.onResize || null; // for flows sake, doesnt recognise a null check direct if (resize) { var _width = this.getWidthFromMouseEvent(e); if (_width > 0) { resize(this.props.column, _width); } } }, onDragEnd: function onDragEnd(e) { var width = this.getWidthFromMouseEvent(e); this.props.onResizeEnd(this.props.column, width); this.setState({ resizing: false }); }, getWidthFromMouseEvent: function getWidthFromMouseEvent(e) { var right = e.pageX; var left = React.findDOMNode(this).getBoundingClientRect().left; return right - left; }, getCell: function getCell() { if (React.isValidElement(this.props.renderer)) { return cloneWithProps(this.props.renderer, { column: this.props.column }); } return this.props.renderer({ column: this.props.column }); }, getStyle: function getStyle() { return { width: this.props.column.width, left: this.props.column.left, display: 'inline-block', position: 'absolute', overflow: 'hidden', height: this.props.height, margin: 0, textOverflow: 'ellipsis', whiteSpace: 'nowrap' }; }, setScrollLeft: function setScrollLeft(scrollLeft) { var node = React.findDOMNode(this); node.style.webkitTransform = 'translate3d(' + scrollLeft + 'px, 0px, 0px)'; node.style.transform = 'translate3d(' + scrollLeft + 'px, 0px, 0px)'; }, render: function render() { var resizeHandle = undefined; if (this.props.column.resizable) { resizeHandle = React.createElement(ResizeHandle, { onDrag: this.onDrag, onDragStart: this.onDragStart, onDragEnd: this.onDragEnd }); } var className = joinClasses({ 'react-grid-HeaderCell': true, 'react-grid-HeaderCell--resizing': this.state.resizing, 'react-grid-HeaderCell--locked': this.props.column.locked }); className = joinClasses(className, this.props.className, this.props.column.cellClass); var cell = this.getCell(); return React.createElement( 'div', { className: className, style: this.getStyle() }, cell, resizeHandle ); } }); module.exports = HeaderCell; /***/ }, /* 30 */ /***/ 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. * * @typechecks static-only * @providesModule cloneWithProps */ 'use strict'; var ReactElement = __webpack_require__(32); var ReactPropTransferer = __webpack_require__(39); var keyOf = __webpack_require__(41); var warning = __webpack_require__(36); var CHILDREN_PROP = keyOf({children: null}); /** * Sometimes you want to change the props of a child passed to you. Usually * this is to add a CSS class. * * @param {ReactElement} child child element you'd like to clone * @param {object} props props you'd like to modify. className and style will be * merged automatically. * @return {ReactElement} a clone of child with props merged in. */ function cloneWithProps(child, props) { if ("production" !== process.env.NODE_ENV) { ("production" !== process.env.NODE_ENV ? warning( !child.ref, 'You are calling cloneWithProps() on a child with a ref. This is ' + 'dangerous because you\'re creating a new child which will not be ' + 'added as a ref to its parent.' ) : null); } var newProps = ReactPropTransferer.mergeProps(props, child.props); // Use `child.props.children` if it is provided. if (!newProps.hasOwnProperty(CHILDREN_PROP) && child.props.hasOwnProperty(CHILDREN_PROP)) { newProps.children = child.props.children; } // The current API doesn't retain _owner and _context, which is why this // doesn't use ReactElement.cloneAndReplaceProps. return ReactElement.createElement(child.type, newProps); } module.exports = cloneWithProps; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(31))) /***/ }, /* 31 */ /***/ 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() { 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; }; /***/ }, /* 32 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2014-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. * * @providesModule ReactElement */ 'use strict'; var ReactContext = __webpack_require__(33); var ReactCurrentOwner = __webpack_require__(38); var assign = __webpack_require__(34); var warning = __webpack_require__(36); var RESERVED_PROPS = { key: true, ref: true }; /** * Warn for mutations. * * @internal * @param {object} object * @param {string} key */ function defineWarningProperty(object, key) { Object.defineProperty(object, key, { configurable: false, enumerable: true, get: function() { if (!this._store) { return null; } return this._store[key]; }, set: function(value) { ("production" !== process.env.NODE_ENV ? warning( false, 'Don\'t set the %s property of the React element. Instead, ' + 'specify the correct value when initially creating the element.', key ) : null); this._store[key] = value; } }); } /** * This is updated to true if the membrane is successfully created. */ var useMutationMembrane = false; /** * Warn for mutations. * * @internal * @param {object} element */ function defineMutationMembrane(prototype) { try { var pseudoFrozenProperties = { props: true }; for (var key in pseudoFrozenProperties) { defineWarningProperty(prototype, key); } useMutationMembrane = true; } catch (x) { // IE will fail on defineProperty } } /** * Base constructor for all React elements. This is only used to make this * work with a dynamic instanceof check. Nothing should live on this prototype. * * @param {*} type * @param {string|object} ref * @param {*} key * @param {*} props * @internal */ var ReactElement = function(type, key, ref, owner, context, props) { // Built-in properties that belong on the element this.type = type; this.key = key; this.ref = ref; // Record the component responsible for creating this element. this._owner = owner; // TODO: Deprecate withContext, and then the context becomes accessible // through the owner. this._context = context; if ("production" !== process.env.NODE_ENV) { // The validation flag and props are currently mutative. We put them on // an external backing store so that we can freeze the whole object. // This can be replaced with a WeakMap once they are implemented in // commonly used development environments. this._store = {props: props, originalProps: assign({}, props)}; // To make comparing ReactElements easier for testing purposes, we make // the validation flag non-enumerable (where possible, which should // include every environment we run tests in), so the test framework // ignores it. try { Object.defineProperty(this._store, 'validated', { configurable: false, enumerable: false, writable: true }); } catch (x) { } this._store.validated = false; // We're not allowed to set props directly on the object so we early // return and rely on the prototype membrane to forward to the backing // store. if (useMutationMembrane) { Object.freeze(this); return; } } this.props = props; }; // We intentionally don't expose the function on the constructor property. // ReactElement should be indistinguishable from a plain object. ReactElement.prototype = { _isReactElement: true }; if ("production" !== process.env.NODE_ENV) { defineMutationMembrane(ReactElement.prototype); } ReactElement.createElement = function(type, config, children) { var propName; // Reserved names are extracted var props = {}; var key = null; var ref = null; if (config != null) { ref = config.ref === undefined ? null : config.ref; key = config.key === undefined ? null : '' + config.key; // Remaining properties are added to a new props object for (propName in config) { if (config.hasOwnProperty(propName) && !RESERVED_PROPS.hasOwnProperty(propName)) { props[propName] = config[propName]; } } } // Children can be more than one argument, and those are transferred onto // the newly allocated props object. var childrenLength = arguments.length - 2; if (childrenLength === 1) { props.children = children; } else if (childrenLength > 1) { var childArray = Array(childrenLength); for (var i = 0; i < childrenLength; i++) { childArray[i] = arguments[i + 2]; } props.children = childArray; } // Resolve default props if (type && type.defaultProps) { var defaultProps = type.defaultProps; for (propName in defaultProps) { if (typeof props[propName] === 'undefined') { props[propName] = defaultProps[propName]; } } } return new ReactElement( type, key, ref, ReactCurrentOwner.current, ReactContext.current, props ); }; ReactElement.createFactory = function(type) { var factory = ReactElement.createElement.bind(null, type); // Expose the type on the factory and the prototype so that it can be // easily accessed on elements. E.g. <Foo />.type === Foo.type. // This should not be named `constructor` since this may not be the function // that created the element, and it may not even be a constructor. // Legacy hook TODO: Warn if this is accessed factory.type = type; return factory; }; ReactElement.cloneAndReplaceProps = function(oldElement, newProps) { var newElement = new ReactElement( oldElement.type, oldElement.key, oldElement.ref, oldElement._owner, oldElement._context, newProps ); if ("production" !== process.env.NODE_ENV) { // If the key on the original is valid, then the clone is valid newElement._store.validated = oldElement._store.validated; } return newElement; }; ReactElement.cloneElement = function(element, config, children) { var propName; // Original props are copied var props = assign({}, element.props); // Reserved names are extracted var key = element.key; var ref = element.ref; // Owner will be preserved, unless ref is overridden var owner = element._owner; if (config != null) { if (config.ref !== undefined) { // Silently steal the ref from the parent. ref = config.ref; owner = ReactCurrentOwner.current; } if (config.key !== undefined) { key = '' + config.key; } // Remaining properties override existing props for (propName in config) { if (config.hasOwnProperty(propName) && !RESERVED_PROPS.hasOwnProperty(propName)) { props[propName] = config[propName]; } } } // Children can be more than one argument, and those are transferred onto // the newly allocated props object. var childrenLength = arguments.length - 2; if (childrenLength === 1) { props.children = children; } else if (childrenLength > 1) { var childArray = Array(childrenLength); for (var i = 0; i < childrenLength; i++) { childArray[i] = arguments[i + 2]; } props.children = childArray; } return new ReactElement( element.type, key, ref, owner, element._context, props ); }; /** * @param {?object} object * @return {boolean} True if `object` is a valid component. * @final */ ReactElement.isValidElement = function(object) { // ReactTestUtils is often used outside of beforeEach where as React is // within it. This leads to two different instances of React on the same // page. To identify a element from a different React instance we use // a flag instead of an instanceof check. var isElement = !!(object && object._isReactElement); // if (isElement && !(object instanceof ReactElement)) { // This is an indicator that you're using multiple versions of React at the // same time. This will screw with ownership and stuff. Fix it, please. // TODO: We could possibly warn here. // } return isElement; }; module.exports = ReactElement; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(31))) /***/ }, /* 33 */ /***/ 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. * * @providesModule ReactContext */ 'use strict'; var assign = __webpack_require__(34); var emptyObject = __webpack_require__(35); var warning = __webpack_require__(36); var didWarn = false; /** * Keeps track of the current context. * * The context is automatically passed down the component ownership hierarchy * and is accessible via `this.context` on ReactCompositeComponents. */ var ReactContext = { /** * @internal * @type {object} */ current: emptyObject, /** * Temporarily extends the current context while executing scopedCallback. * * A typical use case might look like * * render: function() { * var children = ReactContext.withContext({foo: 'foo'}, () => ( * * )); * return <div>{children}</div>; * } * * @param {object} newContext New context to merge into the existing context * @param {function} scopedCallback Callback to run with the new context * @return {ReactComponent|array<ReactComponent>} */ withContext: function(newContext, scopedCallback) { if ("production" !== process.env.NODE_ENV) { ("production" !== process.env.NODE_ENV ? warning( didWarn, 'withContext is deprecated and will be removed in a future version. ' + 'Use a wrapper component with getChildContext instead.' ) : null); didWarn = true; } var result; var previousContext = ReactContext.current; ReactContext.current = assign({}, previousContext, newContext); try { result = scopedCallback(); } finally { ReactContext.current = previousContext; } return result; } }; module.exports = ReactContext; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(31))) /***/ }, /* 34 */ /***/ function(module, exports) { /** * Copyright 2014-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. * * @providesModule Object.assign */ // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-object.assign 'use strict'; function assign(target, sources) { if (target == null) { throw new TypeError('Object.assign target cannot be null or undefined'); } var to = Object(target); var hasOwnProperty = Object.prototype.hasOwnProperty; for (var nextIndex = 1; nextIndex < arguments.length; nextIndex++) { var nextSource = arguments[nextIndex]; if (nextSource == null) { continue; } var from = Object(nextSource); // We don't currently support accessors nor proxies. Therefore this // copy cannot throw. If we ever supported this then we must handle // exceptions and side-effects. We don't support symbols so they won't // be transferred. for (var key in from) { if (hasOwnProperty.call(from, key)) { to[key] = from[key]; } } } return to; } module.exports = assign; /***/ }, /* 35 */ /***/ 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. * * @providesModule emptyObject */ "use strict"; var emptyObject = {}; if ("production" !== process.env.NODE_ENV) { Object.freeze(emptyObject); } module.exports = emptyObject; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(31))) /***/ }, /* 36 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2014-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. * * @providesModule warning */ "use strict"; var emptyFunction = __webpack_require__(37); /** * Similar to invariant but only logs a warning if the condition is not met. * This can be used to log issues in development environments in critical * paths. Removing the logging code for production environments will keep the * same logic and follow the same code paths. */ var warning = emptyFunction; if ("production" !== process.env.NODE_ENV) { warning = function(condition, format ) {for (var args=[],$__0=2,$__1=arguments.length;$__0<$__1;$__0++) args.push(arguments[$__0]); if (format === undefined) { throw new Error( '`warning(condition, format, ...args)` requires a warning ' + 'message argument' ); } if (format.length < 10 || /^[s\W]*$/.test(format)) { throw new Error( 'The warning format should be able to uniquely identify this ' + 'warning. Please, use a more descriptive format than: ' + format ); } if (format.indexOf('Failed Composite propType: ') === 0) { return; // Ignore CompositeComponent proptype check. } if (!condition) { var argIndex = 0; var message = 'Warning: ' + format.replace(/%s/g, function() {return args[argIndex++];}); console.warn(message); try { // --- Welcome to debugging React --- // This error was thrown as a convenience so that you can use this stack // to find the callsite that caused this warning to fire. throw new Error(message); } catch(x) {} } }; } module.exports = warning; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(31))) /***/ }, /* 37 */ /***/ function(module, exports) { /** * 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. * * @providesModule emptyFunction */ function makeEmptyFunction(arg) { return function() { return arg; }; } /** * This function accepts and discards inputs; it has no side effects. This is * primarily useful idiomatically for overridable function endpoints which * always need to be callable, since JS lacks a null-call idiom ala Cocoa. */ function emptyFunction() {} emptyFunction.thatReturns = makeEmptyFunction; emptyFunction.thatReturnsFalse = makeEmptyFunction(false); emptyFunction.thatReturnsTrue = makeEmptyFunction(true); emptyFunction.thatReturnsNull = makeEmptyFunction(null); emptyFunction.thatReturnsThis = function() { return this; }; emptyFunction.thatReturnsArgument = function(arg) { return arg; }; module.exports = emptyFunction; /***/ }, /* 38 */ /***/ function(module, exports) { /** * 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. * * @providesModule ReactCurrentOwner */ 'use strict'; /** * Keeps track of the current owner. * * The current owner is the component who should own any components that are * currently being constructed. * * The depth indicate how many composite components are above this render level. */ var ReactCurrentOwner = { /** * @internal * @type {ReactComponent} */ current: null }; module.exports = ReactCurrentOwner; /***/ }, /* 39 */ /***/ function(module, exports, __webpack_require__) { /** * 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. * * @providesModule ReactPropTransferer */ 'use strict'; var assign = __webpack_require__(34); var emptyFunction = __webpack_require__(37); var joinClasses = __webpack_require__(40); /** * Creates a transfer strategy that will merge prop values using the supplied * `mergeStrategy`. If a prop was previously unset, this just sets it. * * @param {function} mergeStrategy * @return {function} */ function createTransferStrategy(mergeStrategy) { return function(props, key, value) { if (!props.hasOwnProperty(key)) { props[key] = value; } else { props[key] = mergeStrategy(props[key], value); } }; } var transferStrategyMerge = createTransferStrategy(function(a, b) { // `merge` overrides the first object's (`props[key]` above) keys using the // second object's (`value`) keys. An object's style's existing `propA` would // get overridden. Flip the order here. return assign({}, b, a); }); /** * Transfer strategies dictate how props are transferred by `transferPropsTo`. * NOTE: if you add any more exceptions to this list you should be sure to * update `cloneWithProps()` accordingly. */ var TransferStrategies = { /** * Never transfer `children`. */ children: emptyFunction, /** * Transfer the `className` prop by merging them. */ className: createTransferStrategy(joinClasses), /** * Transfer the `style` prop (which is an object) by merging them. */ style: transferStrategyMerge }; /** * Mutates the first argument by transferring the properties from the second * argument. * * @param {object} props * @param {object} newProps * @return {object} */ function transferInto(props, newProps) { for (var thisKey in newProps) { if (!newProps.hasOwnProperty(thisKey)) { continue; } var transferStrategy = TransferStrategies[thisKey]; if (transferStrategy && TransferStrategies.hasOwnProperty(thisKey)) { transferStrategy(props, thisKey, newProps[thisKey]); } else if (!props.hasOwnProperty(thisKey)) { props[thisKey] = newProps[thisKey]; } } return props; } /** * ReactPropTransferer are capable of transferring props to another component * using a `transferPropsTo` method. * * @class ReactPropTransferer */ var ReactPropTransferer = { /** * Merge two props objects using TransferStrategies. * * @param {object} oldProps original props (they take precedence) * @param {object} newProps new props to merge in * @return {object} a new object containing both sets of props merged. */ mergeProps: function(oldProps, newProps) { return transferInto(assign({}, oldProps), newProps); } }; module.exports = ReactPropTransferer; /***/ }, /* 40 */ /***/ function(module, exports) { /** * 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. * * @providesModule joinClasses * @typechecks static-only */ 'use strict'; /** * Combines multiple className strings into one. * http://jsperf.com/joinclasses-args-vs-array * * @param {...?string} classes * @return {string} */ function joinClasses(className/*, ... */) { if (!className) { className = ''; } var nextClass; var argLength = arguments.length; if (argLength > 1) { for (var ii = 1; ii < argLength; ii++) { nextClass = arguments[ii]; if (nextClass) { className = (className ? className + ' ' : '') + nextClass; } } } return className; } module.exports = joinClasses; /***/ }, /* 41 */ /***/ function(module, exports) { /** * 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. * * @providesModule keyOf */ /** * Allows extraction of a minified key. Let's the build system minify keys * without loosing the ability to dynamically use key strings as values * themselves. Pass in an object with a single key/val pair and it will return * you the string key of that single record. Suppose you want to grab the * value for a key 'className' inside of an object. Key/val minification may * have aliased that key to be 'xa12'. keyOf({className: null}) will return * 'xa12' in that case. Resolve keys you want to use once at startup time, then * reuse those resolutions. */ var keyOf = function(oneKeyObj) { var key; for (key in oneKeyObj) { if (!oneKeyObj.hasOwnProperty(key)) { continue; } return key; } return null; }; module.exports = keyOf; /***/ }, /* 42 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var React = __webpack_require__(18); var ExcelColumnShape = { name: React.PropTypes.string.isRequired, key: React.PropTypes.string.isRequired, width: React.PropTypes.number.isRequired }; module.exports = ExcelColumnShape; /***/ }, /* 43 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _extends = __webpack_require__(2)['default']; var React = __webpack_require__(18); var Draggable = __webpack_require__(44); var ResizeHandle = React.createClass({ displayName: 'ResizeHandle', style: { position: 'absolute', top: 0, right: 0, width: 6, height: '100%' }, render: function render() { return React.createElement(Draggable, _extends({}, this.props, { className: 'react-grid-HeaderCell__resizeHandle', style: this.style })); } }); module.exports = ResizeHandle; /***/ }, /* 44 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _extends = __webpack_require__(2)['default']; var React = __webpack_require__(18); var PropTypes = React.PropTypes; var emptyFunction = __webpack_require__(37); var Draggable = React.createClass({ displayName: 'Draggable', propTypes: { onDragStart: PropTypes.func, onDragEnd: PropTypes.func, onDrag: PropTypes.func, component: PropTypes.oneOfType([PropTypes.func, PropTypes.constructor]) }, getDefaultProps: function getDefaultProps() { return { onDragStart: emptyFunction.thatReturnsTrue, onDragEnd: emptyFunction, onDrag: emptyFunction }; }, getInitialState: function getInitialState() { return { drag: null }; }, componentWillUnmount: function componentWillUnmount() { this.cleanUp(); }, onMouseDown: function onMouseDown(e) { var drag = this.props.onDragStart(e); if (drag === null && e.button !== 0) { return; } window.addEventListener('mouseup', this.onMouseUp); window.addEventListener('mousemove', this.onMouseMove); this.setState({ drag: drag }); }, onMouseMove: function onMouseMove(e) { if (this.state.drag === null) { return; } if (e.preventDefault) { e.preventDefault(); } this.props.onDrag(e); }, onMouseUp: function onMouseUp(e) { this.cleanUp(); this.props.onDragEnd(e, this.state.drag); this.setState({ drag: null }); }, cleanUp: function cleanUp() { window.removeEventListener('mouseup', this.onMouseUp); window.removeEventListener('mousemove', this.onMouseMove); }, render: function render() { return React.createElement('div', _extends({}, this.props, { onMouseDown: this.onMouseDown, className: 'react-grid-HeaderCell__draggable' })); } }); module.exports = Draggable; /***/ }, /* 45 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var React = __webpack_require__(18); var joinClasses = __webpack_require__(21); var DEFINE_SORT = { ASC: 'ASC', DESC: 'DESC', NONE: 'NONE' }; var SortableHeaderCell = React.createClass({ displayName: 'SortableHeaderCell', propTypes: { columnKey: React.PropTypes.string.isRequired, column: React.PropTypes.shape({ name: React.PropTypes.string }), onSort: React.PropTypes.func.isRequired, sortDirection: React.PropTypes.oneOf(['ASC', 'DESC', 'NONE']) }, onClick: function onClick() { var direction = undefined; switch (this.props.sortDirection) { default: case null: case undefined: case DEFINE_SORT.NONE: direction = DEFINE_SORT.ASC; break; case DEFINE_SORT.ASC: direction = DEFINE_SORT.DESC; break; case DEFINE_SORT.DESC: direction = DEFINE_SORT.NONE; break; } this.props.onSort(this.props.columnKey, direction); }, getSortByText: function getSortByText() { var unicodeKeys = { ASC: '9650', DESC: '9660', NONE: '' }; return String.fromCharCode(unicodeKeys[this.props.sortDirection]); }, render: function render() { var className = joinClasses({ 'react-grid-HeaderCell-sortable': true, 'react-grid-HeaderCell-sortable--ascending': this.props.sortDirection === 'ASC', 'react-grid-HeaderCell-sortable--descending': this.props.sortDirection === 'DESC' }); return React.createElement( 'div', { className: className, onClick: this.onClick, style: { cursor: 'pointer' } }, this.props.column.name, React.createElement( 'span', { className: 'pull-right' }, this.getSortByText() ) ); } }); module.exports = SortableHeaderCell; /***/ }, /* 46 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var React = __webpack_require__(18); var Canvas = __webpack_require__(47); var ViewportScroll = __webpack_require__(77); var cellMetaDataShape = __webpack_require__(75); var PropTypes = React.PropTypes; var Viewport = React.createClass({ displayName: 'Viewport', mixins: [ViewportScroll], propTypes: { rowOffsetHeight: PropTypes.number.isRequired, totalWidth: PropTypes.number.isRequired, columnMetrics: PropTypes.object.isRequired, rowGetter: PropTypes.oneOfType([PropTypes.array, PropTypes.func]).isRequired, selectedRows: PropTypes.array, expandedRows: PropTypes.array, rowRenderer: PropTypes.func, rowsCount: PropTypes.number.isRequired, rowHeight: PropTypes.number.isRequired, onRows: PropTypes.func, onScroll: PropTypes.func, minHeight: PropTypes.number, cellMetaData: PropTypes.shape(cellMetaDataShape) }, onScroll: function onScroll(scroll) { this.updateScroll(scroll.scrollTop, scroll.scrollLeft, this.state.height, this.props.rowHeight, this.props.rowsCount); if (this.props.onScroll) { this.props.onScroll({ scrollTop: scroll.scrollTop, scrollLeft: scroll.scrollLeft }); } }, getScroll: function getScroll() { return this.refs.canvas.getScroll(); }, setScrollLeft: function setScrollLeft(scrollLeft) { this.refs.canvas.setScrollLeft(scrollLeft); }, render: function render() { var style = { padding: 0, bottom: 0, left: 0, right: 0, overflow: 'hidden', position: 'absolute', top: this.props.rowOffsetHeight }; return React.createElement( 'div', { className: 'react-grid-Viewport', style: style }, React.createElement(Canvas, { ref: 'canvas', totalWidth: this.props.totalWidth, width: this.props.columnMetrics.width, rowGetter: this.props.rowGetter, rowsCount: this.props.rowsCount, selectedRows: this.props.selectedRows, expandedRows: this.props.expandedRows, columns: this.props.columnMetrics.columns, rowRenderer: this.props.rowRenderer, visibleStart: this.state.visibleStart, visibleEnd: this.state.visibleEnd, displayStart: this.state.displayStart, displayEnd: this.state.displayEnd, cellMetaData: this.props.cellMetaData, height: this.state.height, rowHeight: this.props.rowHeight, onScroll: this.onScroll, onRows: this.props.onRows }) ); } }); module.exports = Viewport; /***/ }, /* 47 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var React = __webpack_require__(18); var joinClasses = __webpack_require__(21); var PropTypes = React.PropTypes; var cloneWithProps = __webpack_require__(30); var shallowEqual = __webpack_require__(28); var emptyFunction = __webpack_require__(37); var ScrollShim = __webpack_require__(48); var Row = __webpack_require__(49); var cellMetaDataShape = __webpack_require__(75); var Canvas = React.createClass({ displayName: 'Canvas', mixins: [ScrollShim], propTypes: { rowRenderer: PropTypes.oneOfType([PropTypes.func, PropTypes.element]), rowHeight: PropTypes.number.isRequired, height: PropTypes.number.isRequired, width: PropTypes.number, totalWidth: PropTypes.number, style: PropTypes.string, className: PropTypes.string, displayStart: PropTypes.number.isRequired, displayEnd: PropTypes.number.isRequired, rowsCount: PropTypes.number.isRequired, rowGetter: PropTypes.oneOfType([PropTypes.func.isRequired, PropTypes.array.isRequired]), expandedRows: PropTypes.array, onRows: PropTypes.func, onScroll: PropTypes.func, columns: PropTypes.oneOfType([PropTypes.object, PropTypes.array]).isRequired, cellMetaData: PropTypes.shape(cellMetaDataShape).isRequired, selectedRows: PropTypes.array }, getDefaultProps: function getDefaultProps() { return { rowRenderer: Row, onRows: emptyFunction }; }, getInitialState: function getInitialState() { return { shouldUpdate: true, displayStart: this.props.displayStart, displayEnd: this.props.displayEnd, scrollbarWidth: 0 }; }, componentWillMount: function componentWillMount() { this._currentRowsLength = 0; this._currentRowsRange = { start: 0, end: 0 }; this._scroll = { scrollTop: 0, scrollLeft: 0 }; }, componentDidMount: function componentDidMount() { this.onRows(); }, componentWillReceiveProps: function componentWillReceiveProps(nextProps) { if (nextProps.rowsCount > this.props.rowsCount) { React.findDOMNode(this).scrollTop = nextProps.rowsCount * this.props.rowHeight; } var scrollbarWidth = this.getScrollbarWidth(); var shouldUpdate = !(nextProps.visibleStart > this.state.displayStart && nextProps.visibleEnd < this.state.displayEnd) || nextProps.rowsCount !== this.props.rowsCount || nextProps.rowHeight !== this.props.rowHeight || nextProps.columns !== this.props.columns || nextProps.width !== this.props.width || nextProps.cellMetaData !== this.props.cellMetaData || !shallowEqual(nextProps.style, this.props.style); if (shouldUpdate) { this.setState({ shouldUpdate: true, displayStart: nextProps.displayStart, displayEnd: nextProps.displayEnd, scrollbarWidth: scrollbarWidth }); } else { this.setState({ shouldUpdate: false, scrollbarWidth: scrollbarWidth }); } }, shouldComponentUpdate: function shouldComponentUpdate(nextProps, nextState) { return !nextState || nextState.shouldUpdate; }, componentWillUnmount: function componentWillUnmount() { this._currentRowsLength = 0; this._currentRowsRange = { start: 0, end: 0 }; this._scroll = { scrollTop: 0, scrollLeft: 0 }; }, componentDidUpdate: function componentDidUpdate() { if (this._scroll.scrollTop !== 0 && this._scroll.scrollLeft !== 0) { this.setScrollLeft(this._scroll.scrollLeft); } this.onRows(); }, onRows: function onRows() { if (this._currentRowsRange !== { start: 0, end: 0 }) { this.props.onRows(this._currentRowsRange); this._currentRowsRange = { start: 0, end: 0 }; } }, onScroll: function onScroll(e) { this.appendScrollShim(); var _e$target = e.target; var scrollTop = _e$target.scrollTop; var scrollLeft = _e$target.scrollLeft; var scroll = { scrollTop: scrollTop, scrollLeft: scrollLeft }; this._scroll = scroll; this.props.onScroll(scroll); }, getRows: function getRows(displayStart, displayEnd) { this._currentRowsRange = { start: displayStart, end: displayEnd }; if (Array.isArray(this.props.rowGetter)) { return this.props.rowGetter.slice(displayStart, displayEnd); } var rows = []; for (var i = displayStart; i < displayEnd; i++) { rows.push(this.props.rowGetter(i)); } return rows; }, getScrollbarWidth: function getScrollbarWidth() { var scrollbarWidth = 0; // Get the scrollbar width var canvas = React.findDOMNode(this); scrollbarWidth = canvas.offsetWidth - canvas.clientWidth; return scrollbarWidth; }, getScroll: function getScroll() { var _React$findDOMNode = React.findDOMNode(this); var scrollTop = _React$findDOMNode.scrollTop; var scrollLeft = _React$findDOMNode.scrollLeft; return { scrollTop: scrollTop, scrollLeft: scrollLeft }; }, isRowSelected: function isRowSelected(rowIdx) { return this.props.selectedRows && this.props.selectedRows[rowIdx] === true; }, _currentRowsLength: 0, _currentRowsRange: { start: 0, end: 0 }, _scroll: { scrollTop: 0, scrollLeft: 0 }, setScrollLeft: function setScrollLeft(scrollLeft) { if (this._currentRowsLength !== 0) { if (!this.refs) return; for (var i = 0, len = this._currentRowsLength; i < len; i++) { if (this.refs[i] && this.refs[i].setScrollLeft) { this.refs[i].setScrollLeft(scrollLeft); } } } }, renderRow: function renderRow(props) { var RowsRenderer = this.props.rowRenderer; if (typeof RowsRenderer === 'function') { return React.createElement(RowsRenderer, props); } if (React.isValidElement(this.props.rowRenderer)) { return cloneWithProps(this.props.rowRenderer, props); } }, renderPlaceholder: function renderPlaceholder(key, height) { return React.createElement( 'div', { key: key, style: { height: height } }, this.props.columns.map(function (column, idx) { return React.createElement('div', { style: { width: column.width }, key: idx }); }) ); }, render: function render() { var _this = this; var displayStart = this.state.displayStart; var displayEnd = this.state.displayEnd; var rowHeight = this.props.rowHeight; var length = this.props.rowsCount; var rows = this.getRows(displayStart, displayEnd).map(function (row, idx) { return _this.renderRow({ key: displayStart + idx, ref: idx, idx: displayStart + idx, row: row, height: rowHeight, columns: _this.props.columns, isSelected: _this.isRowSelected(displayStart + idx), expandedRows: _this.props.expandedRows, cellMetaData: _this.props.cellMetaData }); }); this._currentRowsLength = rows.length; if (displayStart > 0) { rows.unshift(this.renderPlaceholder('top', displayStart * rowHeight)); } if (length - displayEnd > 0) { rows.push(this.renderPlaceholder('bottom', (length - displayEnd) * rowHeight)); } var style = { position: 'absolute', top: 0, left: 0, overflowX: 'auto', overflowY: 'scroll', width: this.props.totalWidth + this.state.scrollbarWidth, height: this.props.height, transform: 'translate3d(0, 0, 0)' }; return React.createElement( 'div', { style: style, onScroll: this.onScroll, className: joinClasses('react-grid-Canvas', this.props.className, { opaque: this.props.cellMetaData.selected && this.props.cellMetaData.selected.active }) }, React.createElement( 'div', { style: { width: this.props.width, overflow: 'hidden' } }, rows ) ); } }); module.exports = Canvas; /***/ }, /* 48 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var React = __webpack_require__(18); var ScrollShim = { appendScrollShim: function appendScrollShim() { if (!this._scrollShim) { var size = this._scrollShimSize(); var shim = document.createElement('div'); if (shim.classList) { shim.classList.add('react-grid-ScrollShim'); // flow - not compatible with HTMLElement } else { shim.className += ' react-grid-ScrollShim'; } shim.style.position = 'absolute'; shim.style.top = 0; shim.style.left = 0; shim.style.width = size.width + 'px'; shim.style.height = size.height + 'px'; React.findDOMNode(this).appendChild(shim); this._scrollShim = shim; } this._scheduleRemoveScrollShim(); }, _scrollShimSize: function _scrollShimSize() { return { width: this.props.width, height: this.props.length * this.props.rowHeight }; }, _scheduleRemoveScrollShim: function _scheduleRemoveScrollShim() { if (this._scheduleRemoveScrollShimTimer) { clearTimeout(this._scheduleRemoveScrollShimTimer); } this._scheduleRemoveScrollShimTimer = setTimeout(this._removeScrollShim, 200); }, _removeScrollShim: function _removeScrollShim() { if (this._scrollShim) { this._scrollShim.parentNode.removeChild(this._scrollShim); this._scrollShim = undefined; } } }; module.exports = ScrollShim; /***/ }, /* 49 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _extends = __webpack_require__(2)['default']; var React = __webpack_require__(18); var joinClasses = __webpack_require__(21); var Cell = __webpack_require__(50); var ColumnMetrics = __webpack_require__(23); var ColumnUtilsMixin = __webpack_require__(25); var cellMetaDataShape = __webpack_require__(75); var PropTypes = React.PropTypes; var Row = React.createClass({ displayName: 'Row', propTypes: { height: PropTypes.number.isRequired, columns: PropTypes.oneOfType([PropTypes.object, PropTypes.array]).isRequired, row: PropTypes.any.isRequired, cellRenderer: PropTypes.func, cellMetaData: PropTypes.shape(cellMetaDataShape), isSelected: PropTypes.bool, idx: PropTypes.number.isRequired, key: PropTypes.string, expandedRows: PropTypes.arrayOf(PropTypes.object) }, mixins: [ColumnUtilsMixin], getDefaultProps: function getDefaultProps() { return { cellRenderer: Cell, isSelected: false, height: 35 }; }, shouldComponentUpdate: function shouldComponentUpdate(nextProps) { return !ColumnMetrics.sameColumns(this.props.columns, nextProps.columns, ColumnMetrics.sameColumn) || this.doesRowContainSelectedCell(this.props) || this.doesRowContainSelectedCell(nextProps) || this.willRowBeDraggedOver(nextProps) || nextProps.row !== this.props.row || this.hasRowBeenCopied() || this.props.isSelected !== nextProps.isSelected || nextProps.height !== this.props.height; }, handleDragEnter: function handleDragEnter() { var handleDragEnterRow = this.props.cellMetaData.handleDragEnterRow; if (handleDragEnterRow) { handleDragEnterRow(this.props.idx); } }, getSelectedColumn: function getSelectedColumn() { var selected = this.props.cellMetaData.selected; if (selected && selected.idx) { return this.getColumn(this.props.columns, selected.idx); } }, getCells: function getCells() { var _this = this; var cells = []; var lockedCells = []; var selectedColumn = this.getSelectedColumn(); this.props.columns.forEach(function (column, i) { var CellRenderer = _this.props.cellRenderer; var cell = React.createElement(CellRenderer, { ref: i, key: column.key + '-' + i, idx: i, rowIdx: _this.props.idx, value: _this.getCellValue(column.key || i), column: column, height: _this.getRowHeight(), formatter: column.formatter, cellMetaData: _this.props.cellMetaData, rowData: _this.props.row, selectedColumn: selectedColumn, isRowSelected: _this.props.isSelected }); if (column.locked) { lockedCells.push(cell); } else { cells.push(cell); } }); return cells.concat(lockedCells); }, getRowHeight: function getRowHeight() { var rows = this.props.expandedRows || null; if (rows && this.props.key) { var row = rows[this.props.key] || null; if (row) { return row.height; } } return this.props.height; }, getCellValue: function getCellValue(key) { var val = undefined; if (key === 'select-row') { return this.props.isSelected; } else if (typeof this.props.row.get === 'function') { val = this.props.row.get(key); } else { val = this.props.row[key]; } return val; }, setScrollLeft: function setScrollLeft(scrollLeft) { var _this2 = this; this.props.columns.forEach(function (column, i) { if (column.locked) { if (!_this2.refs[i]) return; _this2.refs[i].setScrollLeft(scrollLeft); } }); }, doesRowContainSelectedCell: function doesRowContainSelectedCell(props) { var selected = props.cellMetaData.selected; if (selected && selected.rowIdx === props.idx) { return true; } return false; }, willRowBeDraggedOver: function willRowBeDraggedOver(props) { var dragged = props.cellMetaData.dragged; return dragged != null && (dragged.rowIdx >= 0 || dragged.complete === true); }, hasRowBeenCopied: function hasRowBeenCopied() { var copied = this.props.cellMetaData.copied; return copied != null && copied.rowIdx === this.props.idx; }, renderCell: function renderCell(props) { if (typeof this.props.cellRenderer === 'function') { this.props.cellRenderer.call(this, props); } if (React.isValidElement(this.props.cellRenderer)) { return cloneWithProps(this.props.cellRenderer, props); } return this.props.cellRenderer(props); }, render: function render() { var className = joinClasses('react-grid-Row', 'react-grid-Row--' + (this.props.idx % 2 === 0 ? 'even' : 'odd')); var style = { height: this.getRowHeight(this.props), overflow: 'hidden' }; var cells = this.getCells(); return React.createElement( 'div', _extends({}, this.props, { className: className, style: style, onDragEnter: this.handleDragEnter }), React.isValidElement(this.props.row) ? this.props.row : cells ); } }); module.exports = Row; /***/ }, /* 50 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _extends = __webpack_require__(2)['default']; var React = __webpack_require__(18); var joinClasses = __webpack_require__(21); var cloneWithProps = __webpack_require__(30); var EditorContainer = __webpack_require__(51); var ExcelColumn = __webpack_require__(42); var isFunction = __webpack_require__(74); var CellMetaDataShape = __webpack_require__(75); var SimpleCellFormatter = __webpack_require__(76); var Cell = React.createClass({ displayName: 'Cell', propTypes: { rowIdx: React.PropTypes.number.isRequired, idx: React.PropTypes.number.isRequired, selected: React.PropTypes.shape({ idx: React.PropTypes.number.isRequired }), selectedColumn: React.PropTypes.object, height: React.PropTypes.number, tabIndex: React.PropTypes.number, ref: React.PropTypes.string, column: React.PropTypes.shape(ExcelColumn).isRequired, value: React.PropTypes.oneOfType([React.PropTypes.string, React.PropTypes.number, React.PropTypes.object, React.PropTypes.bool]).isRequired, isExpanded: React.PropTypes.bool, isRowSelected: React.PropTypes.bool, cellMetaData: React.PropTypes.shape(CellMetaDataShape).isRequired, handleDragStart: React.PropTypes.func, className: React.PropTypes.string, cellControls: React.PropTypes.any, rowData: React.PropTypes.object.isRequired }, getDefaultProps: function getDefaultProps() { return { tabIndex: -1, ref: 'cell', isExpanded: false }; }, getInitialState: function getInitialState() { return { isRowChanging: false, isCellValueChanging: false }; }, componentDidMount: function componentDidMount() { this.checkFocus(); }, componentWillReceiveProps: function componentWillReceiveProps(nextProps) { this.setState({ isRowChanging: this.props.rowData !== nextProps.rowData, isCellValueChanging: this.props.value !== nextProps.value }); }, componentDidUpdate: function componentDidUpdate() { this.checkFocus(); var dragged = this.props.cellMetaData.dragged; if (dragged && dragged.complete === true) { this.props.cellMetaData.handleTerminateDrag(); } if (this.state.isRowChanging && this.props.selectedColumn != null) { this.applyUpdateClass(); } }, shouldComponentUpdate: function shouldComponentUpdate(nextProps) { return this.props.column.width !== nextProps.column.width || this.props.column.left !== nextProps.column.left || this.props.rowData !== nextProps.rowData || this.props.height !== nextProps.height || this.props.rowIdx !== nextProps.rowIdx || this.isCellSelectionChanging(nextProps) || this.isDraggedCellChanging(nextProps) || this.isCopyCellChanging(nextProps) || this.props.isRowSelected !== nextProps.isRowSelected || this.isSelected() || this.props.value !== nextProps.value; }, onCellClick: function onCellClick() { var meta = this.props.cellMetaData; if (meta != null && meta.onCellClick != null) { meta.onCellClick({ rowIdx: this.props.rowIdx, idx: this.props.idx }); } }, onCellDoubleClick: function onCellDoubleClick() { var meta = this.props.cellMetaData; if (meta != null && meta.onCellDoubleClick != null) { meta.onCellDoubleClick({ rowIdx: this.props.rowIdx, idx: this.props.idx }); } }, getStyle: function getStyle() { var style = { position: 'absolute', width: this.props.column.width, height: this.props.height, left: this.props.column.left }; return style; }, getFormatter: function getFormatter() { var col = this.props.column; if (this.isActive()) { return React.createElement(EditorContainer, { rowData: this.getRowData(), rowIdx: this.props.rowIdx, idx: this.props.idx, cellMetaData: this.props.cellMetaData, column: col, height: this.props.height }); } return this.props.column.formatter; }, getRowData: function getRowData() { return this.props.rowData.toJSON ? this.props.rowData.toJSON() : this.props.rowData; }, getFormatterDependencies: function getFormatterDependencies() { // convention based method to get corresponding Id or Name of any Name or Id property if (typeof this.props.column.getRowMetaData === 'function') { return this.props.column.getRowMetaData(this.getRowData(), this.props.column); } }, getCellClass: function getCellClass() { var className = joinClasses(this.props.column.cellClass, 'react-grid-Cell', this.props.className, this.props.column.locked ? 'react-grid-Cell--locked' : null); var extraClasses = joinClasses({ selected: this.isSelected() && !this.isActive(), editing: this.isActive(), copied: this.isCopied(), 'active-drag-cell': this.isSelected() || this.isDraggedOver(), 'is-dragged-over-up': this.isDraggedOverUpwards(), 'is-dragged-over-down': this.isDraggedOverDownwards(), 'was-dragged-over': this.wasDraggedOver() }); return joinClasses(className, extraClasses); }, getUpdateCellClass: function getUpdateCellClass() { return this.props.column.getUpdateCellClass ? this.props.column.getUpdateCellClass(this.props.selectedColumn, this.props.column, this.state.isCellValueChanging) : ''; }, isColumnSelected: function isColumnSelected() { var meta = this.props.cellMetaData; if (meta == null || meta.selected == null) { return false; } return meta.selected && meta.selected.idx === this.props.idx; }, isSelected: function isSelected() { var meta = this.props.cellMetaData; if (meta == null || meta.selected == null) { return false; } return meta.selected && meta.selected.rowIdx === this.props.rowIdx && meta.selected.idx === this.props.idx; }, isActive: function isActive() { var meta = this.props.cellMetaData; if (meta == null || meta.selected == null) { return false; } return this.isSelected() && meta.selected.active === true; }, isCellSelectionChanging: function isCellSelectionChanging(nextProps) { var meta = this.props.cellMetaData; if (meta == null || meta.selected == null) { return false; } var nextSelected = nextProps.cellMetaData.selected; if (meta.selected && nextSelected) { return this.props.idx === nextSelected.idx || this.props.idx === meta.selected.idx; } return true; }, applyUpdateClass: function applyUpdateClass() { var updateCellClass = this.getUpdateCellClass(); // -> removing the class if (updateCellClass != null && updateCellClass !== '') { var cellDOMNode = this.getDOMNode(); if (cellDOMNode.classList) { cellDOMNode.classList.remove(updateCellClass); // -> and re-adding the class cellDOMNode.classList.add(updateCellClass); } else if (cellDOMNode.className.indexOf(updateCellClass) === -1) { // IE9 doesn't support classList, nor (I think) altering element.className // without replacing it wholesale. cellDOMNode.className = cellDOMNode.className + ' ' + updateCellClass; } } }, setScrollLeft: function setScrollLeft(scrollLeft) { var ctrl = this; // flow on windows has an outdated react declaration, once that gets updated, we can remove this if (ctrl.isMounted()) { var node = React.findDOMNode(this); var transform = 'translate3d(' + scrollLeft + 'px, 0px, 0px)'; node.style.webkitTransform = transform; node.style.transform = transform; } }, isCopied: function isCopied() { var copied = this.props.cellMetaData.copied; return copied && copied.rowIdx === this.props.rowIdx && copied.idx === this.props.idx; }, isDraggedOver: function isDraggedOver() { var dragged = this.props.cellMetaData.dragged; return dragged && dragged.overRowIdx === this.props.rowIdx && dragged.idx === this.props.idx; }, wasDraggedOver: function wasDraggedOver() { var dragged = this.props.cellMetaData.dragged; return dragged && (dragged.overRowIdx < this.props.rowIdx && this.props.rowIdx < dragged.rowIdx || dragged.overRowIdx > this.props.rowIdx && this.props.rowIdx > dragged.rowIdx) && dragged.idx === this.props.idx; }, isDraggedCellChanging: function isDraggedCellChanging(nextProps) { var isChanging = undefined; var dragged = this.props.cellMetaData.dragged; var nextDragged = nextProps.cellMetaData.dragged; if (dragged) { isChanging = nextDragged && this.props.idx === nextDragged.idx || dragged && this.props.idx === dragged.idx; return isChanging; } return false; }, isCopyCellChanging: function isCopyCellChanging(nextProps) { var isChanging = undefined; var copied = this.props.cellMetaData.copied; var nextCopied = nextProps.cellMetaData.copied; if (copied) { isChanging = nextCopied && this.props.idx === nextCopied.idx || copied && this.props.idx === copied.idx; return isChanging; } return false; }, isDraggedOverUpwards: function isDraggedOverUpwards() { var dragged = this.props.cellMetaData.dragged; return !this.isSelected() && this.isDraggedOver() && this.props.rowIdx < dragged.rowIdx; }, isDraggedOverDownwards: function isDraggedOverDownwards() { var dragged = this.props.cellMetaData.dragged; return !this.isSelected() && this.isDraggedOver() && this.props.rowIdx > dragged.rowIdx; }, checkFocus: function checkFocus() { if (this.isSelected() && !this.isActive()) { React.findDOMNode(this).focus(); } }, renderCellContent: function renderCellContent(props) { var CellContent = undefined; var Formatter = this.getFormatter(); if (React.isValidElement(Formatter)) { props.dependentValues = this.getFormatterDependencies(); CellContent = cloneWithProps(Formatter, props); } else if (isFunction(Formatter)) { CellContent = React.createElement(Formatter, { value: this.props.value, dependentValues: this.getFormatterDependencies() }); } else { CellContent = React.createElement(SimpleCellFormatter, { value: this.props.value }); } return React.createElement( 'div', { ref: 'cell', className: 'react-grid-Cell__value' }, CellContent, ' ', this.props.cellControls ); }, render: function render() { var style = this.getStyle(); var className = this.getCellClass(); var cellContent = this.renderCellContent({ value: this.props.value, column: this.props.column, rowIdx: this.props.rowIdx, isExpanded: this.props.isExpanded }); return React.createElement( 'div', _extends({}, this.props, { className: className, style: style, onClick: this.onCellClick, onDoubleClick: this.onCellDoubleClick }), cellContent, React.createElement('div', { className: 'drag-handle', draggable: 'true' }) ); } }); module.exports = Cell; /***/ }, /* 51 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var React = __webpack_require__(18); var joinClasses = __webpack_require__(21); var keyboardHandlerMixin = __webpack_require__(52); var SimpleTextEditor = __webpack_require__(53); var isFunction = __webpack_require__(74); var cloneWithProps = __webpack_require__(30); var EditorContainer = React.createClass({ displayName: 'EditorContainer', mixins: [keyboardHandlerMixin], propTypes: { rowIdx: React.PropTypes.number, rowData: React.PropTypes.object.isRequired, value: React.PropTypes.oneOfType([React.PropTypes.string, React.PropTypes.number, React.PropTypes.object, React.PropTypes.bool]).isRequired, cellMetaData: React.PropTypes.shape({ selected: React.PropTypes.object.isRequired, copied: React.PropTypes.object, dragged: React.PropTypes.object, onCellClick: React.PropTypes.func, onCellDoubleClick: React.PropTypes.func, onCommitCancel: React.PropTypes.func, onCommit: React.PropTypes.func }).isRequired, column: React.PropTypes.object.isRequired, height: React.PropTypes.number.isRequired }, changeCommitted: false, getInitialState: function getInitialState() { return { isInvalid: false }; }, componentDidMount: function componentDidMount() { var inputNode = this.getInputNode(); if (inputNode !== undefined) { this.setTextInputFocus(); if (!this.getEditor().disableContainerStyles) { inputNode.className += ' editor-main'; inputNode.style.height = this.props.height - 1 + 'px'; } } }, componentWillUnmount: function componentWillUnmount() { if (!this.changeCommitted && !this.hasEscapeBeenPressed()) { this.commit({ key: 'Enter' }); } }, createEditor: function createEditor() { var _this = this; var editorRef = function editorRef(c) { return _this.editor = c; }; var editorProps = { ref: editorRef, column: this.props.column, value: this.getInitialValue(), onCommit: this.commit, rowMetaData: this.getRowMetaData(), height: this.props.height, onBlur: this.commit, onOverrideKeyDown: this.onKeyDown }; var customEditor = this.props.column.editor; if (customEditor && React.isValidElement(customEditor)) { // return custom column editor or SimpleEditor if none specified return cloneWithProps(customEditor, editorProps); } return React.createElement(SimpleTextEditor, { ref: editorRef, column: this.props.column, value: this.getInitialValue(), onBlur: this.commit, rowMetaData: this.getRowMetaData(), onKeyDown: function () {}, commit: function () {} }); }, onPressEnter: function onPressEnter() { this.commit({ key: 'Enter' }); }, onPressTab: function onPressTab() { this.commit({ key: 'Tab' }); }, onPressEscape: function onPressEscape(e) { if (!this.editorIsSelectOpen()) { this.props.cellMetaData.onCommitCancel(); } else { // prevent event from bubbling if editor has results to select e.stopPropagation(); } }, onPressArrowDown: function onPressArrowDown(e) { if (this.editorHasResults()) { // dont want to propogate as that then moves us round the grid e.stopPropagation(); } else { this.commit(e); } }, onPressArrowUp: function onPressArrowUp(e) { if (this.editorHasResults()) { // dont want to propogate as that then moves us round the grid e.stopPropagation(); } else { this.commit(e); } }, onPressArrowLeft: function onPressArrowLeft(e) { // prevent event propogation. this disables left cell navigation if (!this.isCaretAtBeginningOfInput()) { e.stopPropagation(); } else { this.commit(e); } }, onPressArrowRight: function onPressArrowRight(e) { // prevent event propogation. this disables right cell navigation if (!this.isCaretAtEndOfInput()) { e.stopPropagation(); } else { this.commit(e); } }, editorHasResults: function editorHasResults() { if (isFunction(this.getEditor().hasResults)) { return this.getEditor().hasResults(); } return false; }, editorIsSelectOpen: function editorIsSelectOpen() { if (isFunction(this.getEditor().isSelectOpen)) { return this.getEditor().isSelectOpen(); } return false; }, getRowMetaData: function getRowMetaData() { // clone row data so editor cannot actually change this // convention based method to get corresponding Id or Name of any Name or Id property if (typeof this.props.column.getRowMetaData === 'function') { return this.props.column.getRowMetaData(this.props.rowData, this.props.column); } }, getEditor: function getEditor() { return this.editor; }, getInputNode: function getInputNode() { return this.getEditor().getInputNode(); }, getInitialValue: function getInitialValue() { var selected = this.props.cellMetaData.selected; var keyCode = selected.initialKeyCode; if (keyCode === 'Delete' || keyCode === 'Backspace') { return ''; } else if (keyCode === 'Enter') { return this.props.value; } var text = keyCode ? String.fromCharCode(keyCode) : this.props.value; return text; }, getContainerClass: function getContainerClass() { return joinClasses({ 'has-error': this.state.isInvalid === true }); }, commit: function commit(args) { var opts = args || {}; var updated = this.getEditor().getValue(); if (this.isNewValueValid(updated)) { var cellKey = this.props.column.key; this.props.cellMetaData.onCommit({ cellKey: cellKey, rowIdx: this.props.rowIdx, updated: updated, key: opts.key }); } this.changeCommitted = true; }, isNewValueValid: function isNewValueValid(value) { if (isFunction(this.getEditor().validate)) { var isValid = this.getEditor().validate(value); this.setState({ isInvalid: !isValid }); return isValid; } return true; }, setCaretAtEndOfInput: function setCaretAtEndOfInput() { var input = this.getInputNode(); // taken from http://stackoverflow.com/questions/511088/use-javascript-to-place-cursor-at-end-of-text-in-text-input-element var txtLength = input.value.length; if (input.setSelectionRange) { input.setSelectionRange(txtLength, txtLength); } else if (input.createTextRange) { var fieldRange = input.createTextRange(); fieldRange.moveStart('character', txtLength); fieldRange.collapse(); fieldRange.select(); } }, isCaretAtBeginningOfInput: function isCaretAtBeginningOfInput() { var inputNode = this.getInputNode(); return inputNode.selectionStart === inputNode.selectionEnd && inputNode.selectionStart === 0; }, isCaretAtEndOfInput: function isCaretAtEndOfInput() { var inputNode = this.getInputNode(); return inputNode.selectionStart === inputNode.value.length; }, setTextInputFocus: function setTextInputFocus() { var selected = this.props.cellMetaData.selected; var keyCode = selected.initialKeyCode; var inputNode = this.getInputNode(); inputNode.focus(); if (inputNode.tagName === 'INPUT') { if (!this.isKeyPrintable(keyCode)) { inputNode.focus(); inputNode.select(); } else { inputNode.select(); } } }, hasEscapeBeenPressed: function hasEscapeBeenPressed() { var pressed = false; var escapeKey = 27; if (window.event) { if (window.event.keyCode === escapeKey) { pressed = true; } else if (window.event.which === escapeKey) { pressed = true; } } return pressed; }, renderStatusIcon: function renderStatusIcon() { if (this.state.isInvalid === true) { return React.createElement('span', { className: 'glyphicon glyphicon-remove form-control-feedback' }); } }, render: function render() { return React.createElement( 'div', { className: this.getContainerClass(), onKeyDown: this.onKeyDown, commit: this.commit }, this.createEditor(), this.renderStatusIcon() ); } }); module.exports = EditorContainer; /***/ }, /* 52 */ /***/ function(module, exports) { 'use strict'; var KeyboardHandlerMixin = { onKeyDown: function onKeyDown(e) { if (this.isCtrlKeyHeldDown(e)) { this.checkAndCall('onPressKeyWithCtrl', e); } else if (this.isKeyExplicitlyHandled(e.key)) { // break up individual keyPress events to have their own specific callbacks // this allows multiple mixins to listen to onKeyDown events and somewhat reduces methodName clashing var callBack = 'onPress' + e.key; this.checkAndCall(callBack, e); } else if (this.isKeyPrintable(e.keyCode)) { this.checkAndCall('onPressChar', e); } }, // taken from http://stackoverflow.com/questions/12467240/determine-if-javascript-e-keycode-is-a-printable-non-control-character isKeyPrintable: function isKeyPrintable(keycode) { var valid = keycode > 47 && keycode < 58 || // number keys keycode === 32 || keycode === 13 || // spacebar & return key(s) (if you want to allow carriage returns) keycode > 64 && keycode < 91 || // letter keys keycode > 95 && keycode < 112 || // numpad keys keycode > 185 && keycode < 193 || // ;=,-./` (in order) keycode > 218 && keycode < 223; // [\]' (in order) return valid; }, isKeyExplicitlyHandled: function isKeyExplicitlyHandled(key) { return typeof this['onPress' + key] === 'function'; }, isCtrlKeyHeldDown: function isCtrlKeyHeldDown(e) { return e.ctrlKey === true && e.key !== 'Control'; }, checkAndCall: function checkAndCall(methodName, args) { if (typeof this[methodName] === 'function') { this[methodName](args); } } }; module.exports = KeyboardHandlerMixin; /***/ }, /* 53 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _get = __webpack_require__(54)['default']; var _inherits = __webpack_require__(60)['default']; var _createClass = __webpack_require__(69)['default']; var _classCallCheck = __webpack_require__(72)['default']; var React = __webpack_require__(18); var EditorBase = __webpack_require__(73); var SimpleTextEditor = (function (_EditorBase) { _inherits(SimpleTextEditor, _EditorBase); function SimpleTextEditor() { _classCallCheck(this, SimpleTextEditor); _get(Object.getPrototypeOf(SimpleTextEditor.prototype), 'constructor', this).apply(this, arguments); } _createClass(SimpleTextEditor, [{ key: 'render', value: function render() { return React.createElement('input', { ref: 'input', type: 'text', onBlur: this.props.onBlur, className: 'form-control', defaultValue: this.props.value }); } }]); return SimpleTextEditor; })(EditorBase); module.exports = SimpleTextEditor; /***/ }, /* 54 */ /***/ function(module, exports, __webpack_require__) { "use strict"; var _Object$getOwnPropertyDescriptor = __webpack_require__(55)["default"]; exports["default"] = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; 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 { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; exports.__esModule = true; /***/ }, /* 55 */ /***/ function(module, exports, __webpack_require__) { module.exports = { "default": __webpack_require__(56), __esModule: true }; /***/ }, /* 56 */ /***/ function(module, exports, __webpack_require__) { var $ = __webpack_require__(12); __webpack_require__(57); module.exports = function getOwnPropertyDescriptor(it, key){ return $.getDesc(it, key); }; /***/ }, /* 57 */ /***/ function(module, exports, __webpack_require__) { // 19.1.2.6 Object.getOwnPropertyDescriptor(O, P) var toIObject = __webpack_require__(58); __webpack_require__(59)('getOwnPropertyDescriptor', function($getOwnPropertyDescriptor){ return function getOwnPropertyDescriptor(it, key){ return $getOwnPropertyDescriptor(toIObject(it), key); }; }); /***/ }, /* 58 */ /***/ function(module, exports, __webpack_require__) { // to indexed object, toObject with fallback for non-array-like ES3 strings var IObject = __webpack_require__(15) , defined = __webpack_require__(14); module.exports = function(it){ return IObject(defined(it)); }; /***/ }, /* 59 */ /***/ function(module, exports, __webpack_require__) { // most Object methods by ES6 should accept primitives var $export = __webpack_require__(6) , core = __webpack_require__(8) , fails = __webpack_require__(17); 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); }; /***/ }, /* 60 */ /***/ function(module, exports, __webpack_require__) { "use strict"; var _Object$create = __webpack_require__(61)["default"]; var _Object$setPrototypeOf = __webpack_require__(63)["default"]; 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); } 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; }; exports.__esModule = true; /***/ }, /* 61 */ /***/ function(module, exports, __webpack_require__) { module.exports = { "default": __webpack_require__(62), __esModule: true }; /***/ }, /* 62 */ /***/ function(module, exports, __webpack_require__) { var $ = __webpack_require__(12); module.exports = function create(P, D){ return $.create(P, D); }; /***/ }, /* 63 */ /***/ function(module, exports, __webpack_require__) { module.exports = { "default": __webpack_require__(64), __esModule: true }; /***/ }, /* 64 */ /***/ function(module, exports, __webpack_require__) { __webpack_require__(65); module.exports = __webpack_require__(8).Object.setPrototypeOf; /***/ }, /* 65 */ /***/ function(module, exports, __webpack_require__) { // 19.1.3.19 Object.setPrototypeOf(O, proto) var $export = __webpack_require__(6); $export($export.S, 'Object', {setPrototypeOf: __webpack_require__(66).set}); /***/ }, /* 66 */ /***/ function(module, exports, __webpack_require__) { // Works with __proto__ only. Old v8 can't work with null proto objects. /* eslint-disable no-proto */ var getDesc = __webpack_require__(12).getDesc , isObject = __webpack_require__(67) , anObject = __webpack_require__(68); 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__(9)(Function.call, getDesc(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 }; /***/ }, /* 67 */ /***/ function(module, exports) { module.exports = function(it){ return typeof it === 'object' ? it !== null : typeof it === 'function'; }; /***/ }, /* 68 */ /***/ function(module, exports, __webpack_require__) { var isObject = __webpack_require__(67); module.exports = function(it){ if(!isObject(it))throw TypeError(it + ' is not an object!'); return it; }; /***/ }, /* 69 */ /***/ function(module, exports, __webpack_require__) { "use strict"; var _Object$defineProperty = __webpack_require__(70)["default"]; 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; _Object$defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); exports.__esModule = true; /***/ }, /* 70 */ /***/ function(module, exports, __webpack_require__) { module.exports = { "default": __webpack_require__(71), __esModule: true }; /***/ }, /* 71 */ /***/ function(module, exports, __webpack_require__) { var $ = __webpack_require__(12); module.exports = function defineProperty(it, key, desc){ return $.setDesc(it, key, desc); }; /***/ }, /* 72 */ /***/ function(module, exports) { "use strict"; exports["default"] = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }; exports.__esModule = true; /***/ }, /* 73 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _get = __webpack_require__(54)['default']; var _inherits = __webpack_require__(60)['default']; var _createClass = __webpack_require__(69)['default']; var _classCallCheck = __webpack_require__(72)['default']; var React = __webpack_require__(18); var ExcelColumn = __webpack_require__(42); var EditorBase = (function (_React$Component) { _inherits(EditorBase, _React$Component); function EditorBase() { _classCallCheck(this, EditorBase); _get(Object.getPrototypeOf(EditorBase.prototype), 'constructor', this).apply(this, arguments); } _createClass(EditorBase, [{ key: 'getStyle', value: function getStyle() { return { width: '100%' }; } }, { key: 'getValue', value: function getValue() { var updated = {}; updated[this.props.column.key] = this.getInputNode().value; return updated; } }, { key: 'getInputNode', value: function getInputNode() { var domNode = React.findDOMNode(this); if (domNode.tagName === 'INPUT') { return domNode; } return domNode.querySelector('input:not([type=hidden])'); } }, { key: 'inheritContainerStyles', value: function inheritContainerStyles() { return true; } }]); return EditorBase; })(React.Component); EditorBase.propTypes = { onKeyDown: React.PropTypes.func.isRequired, value: React.PropTypes.any.isRequired, onBlur: React.PropTypes.func.isRequired, column: React.PropTypes.shape(ExcelColumn).isRequired, commit: React.PropTypes.func.isRequired }; module.exports = EditorBase; /***/ }, /* 74 */ /***/ function(module, exports) { 'use strict'; var isFunction = function isFunction(functionToCheck) { var getType = {}; return functionToCheck && getType.toString.call(functionToCheck) === '[object Function]'; }; module.exports = isFunction; /***/ }, /* 75 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var PropTypes = __webpack_require__(18).PropTypes; module.exports = { selected: PropTypes.object.isRequired, copied: PropTypes.object, dragged: PropTypes.object, onCellClick: PropTypes.func.isRequired, onCellDoubleClick: PropTypes.func.isRequired, onCommit: PropTypes.func.isRequired, onCommitCancel: PropTypes.func.isRequired, handleDragEnterRow: PropTypes.func.isRequired, handleTerminateDrag: PropTypes.func.isRequired }; /***/ }, /* 76 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var React = __webpack_require__(18); var SimpleCellFormatter = React.createClass({ displayName: 'SimpleCellFormatter', propTypes: { value: React.PropTypes.oneOfType([React.PropTypes.string, React.PropTypes.number, React.PropTypes.object, React.PropTypes.bool]).isRequired }, shouldComponentUpdate: function shouldComponentUpdate(nextProps) { return nextProps.value !== this.props.value; }, render: function render() { return React.createElement( 'span', null, this.props.value ); } }); module.exports = SimpleCellFormatter; /***/ }, /* 77 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var React = __webpack_require__(18); var DOMMetrics = __webpack_require__(78); var min = Math.min; var max = Math.max; var floor = Math.floor; var ceil = Math.ceil; module.exports = { mixins: [DOMMetrics.MetricsMixin], DOMMetrics: { viewportHeight: function viewportHeight() { return React.findDOMNode(this).offsetHeight; } }, propTypes: { rowHeight: React.PropTypes.number, rowsCount: React.PropTypes.number.isRequired }, getDefaultProps: function getDefaultProps() { return { rowHeight: 30 }; }, getInitialState: function getInitialState() { return this.getGridState(this.props); }, getGridState: function getGridState(props) { var renderedRowsCount = ceil((props.minHeight - props.rowHeight) / props.rowHeight); var totalRowCount = min(renderedRowsCount * 2, props.rowsCount); return { displayStart: 0, displayEnd: totalRowCount, height: props.minHeight, scrollTop: 0, scrollLeft: 0 }; }, updateScroll: function updateScroll(scrollTop, scrollLeft, height, rowHeight, length) { var renderedRowsCount = ceil(height / rowHeight); var visibleStart = floor(scrollTop / rowHeight); var visibleEnd = min(visibleStart + renderedRowsCount, length); var displayStart = max(0, visibleStart - renderedRowsCount * 2); var displayEnd = min(visibleStart + renderedRowsCount * 2, length); var nextScrollState = { visibleStart: visibleStart, visibleEnd: visibleEnd, displayStart: displayStart, displayEnd: displayEnd, height: height, scrollTop: scrollTop, scrollLeft: scrollLeft }; this.setState(nextScrollState); }, metricsUpdated: function metricsUpdated() { var height = this.DOMMetrics.viewportHeight(); if (height) { this.updateScroll(this.state.scrollTop, this.state.scrollLeft, height, this.props.rowHeight, this.props.rowsCount); } }, componentWillReceiveProps: function componentWillReceiveProps(nextProps) { if (this.props.rowHeight !== nextProps.rowHeight || this.props.minHeight !== nextProps.minHeight) { this.setState(this.getGridState(nextProps)); } else if (this.props.rowsCount !== nextProps.rowsCount) { this.updateScroll(this.state.scrollTop, this.state.scrollLeft, this.state.height, nextProps.rowHeight, nextProps.rowsCount); } } }; /***/ }, /* 78 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var React = __webpack_require__(18); var emptyFunction = __webpack_require__(37); var shallowCloneObject = __webpack_require__(22); var contextTypes = { metricsComputator: React.PropTypes.object }; var MetricsComputatorMixin = { childContextTypes: contextTypes, getChildContext: function getChildContext() { return { metricsComputator: this }; }, getMetricImpl: function getMetricImpl(name) { return this._DOMMetrics.metrics[name].value; }, registerMetricsImpl: function registerMetricsImpl(component, metrics) { var getters = {}; var s = this._DOMMetrics; for (var _name in metrics) { if (s.metrics[_name] !== undefined) { throw new Error('DOM metric ' + _name + ' is already defined'); } s.metrics[_name] = { component: component, computator: metrics[_name].bind(component) }; getters[_name] = this.getMetricImpl.bind(null, _name); } if (s.components.indexOf(component) === -1) { s.components.push(component); } return getters; }, unregisterMetricsFor: function unregisterMetricsFor(component) { var s = this._DOMMetrics; var idx = s.components.indexOf(component); if (idx > -1) { s.components.splice(idx, 1); var _name2 = undefined; var metricsToDelete = {}; for (_name2 in s.metrics) { if (s.metrics[_name2].component === component) { metricsToDelete[_name2] = true; } } for (_name2 in metricsToDelete) { if (metricsToDelete.hasOwnProperty(_name2)) { delete s.metrics[_name2]; } } } }, updateMetrics: function updateMetrics() { var s = this._DOMMetrics; var needUpdate = false; for (var _name3 in s.metrics) { if (!s.metrics.hasOwnProperty(_name3)) continue; var newMetric = s.metrics[_name3].computator(); if (newMetric !== s.metrics[_name3].value) { needUpdate = true; } s.metrics[_name3].value = newMetric; } if (needUpdate) { for (var i = 0, len = s.components.length; i < len; i++) { if (s.components[i].metricsUpdated) { s.components[i].metricsUpdated(); } } } }, componentWillMount: function componentWillMount() { this._DOMMetrics = { metrics: {}, components: [] }; }, componentDidMount: function componentDidMount() { if (window.addEventListener) { window.addEventListener('resize', this.updateMetrics); } else { window.attachEvent('resize', this.updateMetrics); } this.updateMetrics(); }, componentWillUnmount: function componentWillUnmount() { window.removeEventListener('resize', this.updateMetrics); } }; var MetricsMixin = { contextTypes: contextTypes, componentWillMount: function componentWillMount() { if (this.DOMMetrics) { this._DOMMetricsDefs = shallowCloneObject(this.DOMMetrics); this.DOMMetrics = {}; for (var _name4 in this._DOMMetricsDefs) { if (!this._DOMMetricsDefs.hasOwnProperty(_name4)) continue; this.DOMMetrics[_name4] = emptyFunction; } } }, componentDidMount: function componentDidMount() { if (this.DOMMetrics) { this.DOMMetrics = this.registerMetrics(this._DOMMetricsDefs); } }, componentWillUnmount: function componentWillUnmount() { if (!this.registerMetricsImpl) { return this.context.metricsComputator.unregisterMetricsFor(this); } if (this.hasOwnProperty('DOMMetrics')) { delete this.DOMMetrics; } }, registerMetrics: function registerMetrics(metrics) { if (this.registerMetricsImpl) { return this.registerMetricsImpl(this, metrics); } return this.context.metricsComputator.registerMetricsImpl(this, metrics); }, getMetric: function getMetric(name) { if (this.getMetricImpl) { return this.getMetricImpl(name); } return this.context.metricsComputator.getMetricImpl(name); } }; module.exports = { MetricsComputatorMixin: MetricsComputatorMixin, MetricsMixin: MetricsMixin }; /***/ }, /* 79 */ /***/ function(module, exports) { "use strict"; module.exports = { componentDidMount: function componentDidMount() { this._scrollLeft = this.refs.viewport ? this.refs.viewport.getScroll().scrollLeft : 0; this._onScroll(); }, componentDidUpdate: function componentDidUpdate() { this._onScroll(); }, componentWillMount: function componentWillMount() { this._scrollLeft = undefined; }, componentWillUnmount: function componentWillUnmount() { this._scrollLeft = undefined; }, onScroll: function onScroll(props) { if (this._scrollLeft !== props.scrollLeft) { this._scrollLeft = props.scrollLeft; this._onScroll(); } }, _onScroll: function _onScroll() { if (this._scrollLeft !== undefined) { this.refs.header.setScrollLeft(this._scrollLeft); if (this.refs.viewport) { this.refs.viewport.setScrollLeft(this._scrollLeft); } } } }; /***/ }, /* 80 */ /***/ function(module, exports, __webpack_require__) { "use strict"; var React = __webpack_require__(18); var CheckboxEditor = React.createClass({ displayName: "CheckboxEditor", propTypes: { value: React.PropTypes.bool.isRequired, rowIdx: React.PropTypes.number.isRequired, column: React.PropTypes.shape({ key: React.PropTypes.string.isRequired, onCellChange: React.PropTypes.func.isRequired }).isRequired }, handleChange: function handleChange(e) { this.props.column.onCellChange(this.props.rowIdx, this.props.column.key, e); }, render: function render() { var checked = this.props.value != null ? this.props.value : false; return React.createElement("input", { className: "react-grid-CheckBox", type: "checkbox", checked: checked, onClick: this.handleChange, onChange: this.handleChange }); } }); module.exports = CheckboxEditor; /***/ }, /* 81 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var React = __webpack_require__(18); var ExcelColumn = __webpack_require__(42); var FilterableHeaderCell = React.createClass({ displayName: 'FilterableHeaderCell', propTypes: { onChange: React.PropTypes.func.isRequired, column: React.PropTypes.shape(ExcelColumn) }, getInitialState: function getInitialState() { return { filterTerm: '' }; }, handleChange: function handleChange(e) { var val = e.target.value; this.setState({ filterTerm: val }); this.props.onChange({ filterTerm: val, columnKey: this.props.column.key }); }, renderInput: function renderInput() { if (this.props.column.filterable === false) { return React.createElement('span', null); } var inputKey = 'header-filter-' + this.props.column.key; return React.createElement('input', { key: inputKey, type: 'text', className: 'form-control input-sm', placeholder: 'Search', value: this.state.filterTerm, onChange: this.handleChange }); }, render: function render() { return React.createElement( 'div', null, React.createElement( 'div', { className: 'form-group' }, this.renderInput() ) ); } }); module.exports = FilterableHeaderCell; /***/ }, /* 82 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _classCallCheck = __webpack_require__(72)['default']; var ColumnMetrics = __webpack_require__(23); var DOMMetrics = __webpack_require__(78); Object.assign = __webpack_require__(83); var PropTypes = __webpack_require__(18).PropTypes; var ColumnUtils = __webpack_require__(25); var React = __webpack_require__(18); var Column = function Column() { _classCallCheck(this, Column); }; module.exports = { mixins: [DOMMetrics.MetricsMixin], propTypes: { columns: PropTypes.arrayOf(Column), minColumnWidth: PropTypes.number, columnEquality: PropTypes.func }, DOMMetrics: { gridWidth: function gridWidth() { return React.findDOMNode(this).parentElement.offsetWidth; } }, getDefaultProps: function getDefaultProps() { return { minColumnWidth: 80, columnEquality: ColumnMetrics.sameColumn }; }, componentWillReceiveProps: function componentWillReceiveProps(nextProps) { if (nextProps.columns) { if (!ColumnMetrics.sameColumns(this.props.columns, nextProps.columns, this.props.columnEquality) || nextProps.minWidth !== this.props.minWidth) { var columnMetrics = this.createColumnMetrics(nextProps); this.setState({ columnMetrics: columnMetrics }); } } }, getTotalWidth: function getTotalWidth() { var totalWidth = 0; if (this.isMounted()) { totalWidth = this.DOMMetrics.gridWidth(); } else { totalWidth = ColumnUtils.getSize(this.props.columns) * this.props.minColumnWidth; } return totalWidth; }, getColumnMetricsType: function getColumnMetricsType(metrics) { var totalWidth = metrics.totalWidth || this.getTotalWidth(); var currentMetrics = { columns: metrics.columns, totalWidth: totalWidth, minColumnWidth: metrics.minColumnWidth }; var updatedMetrics = ColumnMetrics.recalculate(currentMetrics); return updatedMetrics; }, getColumn: function getColumn(idx) { var columns = this.state.columnMetrics.columns; if (Array.isArray(columns)) { return columns[idx]; } else if (typeof Immutable !== 'undefined') { return columns.get(idx); } }, getSize: function getSize() { var columns = this.state.columnMetrics.columns; if (Array.isArray(columns)) { return columns.length; } else if (typeof Immutable !== 'undefined') { return columns.size; } }, metricsUpdated: function metricsUpdated() { var columnMetrics = this.createColumnMetrics(); this.setState({ columnMetrics: columnMetrics }); }, createColumnMetrics: function createColumnMetrics() { var props = arguments.length <= 0 || arguments[0] === undefined ? this.props : arguments[0]; var gridColumns = this.setupGridColumns(props); return this.getColumnMetricsType({ columns: gridColumns, minColumnWidth: this.props.minColumnWidth, totalWidth: props.minWidth }); }, onColumnResize: function onColumnResize(index, width) { var columnMetrics = ColumnMetrics.resizeColumn(this.state.columnMetrics, index, width); this.setState({ columnMetrics: columnMetrics }); } }; /***/ }, /* 83 */ /***/ function(module, exports) { 'use strict'; function ToObject(val) { if (val == null) { throw new TypeError('Object.assign cannot be called with null or undefined'); } return Object(val); } module.exports = Object.assign || function (target, source) { var from; var keys; var to = ToObject(target); for (var s = 1; s < arguments.length; s++) { from = arguments[s]; keys = Object.keys(Object(from)); for (var i = 0; i < keys.length; i++) { to[keys[i]] = from[keys[i]]; } } return to; }; /***/ }, /* 84 */ /***/ function(module, exports) { 'use strict'; var RowUtils = { get: function get(row, property) { if (typeof row.get === 'function') { return row.get(property); } return row[property]; } }; module.exports = RowUtils; /***/ }, /* 85 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var Editors = { AutoComplete: __webpack_require__(86), DropDownEditor: __webpack_require__(88), SimpleTextEditor: __webpack_require__(53), CheckboxEditor: __webpack_require__(80) }; module.exports = Editors; /***/ }, /* 86 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var React = __webpack_require__(18); var ReactAutocomplete = __webpack_require__(87); var ExcelColumn = __webpack_require__(42); var optionPropType = React.PropTypes.shape({ id: React.PropTypes.required, title: React.PropTypes.string }); var AutoCompleteEditor = React.createClass({ displayName: 'AutoCompleteEditor', propTypes: { onCommit: React.PropTypes.func.isRequired, options: React.PropTypes.arrayOf(optionPropType).isRequired, label: React.PropTypes.any, value: React.PropTypes.any.isRequired, height: React.PropTypes.number, valueParams: React.PropTypes.arrayOf(React.PropTypes.string), column: React.PropTypes.shape(ExcelColumn).isRequired, resultIdentifier: React.PropTypes.string, search: React.PropTypes.string, onKeyDown: React.PropTypes.func }, getDefaultProps: function getDefaultProps() { return { resultIdentifier: 'id' }; }, handleChange: function handleChange() { this.props.onCommit(); }, getValue: function getValue() { var value = undefined; var updated = {}; if (this.hasResults() && this.isFocusedOnSuggestion()) { value = this.getLabel(this.refs.autoComplete.state.focusedValue); if (this.props.valueParams) { value = this.constuctValueFromParams(this.refs.autoComplete.state.focusedValue, this.props.valueParams); } } else { value = this.refs.autoComplete.state.searchTerm; } updated[this.props.column.key] = value; return updated; }, getInputNode: function getInputNode() { return this.getDOMNode().getElementsByTagName('input')[0]; }, getLabel: function getLabel(item) { var label = this.props.label != null ? this.props.label : 'title'; if (typeof label === 'function') { return label(item); } else if (typeof label === 'string') { return item[label]; } }, hasResults: function hasResults() { return this.refs.autoComplete.state.results.length > 0; }, isFocusedOnSuggestion: function isFocusedOnSuggestion() { var autoComplete = this.refs.autoComplete; return autoComplete.state.focusedValue != null; }, constuctValueFromParams: function constuctValueFromParams(obj, props) { if (!props) { return ''; } var ret = []; for (var i = 0, ii = props.length; i < ii; i++) { ret.push(obj[props[i]]); } return ret.join('|'); }, render: function render() { var label = this.props.label != null ? this.props.label : 'title'; return React.createElement( 'div', { height: this.props.height, onKeyDown: this.props.onKeyDown }, React.createElement(ReactAutocomplete, { search: this.props.search, ref: 'autoComplete', label: label, onChange: this.handleChange, resultIdentifier: this.props.resultIdentifier, options: this.props.options, value: { title: this.props.value } }) ); } }); module.exports = AutoCompleteEditor; /***/ }, /* 87 */ /***/ function(module, exports, __webpack_require__) { (function webpackUniversalModuleDefinition(root, factory) { if(true) module.exports = factory(__webpack_require__(18)); else if(typeof define === 'function' && define.amd) define(["react"], factory); else if(typeof exports === 'object') exports["ReactAutocomplete"] = factory(require("react")); else root["ReactAutocomplete"] = factory(root["React"]); })(this, function(__WEBPACK_EXTERNAL_MODULE_1__) { 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__) { /** * @jsx React.DOM */ "use strict"; var React = __webpack_require__(1); var joinClasses = __webpack_require__(2); var Autocomplete = React.createClass({ displayName: "Autocomplete", propTypes: { options: React.PropTypes.any, search: React.PropTypes.func, resultRenderer: React.PropTypes.oneOfType([React.PropTypes.component, React.PropTypes.func]), value: React.PropTypes.object, onChange: React.PropTypes.func, onError: React.PropTypes.func }, getDefaultProps: function () { return { search: searchArray }; }, getInitialState: function () { var searchTerm = this.props.searchTerm ? this.props.searchTerm : this.props.value ? this.props.value.title : ""; return { results: [], showResults: false, showResultsInProgress: false, searchTerm: searchTerm, focusedValue: null }; }, getResultIdentifier: function (result) { if (this.props.resultIdentifier === undefined) { return result.id; } else { return result[this.props.resultIdentifier]; } }, render: function () { var className = joinClasses(this.props.className, "react-autocomplete-Autocomplete", this.state.showResults ? "react-autocomplete-Autocomplete--resultsShown" : undefined); var style = { position: "relative", outline: "none" }; return React.createElement("div", { tabIndex: "1", className: className, onFocus: this.onFocus, onBlur: this.onBlur, style: style }, React.createElement("input", { ref: "search", className: "react-autocomplete-Autocomplete__search", style: { width: "100%" }, onClick: this.showAllResults, onChange: this.onQueryChange, onFocus: this.showAllResults, onBlur: this.onQueryBlur, onKeyDown: this.onQueryKeyDown, value: this.state.searchTerm }), React.createElement(Results, { className: "react-autocomplete-Autocomplete__results", onSelect: this.onValueChange, onFocus: this.onValueFocus, results: this.state.results, focusedValue: this.state.focusedValue, show: this.state.showResults, renderer: this.props.resultRenderer, label: this.props.label, resultIdentifier: this.props.resultIdentifier })); }, componentWillReceiveProps: function (nextProps) { var searchTerm = nextProps.searchTerm ? nextProps.searchTerm : nextProps.value ? nextProps.value.title : ""; this.setState({ searchTerm: searchTerm }); }, componentWillMount: function () { this.blurTimer = null; }, /** * Show results for a search term value. * * This method doesn't update search term value itself. * * @param {Search} searchTerm */ showResults: function (searchTerm) { this.setState({ showResultsInProgress: true }); this.props.search(this.props.options, searchTerm.trim(), this.onSearchComplete); }, showAllResults: function () { if (!this.state.showResultsInProgress && !this.state.showResults) { this.showResults(""); } }, onValueChange: function (value) { var state = { value: value, showResults: false }; if (value) { state.searchTerm = value.title; } this.setState(state); if (this.props.onChange) { this.props.onChange(value); } }, onSearchComplete: function (err, results) { if (err) { if (this.props.onError) { this.props.onError(err); } else { throw err; } } this.setState({ showResultsInProgress: false, showResults: true, results: results }); }, onValueFocus: function (value) { this.setState({ focusedValue: value }); }, onQueryChange: function (e) { var searchTerm = e.target.value; this.setState({ searchTerm: searchTerm, focusedValue: null }); this.showResults(searchTerm); }, onFocus: function () { if (this.blurTimer) { clearTimeout(this.blurTimer); this.blurTimer = null; } this.refs.search.getDOMNode().focus(); }, onBlur: function () { // wrap in setTimeout so we can catch a click on results this.blurTimer = setTimeout((function () { if (this.isMounted()) { this.setState({ showResults: false }); } }).bind(this), 100); }, onQueryKeyDown: function (e) { if (e.key === "Enter") { e.preventDefault(); if (this.state.focusedValue) { this.onValueChange(this.state.focusedValue); } } else if (e.key === "ArrowUp" && this.state.showResults) { e.preventDefault(); var prevIdx = Math.max(this.focusedValueIndex() - 1, 0); this.setState({ focusedValue: this.state.results[prevIdx] }); } else if (e.key === "ArrowDown") { e.preventDefault(); if (this.state.showResults) { var nextIdx = Math.min(this.focusedValueIndex() + (this.state.showResults ? 1 : 0), this.state.results.length - 1); this.setState({ showResults: true, focusedValue: this.state.results[nextIdx] }); } else { this.showAllResults(); } } }, focusedValueIndex: function () { if (!this.state.focusedValue) { return -1; } for (var i = 0, len = this.state.results.length; i < len; i++) { if (this.getResultIdentifier(this.state.results[i]) === this.getResultIdentifier(this.state.focusedValue)) { return i; } } return -1; } }); var Results = React.createClass({ displayName: "Results", getResultIdentifier: function (result) { if (this.props.resultIdentifier === undefined) { if (!result.id) { throw "id property not found on result. You must specify a resultIdentifier and pass as props to autocomplete component"; } return result.id; } else { return result[this.props.resultIdentifier]; } }, render: function () { var style = { display: this.props.show ? "block" : "none", position: "absolute", listStyleType: "none" }; var $__0 = this.props, className = $__0.className, props = (function (source, exclusion) { var rest = {};var hasOwn = Object.prototype.hasOwnProperty;if (source == null) { throw new TypeError(); }for (var key in source) { if (hasOwn.call(source, key) && !hasOwn.call(exclusion, key)) { rest[key] = source[key]; } }return rest; })($__0, { className: 1 }); return React.createElement("ul", React.__spread({}, props, { style: style, className: className + " react-autocomplete-Results" }), this.props.results.map(this.renderResult)); }, renderResult: function (result) { var focused = this.props.focusedValue && this.getResultIdentifier(this.props.focusedValue) === this.getResultIdentifier(result); var Renderer = this.props.renderer || Result; return React.createElement(Renderer, { ref: focused ? "focused" : undefined, key: this.getResultIdentifier(result), result: result, focused: focused, onMouseEnter: this.onMouseEnterResult, onClick: this.props.onSelect, label: this.props.label }); }, componentDidUpdate: function () { this.scrollToFocused(); }, componentDidMount: function () { this.scrollToFocused(); }, componentWillMount: function () { this.ignoreFocus = false; }, scrollToFocused: function () { var focused = this.refs && this.refs.focused; if (focused) { var containerNode = this.getDOMNode(); var scroll = containerNode.scrollTop; var height = containerNode.offsetHeight; var node = focused.getDOMNode(); var top = node.offsetTop; var bottom = top + node.offsetHeight; // we update ignoreFocus to true if we change the scroll position so // the mouseover event triggered because of that won't have an // effect if (top < scroll) { this.ignoreFocus = true; containerNode.scrollTop = top; } else if (bottom - scroll > height) { this.ignoreFocus = true; containerNode.scrollTop = bottom - height; } } }, onMouseEnterResult: function (e, result) { // check if we need to prevent the next onFocus event because it was // probably caused by a mouseover due to scroll position change if (this.ignoreFocus) { this.ignoreFocus = false; } else { // we need to make sure focused node is visible // for some reason mouse events fire on visible nodes due to // box-shadow var containerNode = this.getDOMNode(); var scroll = containerNode.scrollTop; var height = containerNode.offsetHeight; var node = e.target; var top = node.offsetTop; var bottom = top + node.offsetHeight; if (bottom > scroll && top < scroll + height) { this.props.onFocus(result); } } } }); var Result = React.createClass({ displayName: "Result", getDefaultProps: function () { return { label: function (result) { return result.title; } }; }, getLabel: function (result) { if (typeof this.props.label === "function") { return this.props.label(result); } else if (typeof this.props.label === "string") { return result[this.props.label]; } }, render: function () { var className = joinClasses({ "react-autocomplete-Result": true, "react-autocomplete-Result--active": this.props.focused }); return React.createElement("li", { style: { listStyleType: "none" }, className: className, onClick: this.onClick, onMouseEnter: this.onMouseEnter }, React.createElement("a", null, this.getLabel(this.props.result))); }, onClick: function () { this.props.onClick(this.props.result); }, onMouseEnter: function (e) { if (this.props.onMouseEnter) { this.props.onMouseEnter(e, this.props.result); } }, shouldComponentUpdate: function (nextProps) { return nextProps.result.id !== this.props.result.id || nextProps.focused !== this.props.focused; } }); /** * Search options using specified search term treating options as an array * of candidates. * * @param {Array.<Object>} options * @param {String} searchTerm * @param {Callback} cb */ function searchArray(options, searchTerm, cb) { if (!options) { return cb(null, []); } searchTerm = new RegExp(searchTerm, "i"); var results = []; for (var i = 0, len = options.length; i < len; i++) { if (searchTerm.exec(options[i].title)) { results.push(options[i]); } } cb(null, results); } module.exports = Autocomplete; /***/ }, /* 1 */ /***/ function(module, exports) { module.exports = __WEBPACK_EXTERNAL_MODULE_1__; /***/ }, /* 2 */ /***/ function(module, exports, __webpack_require__) { var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/*! Copyright (c) 2015 Jed Watson. Licensed under the MIT License (MIT), see http://jedwatson.github.io/classnames */ function classNames() { var classes = ''; var arg; for (var i = 0; i < arguments.length; i++) { arg = arguments[i]; if (!arg) { continue; } if ('string' === typeof arg || 'number' === typeof arg) { classes += ' ' + arg; } else if (Object.prototype.toString.call(arg) === '[object Array]') { classes += ' ' + classNames.apply(null, arg); } else if ('object' === typeof arg) { for (var key in arg) { if (!arg.hasOwnProperty(key) || !arg[key]) { continue; } classes += ' ' + key; } } } return classes.substr(1); } // safely export classNames for node / browserify if (typeof module !== 'undefined' && module.exports) { module.exports = classNames; } // safely export classNames for RequireJS if (true) { !(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_RESULT__ = function() { return classNames; }.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); } /***/ } /******/ ]) }); ; /***/ }, /* 88 */ /***/ function(module, exports, __webpack_require__) { /** * @jsx React.DOM */ 'use strict'; var _get = __webpack_require__(54)['default']; var _inherits = __webpack_require__(60)['default']; var _createClass = __webpack_require__(69)['default']; var _classCallCheck = __webpack_require__(72)['default']; var React = __webpack_require__(18); var EditorBase = __webpack_require__(73); var DropDownEditor = (function (_EditorBase) { _inherits(DropDownEditor, _EditorBase); function DropDownEditor() { _classCallCheck(this, DropDownEditor); _get(Object.getPrototypeOf(DropDownEditor.prototype), 'constructor', this).apply(this, arguments); } _createClass(DropDownEditor, [{ key: 'getInputNode', value: function getInputNode() { return React.findDOMNode(this); } }, { key: 'onClick', value: function onClick() { this.getInputNode().focus(); } }, { key: 'onDoubleClick', value: function onDoubleClick() { this.getInputNode().focus(); } }, { key: 'render', value: function render() { return React.createElement( 'select', { style: this.getStyle(), defaultValue: this.props.value, onBlur: this.props.onBlur, onChange: this.onChange }, this.renderOptions() ); } }, { key: 'renderOptions', value: function renderOptions() { var options = []; this.props.options.forEach(function (name) { options.push(React.createElement( 'option', { key: name, value: name }, name )); }, this); return options; } }]); return DropDownEditor; })(EditorBase); DropDownEditor.propTypes = { options: React.PropTypes.arrayOf(React.PropTypes.string).isRequired }; module.exports = DropDownEditor; /***/ }, /* 89 */ /***/ function(module, exports, __webpack_require__) { // not including this // it currently requires the whole of moment, which we dont want to take as a dependency 'use strict'; var ImageFormatter = __webpack_require__(90); var Formatters = { ImageFormatter: ImageFormatter }; module.exports = Formatters; /***/ }, /* 90 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var React = __webpack_require__(18); var PendingPool = {}; var ReadyPool = {}; var ImageFormatter = React.createClass({ displayName: 'ImageFormatter', propTypes: { value: React.PropTypes.string.isRequired }, getInitialState: function getInitialState() { return { ready: false }; }, componentWillMount: function componentWillMount() { this._load(this.props.value); }, componentWillReceiveProps: function componentWillReceiveProps(nextProps) { if (nextProps.value !== this.props.value) { this.setState({ value: null }); this._load(nextProps.value); } }, _load: function _load(src) { var imageSrc = src; if (ReadyPool[imageSrc]) { this.setState({ value: imageSrc }); return; } if (PendingPool[imageSrc]) { PendingPool[imageSrc].push(this._onLoad); return; } PendingPool[imageSrc] = [this._onLoad]; var img = new Image(); img.onload = function () { PendingPool[imageSrc].forEach(function (callback) { callback(imageSrc); }); delete PendingPool[imageSrc]; img.onload = null; imageSrc = undefined; }; img.src = imageSrc; }, _onLoad: function _onLoad(src) { if (this.isMounted() && src === this.props.value) { this.setState({ value: src }); } }, render: function render() { var style = this.state.value ? { backgroundImage: 'url(' + this.state.value + ')' } : undefined; return React.createElement('div', { className: 'react-grid-image', style: style }); } }); module.exports = ImageFormatter; /***/ }, /* 91 */ /***/ function(module, exports, __webpack_require__) { /** * @jsx React.DOM */ "use strict"; var React = __webpack_require__(18); var Toolbar = React.createClass({ displayName: "Toolbar", propTypes: { onAddRow: React.PropTypes.func, onToggleFilter: React.PropTypes.func.isRequired, enableFilter: React.PropTypes.bool, numberOfRows: React.PropTypes.number.isRequired }, onAddRow: function onAddRow() { if (this.props.onAddRow !== null && this.props.onAddRow instanceof Function) { this.props.onAddRow({ newRowIndex: this.props.numberOfRows }); } }, getDefaultProps: function getDefaultProps() { return { enableAddRow: true }; }, renderAddRowButton: function renderAddRowButton() { if (this.props.onAddRow) { return React.createElement( "button", { type: "button", className: "btn", onClick: this.onAddRow }, "Add Row" ); } }, renderToggleFilterButton: function renderToggleFilterButton() { if (this.props.enableFilter) { return React.createElement( "button", { type: "button", className: "btn", onClick: this.props.onToggleFilter }, "Filter Rows" ); } }, render: function render() { return React.createElement( "div", { className: "react-grid-Toolbar" }, React.createElement( "div", { className: "tools" }, this.renderAddRowButton(), this.renderToggleFilterButton() ) ); } }); module.exports = Toolbar; /***/ } /******/ ]) }); ;
/************************************************************************************************* The MIT License (MIT) Copyright (c) 2015 THOMAS FORD 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. AUTHOR: Thomas Ford DATE: 3/21/2015 http://jinqJs.com ------------------------------------------------------------------------------------------ DATE: 3/23/15 VERSION: .1.1 NOTE: Added leftJoin(), avg(), and predicate for on(). DATE: 3/26/15 VERSION: .1.2 NOTE: Minor corrections DATE: 3/30/15 VERSION .1.3 NOTE: Added ability to sort asc/desc on plain arrays concat() and union() DATE: 4/1/15 VERSION: .1.4 NOTE: Added support for positional for orderBy and Select on {field: #} objects DATE: 4/2/15 VERSION: .1.5 NOTE: Added ability to join() on() collections with simple arrays DATE: 4/3/15 VESION: .1.6 NOTE: Added index as 2nd parameter for .where() and .select() Added .not(), .in() DATE: 4/4/15 VERSION 1.00 NOTE: Added ability to do .distinct(), .max(),. min(), .avg() on simple arrays. Added ability to union simple arrays. .in() can except multiple columns to compare to. If .orderBy() uses positional, then all fields ordered must be positional Added support for .identity() on simple arrays. When on simple arrays the value gets set to a "Value" column by default. Included unit tests DATE: 4/11/15 VERSION 1.13 NOTE: Made various performance improvements. Added new ability to perform Full Joins using .fullJoin() <-- Only String columns, no expressions Added new function .skip(). Added support for strong type comparison === and !== in .where() when using expressions. Fixed an issue with the .not().in() function not properly working when using multiple columns. DATE: 4/13/15 VERSION 1.2a NOTE: Added new function jinqJs.addPlugin() to allow extensibility. See API documentation. DATE: 4/13/15 VERSION 1.3 NOTE: Added module jinqJs to support node.js. DATE: 7/12/15 VERSION 1.4 NOTE: Added the ability to support a single parameter as an array of fields for the distinct(). Thank you to jinhduong for contributing and your recommendation. DATE: 8/1/15 VERSION: 1.5 NOTE: .Did some code refactoring for getExpression() and isTruthy() functions. .Added new function filter(), filter() function is synonymous to the where() function. The filter() is just a refernce to the where() and can be used interchangeably. .Added ability to now update rows inside an array. The update does an in-place update (Referencing the original array), it is not necessary to execute the select() when only performing an update on the array. New functions update() and at() have been added. DATE: 8/3/15 VERSION: 1.5.1 NOTE: Added .delete() for deleting records when the .at() is true. DATE: 8/12/15 VERSION: 1.5.2 NOTE: Changed the .at() and .update() predicates first parameter not to be a row object, but the array instead. The two parameters passed to the delegate are now (collection, index). This was changed due to an issue when trying to update simple arrays i.e. [1,2,3,4,5], since they are not object types they were not getting updated. DATE: 11/24/15 VERSION: 1.5.3 NOTE: Added support for TYpeScript definition file. DATE: 11/24/15 VERSION: 1.5.3 NOTE: Added support for TYpeScript definition file. DATE: 12/5/15 VERSION: 1.5.6 NOTE: Fixed bug when R-Value of an expression contained spaces. DATE: 1/3/16 VERSION: 1.5.9 NOTE: Added jinqJs service for Angular 1.x DATE: 5/14/16 VERSION: 1.6.0 NOTE: Thanks to gpminsuk for recommending a change to isObject() you can now perform a select on an array that contains arrays. For example: .from([[1,2,3],[4,5,6]]).select(2) Will return the second element of each of the arrays in the root array. DATE 9/18/16 VERSION: 1.6.1 Thanks to gpminsuk for finding an issue when a propery in a collection had a 0 value, a null was returned! See Issue #16 Thanks to pascalberge, moved the jinqJs definition file to scripts\typings\jinqJs. Thanks to pemn, for finding if a collection has been added using a from() and then later .delete().at() is called with no parameters, the internal variable collections is not being cleared. Thanks to ninety7 for suggesting using string.localeCompare() for ordering. *************************************************************************************************/ var jinqJs = function (settings) { 'use strict'; /* Private Variables */ var collections = [], result = [], groups = [], notted = false, identityUsed = false, delegateUpdate = null, deleteFlag = false, operators = { LessThen: 0, LessThenEqual: 1, GreaterThen: 2, GreaterThenEqual: 3, Equal: 4, EqualEqualType: 5, NotEqual: 6, NotEqualEqualType: 7, Contains: 8 }, storage = {}; jinqJs.settings = jinqJs.settings || {}; /* Constructor Code */ if (typeof settings !== 'undefined') { jinqJs.settings = settings; } else { jinqJs.settings = { includeIdentity: jinqJs.settings.includeIdentity || false }; } /* Private Methods (no prefix) */ var isEmpty = function (array) { return (typeof array === 'undefined' || array.length === 0); }, isArray = function (array) { return (hasProperty(array, 'length') && !isString(array) && !isFunction(array)); }, isObject = function (obj) { return (obj !== null && (obj.constructor === Object || isArray(obj))); }, isString = function (str) { return (str !== null && str.constructor === String); }, hasProperty = function (obj, property) { return obj[property] !== undefined; }, isFunction = function (func) { return (typeof func === 'function'); }, isNumber = function (value) { return typeof value === 'number'; }, arrayItemFieldValueExists = function (collection, field, value) { for (var index = 0; index < collection.length; index++) { if (collection[index][field] === value) return true; } return false; }, arrayFindFirstItem = function (collection, obj) { return arrayFindItem(collection, obj, true); }, arrayFindItem = function (collection, obj, findFirst) { var row = null; var isMatch = false; var ret = []; var isObj = false; findFirst = findFirst || false; for (var index = 0; index < collection.length; index++) { isMatch = false; for (var field in obj) { row = collection[index]; isObj = isObject(row); if ((!isObj && row != obj[field]) || (isObj && row[field] != obj[field])) { isMatch = false; break; } isMatch = true; } if (isMatch) { if (findFirst) return row; else ret.push(row); } } return (ret.length === 0 ? null : ret); }, condenseToFields = function (obj, fields) { var newObj = {}; var field = null; for (var index = 0; index < fields.length; index++) { field = fields[index]; if (hasProperty(obj, field)) newObj[field] = obj[field]; else newObj[field] = 0; } return newObj; }, aggregator = function (args, predicate) { var collection = []; var keys = null; var values = null; var row = null; for (var index = 0; index < result.length; index++) { keys = condenseToFields(result[index], groups); values = condenseToFields(result[index], args); row = arrayFindFirstItem(collection, keys); if (row === null) { row = {}; for (var keyField in keys) row[keyField] = keys[keyField]; for (var valField in values) row[valField] = predicate(row[valField], values[valField], JSON.stringify(keys) + valField); collection.push(row); } else { for (var vField in values) { row[vField] = predicate(row[vField], result[index][vField], JSON.stringify(keys) + vField); } } } groups = []; return collection; }, orderByComplex = function (complexFields) { var complex = null; var prior = null; var field = null; var firstField = null; var secondField = null; var priorFirstField = null; var priorSecondField = null; var order = 1; var isNumField = false; for (var index = 0; index < complexFields.length; index++) { prior = (index > 0 ? complexFields[index - 1] : null); complex = complexFields[index]; field = (hasProperty(complex, 'field') ? complex.field : null); order = (hasProperty(complex, 'sort') && complex.sort === 'desc' ? -1 : 1); isNumField = (field !== null && !isNaN(field) ? true : false); result.sort(function (first, second) { var lValueIsLess = false; var lValueIsGreater = false; var lValue = null; var rValue = null; if (isNumField) { firstField = Object.keys(first)[field]; secondField = Object.keys(second)[field]; if (prior !== null) { priorFirstField = Object.keys(first)[prior.field]; priorSecondField = Object.keys(second)[prior.field]; } } else { firstField = secondField = field; if (prior !== null) priorFirstField = priorSecondField = prior.field; } lValue = (field === null ? first : (isNaN(first[firstField]) ? first[firstField] : Number(first[firstField]))); rValue = (field === null ? second : (isNaN(second[secondField]) ? second[secondField] : Number(second[secondField]))); if (isString(lValue) && isString(rValue)){ var localeComparison = lValue.localeCompare(rValue); switch(localeComparison){ case -1: lValueIsLess = true; break; case 1: lValueIsGreater = true; break; } } else { lValueIsLess = lValue < rValue; lValueIsGreater = lValue > rValue; } if (lValueIsLess && (prior === null || (field === null || first[priorFirstField] == second[priorSecondField]))) return -1 * order; if (lValueIsGreater && (prior === null || (field === null || first[priorFirstField] == second[priorSecondField]))) return 1 * order; return 0; } ); } }, flattenCollection = function (collection) { //This is done for optimal performance switch (collection.length) { case 1: return collection[0].concat(); case 2: return [].concat(collection[0], collection[1]); case 3: return [].concat(collection[0], collection[1], collection[2]); case 4: return [].concat(collection[0], collection[1], collection[2], collection[3]); case 5: return [].concat(collection[0], collection[1], collection[2], collection[3], collection[4]); default: var flatCollection = []; for (var index = 0; index < collection.length; index++) flatCollection = flatCollection.concat(collection[index]); return flatCollection; } }, /* Possible future use */ pluckRowByMissingField = function (collection, args) { var ret = []; var bIsMissing = false; if (args.length === 0) return collection; for (var index = 0; index < collection.length; index++) { bIsMissing = false; for (var iArg = 0; iArg < args.length; iArg++) { if (!hasProperty(collection[index], args[iArg])) { bIsMissing = true; break; } } if (!bIsMissing) ret.push(collection[index]); } return ret; }, mergeObjectsFields = function (objects) { var obj = {}; for (var index = 0; index < objects.length; index++) { for (var prop in objects[index]) { obj[prop] = objects[index][prop]; } } return obj; }, convertToEmptyObject = function (obj) { var o = {}; for (var field in obj) o[field] = ''; return o; }, convertToOperatorEnum = function (operator) { switch (operator) { case '<': return operators.LessThen; case '>': return operators.GreaterThen; case '!=': return operators.NotEqual; case '!==': return operators.NotEqualEqualType; case '=': case '==': return operators.Equal; case '===': return operators.EqualEqualType; case '<=': return operators.LessThenEqual; case '>=': return operators.GreaterThenEqual; case '*': return operators.Contains; default: throw 'Invalid Expression!'; } }, convertToFieldArray = function (obj) { var array = []; for (var field in obj) { array.push({ field: field }); } return array; }, isNode = function() { return (typeof module !== 'undefined' && typeof module.exports !== 'undefined'); }, onFromJoin = function (joinType, comparers) { var row = null; var ret = []; var matches = null; var collection = []; var startIndex = 1; if (!isArray(comparers) || comparers.length === 0 || collections.length === 0) return; switch (joinType) { case 'from': //If we have just one pending collection then just return it, there is nothing to join it with if (collections.length === 1) { result = collections[0]; return; } collection = collections[0]; break; case 'full': case 'inner': case 'left': collection = result; startIndex = 0; break; default: return; } for (var index = startIndex; index < collections.length; index++) { ret = []; collection.forEach(function (lItem) { if (isFunction(comparers[0])) { matches = []; collections[index].forEach(function (item) { if (comparers[0](lItem, item)) matches.push(item); } ); //This condition is used to handle left joins with a predicate if (matches.length === 0) { matches = null; } } else { row = condenseToFields(lItem, comparers); matches = arrayFindItem(collections[index], row); } if (matches !== null) { if (isString(matches[0])) ret.push(lItem); else { matches.forEach(function (rItem) { ret.push(mergeObjectsFields([rItem, lItem])); }); } } else { if (joinType === 'left' || joinType === 'full') { if (collections[index].length > 0) { //The order of merging objects is important here, right -> left row = convertToEmptyObject(collections[index][0]); row = mergeObjectsFields([row, lItem]); } ret.push(mergeObjectsFields([lItem, row])); } } }); //Next get the elements on the right that are not in the result if (joinType === 'full') { var z = new jinqJs().from(collections[index]).not().in(ret, comparers).select(convertToFieldArray(ret[0])); ret = ret.concat(z); } collection = ret; } collections = []; result = ret; }, joinIt = function (joinType, args) { if (args.length === 0) return this; collections = []; collections.func = joinType; for (var index = 0; index < args.length; index++) { if (args[index].length > 0) //Could be a url string here or an array here. Length is ok to use either way collections.push(args[index]); } }, nodeServiceCall = function(self, url, callback){ var http = require("http"); http.get(url, function(response){ var content = ''; response.on('data', function(data){ content += data; }); response.on('end', function() { var data = JSON.parse(content); var collection = null; if (isArray(data)) collection = data; else collection = new Array(data); collections.push(collection); result = collection; if (isFunction(callback)) callback(self); }); }); }, browserServiceCall = function(self, url, callback){ var xmlhttp = new XMLHttpRequest(); var collection = null; if (isFunction(callback)) { xmlhttp.onreadystatechange = function () { if (xmlhttp.response.length === 0) return; var response = JSON.parse(xmlhttp.response); if (isArray(response)) collection = response; else collection = new Array(response); collections.push(collection); result = collection; callback(self); }; } xmlhttp.open("GET", url, isFunction(callback)); xmlhttp.send(); if (!isFunction(callback)) { var response = JSON.parse(xmlhttp.response); if (isArray(response)) collection = response; else collection = new Array(response); collections.push(collection); } }, getExpressions = function(args){ var regExpr = /([^\s]+)\s(<|>|!=|!==|=|==|===|<=|>=|\*)\s(.+)/; var argLen = args.length; var expr = new Array(argLen); for (var eIndex = 0; eIndex < argLen; eIndex++) { var matches = args[eIndex].match(regExpr); if (matches.length !== 4) throw ('Invalid expression!'); expr[eIndex] = { lField: matches[1], operator: convertToOperatorEnum(matches[2]), rValue: matches[3] }; } return expr; }, isTruthy = function(row, expr){ switch (expr.operator) { case operators.EqualEqualType: return (row[expr.lField] === expr.rValue); case operators.NotEqualEqualType: return (row[expr.lField] !== expr.rValue); case operators.LessThen: return (row[expr.lField] < expr.rValue); case operators.GreaterThen: return (row[expr.lField] > expr.rValue); case operators.NotEqual: return (row[expr.lField] != expr.rValue); case operators.Equal: return (row[expr.lField] == expr.rValue); case operators.LessThenEqual: return (row[expr.lField] <= expr.rValue); case operators.GreaterThenEqual: return (row[expr.lField] >= expr.rValue); case operators.Contains: return (row[expr.lField].indexOf(expr.rValue) > -1); default: return false; } }; /* Exposed Methods (prefixed with _) */ var _from = function () { var collection = null; var callback = null; if (arguments.length === 0) return this; result = []; for (var index = 0; index < arguments.length; index++) { if (arguments[index] === null || arguments[index].length === 0) continue; if (arguments.length == 2 && isFunction(arguments[1])) { collection = arguments[0]; callback = arguments[1]; index = arguments.length; } else { collection = arguments[index]; //Check for a callback function we dont support asyn callbacks with multiple tables if (isFunction(collection)) continue; } if (isString(collection)) { if (!isNode()) browserServiceCall(this, collection, callback); else nodeServiceCall(this, collection, callback); } else { collections.push(collection); } } collections.func = 'from'; result = flattenCollection(collections); return (isFunction(callback) ? callback : this); }, _select = function () { var fields = null; var fieldIsObject = false; var fieldIsPredicate = false; var collection = null; if (isEmpty(result)) return []; var obj = null; var srcFieldName = null; var dstFieldName = null; var isSimple = false; var fieldDefs = null; if (jinqJs.settings.includeIdentity && !identityUsed) { _identity(); } if (isEmpty(arguments)) { return result; } collection = new Array(result.length); //Check if an Array of objects is passed in as first parameter if (isArray(arguments[0])) { fields = arguments[0]; fieldIsObject = true; fieldDefs = new Array(fields.length); for (var fIndex = 0; fIndex < fields.length; fIndex++) { fieldDefs[fIndex] = { hasField: hasProperty(fields[fIndex], 'field'), hasText: hasProperty(fields[fIndex], 'text'), hasValue: hasProperty(fields[fIndex], 'value'), }; } } else if (isFunction(arguments[0])) { fields = arguments[0]; fieldIsPredicate = true; } else { fields = arguments; } isSimple = !isObject(result[0]); //It cant be empty if I got here for (var index = 0; index < result.length; index++) { if (fieldIsPredicate) { collection[index] = fields(result[index], index); } else { obj = {}; for (var field = 0; field < fields.length; field++) { if (fieldIsObject) { if (fieldDefs[field].hasField) { if (!isNumber(fields[field].field)) srcFieldName = fields[field].field; else srcFieldName = Object.keys(result[index])[fields[field].field]; } dstFieldName = (fieldDefs[field].hasText ? fields[field].text : fields[field].field); } else { dstFieldName = srcFieldName = fields[field]; } if (fieldIsObject && fieldDefs[field].hasValue) { if (isFunction(fields[field].value)) obj[dstFieldName] = fields[field].value(result[index]); else obj[dstFieldName] = fields[field].value; } else { obj[dstFieldName] = (isSimple ? result[index] : (result[index][srcFieldName] === 0 ? 0 : result[index][srcFieldName] || null) ); } } collection[index] = obj; } } return collection; }, _update = function(predicate) { if (deleteFlag) throw ('A pending delete operation exists!'); if (typeof predicate === 'undefined' || !isFunction(predicate)) return this; delegateUpdate = predicate; return this; }, _delete = function() { if (delegateUpdate !== null) throw ('A pending update operation exists!'); deleteFlag = true; return this; }, _at = function() { var resLen = result.length; var expr = null; var isPredicateFunc = false; var isTruthfull = false; var argLen = arguments.length; if ( (delegateUpdate === null && !deleteFlag) || resLen === 0) return this; //Check if this is just clearing all data if (deleteFlag && argLen === 0) { result = []; collections = []; delegateUpdate = null; deleteFlag = false; return this; } if (argLen > 0){ isPredicateFunc = isFunction(arguments[0]); if (!isPredicateFunc) { expr = getExpressions(arguments); } } for (var index = resLen-1; index > -1; index--) { if (isPredicateFunc) { if (arguments[0](result, index)) { if (deleteFlag) result.splice(index,1); else delegateUpdate(result, index); } } else if (argLen === 0) { if (deleteFlag) result.splice(index,1); else delegateUpdate(result, index); } else { for (var arg = 0; arg < argLen; arg++) { isTruthfull = isTruthy(result[index], expr[arg]); if (!isTruthfull) break; } if (isTruthfull) { if (deleteFlag) result.splice(index,1); else delegateUpdate(result, index); } } } delegateUpdate = null; deleteFlag = false; return this; }, _concat = function () { collections.func = null; for (var index = 0; index < arguments.length; index++) result = result.concat(arguments[index]); return this; }, _top = function (amount) { var totalRows = 0; //Check for a percentage if (amount > -1 && amount < 1) { totalRows = result.length * amount; } else totalRows = amount; if (amount < 0) { result = result.slice(totalRows, (result.length - Math.abs(totalRows) * -1)); } else result = result.slice(0, totalRows); return this; }, _bottom = function (amount) { _top(amount * -1); return this; }, _where = function (predicate) { var collection = []; var isPredicateFunc = false; var isTruthfull = false; var argLen = arguments.length; var resLen = result.length; var expr = null; var row = null; if (typeof predicate === 'undefined') return this; isPredicateFunc = isFunction(predicate); if (!isPredicateFunc) { expr = getExpressions(arguments); } for (var index = 0; index < resLen; index++) { row = result[index]; if (isPredicateFunc) { if (predicate(row, index)) collection.push(row); } else { for (var arg = 0; arg < argLen; arg++) { isTruthfull = isTruthy(row, expr[arg]); if (!isTruthfull) break; } if (isTruthfull) collection.push(row); } } result = collection; return this; }, _distinct = function () { var collection = []; var row = null; var field = null; var index = 0; var len = result.length; var collSize = 0; var dupp = false; if (arguments.length === 0) { if (isObject(result[0])) { for (index = 0; index < len; index++) { dupp = false; for (var i = 0; i < collSize; i++) { if (result[index] !== collection[i]) continue; dupp = true; break; } if (!dupp) collection[collSize++] = result[index]; } } else { var obj = {}; for (index = 0; index !== len; index++) { row = result[index]; if (obj[row] !== 1) { obj[row] = 1; collection[collection.length] = row; } } } } else { var argsDistinct = arguments; if (Array.isArray(arguments[0])) argsDistinct = arguments[0]; for (index = 0; index < len; index++) { row = condenseToFields(result[index], argsDistinct); for (var fieldIndex = 0; fieldIndex < argsDistinct.length; fieldIndex++) { field = argsDistinct[fieldIndex]; if (!arrayItemFieldValueExists(collection, field, row[field])) { collection.push(row); break; } } } } result = collection; return this; }, _groupBy = function () { groups = arguments; return this; }, _sum = function () { var sum = {}; if (groups.length === 0) { sum = 0; for (var index = 0; index < result.length; index++) sum += (arguments.length === 0 ? result[index] : result[index][arguments[0]]); result = [sum]; } else { result = aggregator(arguments, function (lValue, rValue, keys) { var key = keys;//JSON.stringify(keys); if (!hasProperty(sum, key)) sum[key] = 0; return sum[key] += rValue; }); } return this; }, _avg = function () { var avg = {}; if (groups.length === 0) { avg = 0; for (var index = 0; index < result.length; index++) avg += (arguments.length === 0 ? result[index] : result[index][arguments[0]]); result = [avg / result.length]; } else { result = aggregator(arguments, function (lValue, rValue, keys) { var key = JSON.stringify(keys); if (!hasProperty(avg, key)) avg[key] = { count: 0, sum: 0 }; avg[key].count++; avg[key].sum += rValue; return avg[key].sum / avg[key].count; }); } return this; }, _count = function () { var total = {}; result = aggregator(arguments, function (lValue, rValue, keys) { var key = JSON.stringify(keys); if (!hasProperty(total, key)) total[key] = 0; return ++total[key]; }); return this; }, _min = function () { var minValue = {}; var value = 0; if (groups.length === 0) { minValue = -1; for (var index = 0; index < result.length; index++) { value = (arguments.length === 0 ? Number(result[index]) : Number(result[index][arguments[0]])); minValue = (value < minValue || minValue === -1 ? value : minValue); } result = [minValue]; } else { result = aggregator(arguments, function (lValue, rValue, keys) { var key = JSON.stringify(keys); if (!hasProperty(minValue, key)) minValue[key] = 0; if (minValue[key] === 0 || rValue < minValue[key]) minValue[key] = rValue; return minValue[key]; }); } return this; }, _max = function () { var maxValue = {}; var value = 0; if (groups.length === 0) { maxValue = -1; for (var index = 0; index < result.length; index++) { value = (arguments.length === 0 ? Number(result[index]) : Number(result[index][arguments[0]])); maxValue = (value > maxValue || maxValue === -1 ? value : maxValue); } result = [maxValue]; } else { result = aggregator(arguments, function (lValue, rValue, keys) { var key = JSON.stringify(keys); if (!hasProperty(maxValue, key)) maxValue[key] = 0; if (rValue > maxValue[key]) maxValue[key] = rValue; return maxValue[key]; }); } return this; }, _identity = function () { var id = 1; var label = (arguments.length === 0 ? 'ID' : arguments[0]); var isSimple = (result.length > 0 && !isObject(result[0])); var ret = []; var obj = null; identityUsed = true; for (var index = 0; index < result.length; index++) { if (isSimple) { obj = {}; obj[label] = id++; obj.Value = result[index]; ret.push(obj); } else result[index][label] = id++; } if (isSimple) result = ret; return this; }, _orderBy = function () { var fields = arguments; if (arguments.length > 0 && isArray(arguments[0])) { orderByComplex(arguments[0]); return this; } result.sort(function (first, second) { //0 Equals //-1 Less then //1 Greater then var firstFields = JSON.stringify(condenseToFields(first, fields)); var secondFields = JSON.stringify(condenseToFields(second, fields)); return firstFields.localeCompare(secondFields); }); return this; }, _union = function () { if (arguments.length === 0 || !isArray(arguments[0]) || arguments[0].length === 0) return this; if (!isObject(arguments[0][0])) { for (var index = 0; index < arguments.length; index++) _concat(arguments[index]); _distinct(); } else { var collection = flattenCollection(arguments); _concat(collection); groups = []; for (var field in arguments[0][0]) groups.push(field); _count(); } return this; }, _on = function () { if (arguments.length === 0 || !hasProperty(collections, 'func')) return this; onFromJoin(collections.func, arguments); collections.func = null; return this; }, _in = function () { var ret = []; var outerField = null; var innerField = null; var match = false; var fields = []; var collection = null; if (arguments.length === 0) return this; collection = arguments[0]; if (collection.length === 0 || result.length === 0) return this; var isInnerSimple = !isObject(collection[0]); var isOuterSimple = !isObject(result[0]); if ((!isInnerSimple || !isOuterSimple) && arguments.length < 2) throw 'Invalid field or missing field!'; if (arguments.length < 2) fields = [0]; //Just a dummy position holder else { if (isArray(arguments[1])) fields = arguments[1]; else { for (var i = 1; i < arguments.length; i++) fields.push(arguments[i]); } } var matches = 0; for (var outer = 0; outer < result.length; outer++) { for (var inner = 0; inner < collection.length; inner++) { matches = 0; for (var index = 0; index < fields.length; index++) { outerField = (isOuterSimple ? result[outer] : result[outer][fields[index]]); innerField = (isInnerSimple ? collection[inner] : collection[inner][fields[index]]); match = (outerField === innerField); if (match) matches++; } if (matches === fields.length) break; } if ((inner < collection.length && !notted) || (inner === collection.length && notted)) ret.push(result[outer]); } notted = false; result = ret; return this; }, _join = function () { joinIt('inner', arguments); return this; }, _leftJoin = function () { joinIt('left', arguments); return this; }, _fullJoin = function () { joinIt('full', arguments); return this; }, _not = function () { notted = true; return this; }, _skip = function () { var totalRows = 0; if (arguments.length === 0 || !isNumber(arguments[0])) return this; //Check for a percentage var amount = arguments[0]; if (amount > -1 && arguments[0] < 1) { totalRows = result.length * amount; } else totalRows = amount; result = result.slice(totalRows); return this; }; //Globals this.from = _from; this.select = _select; this.update = _update; this.top = _top; this.bottom = _bottom; this.where = _where; this.distinct = _distinct; this.groupBy = _groupBy; this.sum = _sum; this.count = _count; this.min = _min; this.max = _max; this.avg = _avg; this.identity = _identity; this.orderBy = _orderBy; this.on = _on; this.join = _join; this.leftJoin = _leftJoin; this.fullJoin = _fullJoin; this.concat = _concat; this.union = _union; this.not = _not; this.in = _in; this.skip = _skip; this.filter = _where; this.at = _at; this.delete = _delete; this._x = function(name, args, plugin){ storage[name] = storage[name] || {}; return plugin.call(this, result, args, storage[name]); }; }; (function() { 'use strict'; jinqJs.addPlugin = function(name, plugin) { jinqJs.prototype[name] = function() {return this._x(name, arguments, plugin);}; }; //node.js if (typeof module !== 'undefined' && typeof module.exports !== 'undefined') module.exports = jinqJs; if (typeof angular !== 'undefined'){ angular.module('angular-jinqjs', []).service('$jinqJs', function() {return new jinqJs(); }); } })();
/*! * JavaScript Custom Forms : Radio Module * * Copyright 2014 PSD2HTML (http://psd2html.com) * Released under the MIT license (LICENSE.txt) * * Version: 1.0.2 */ ;(function($, window) { 'use strict'; jcf.addModule({ name: 'Radio', selector: 'input[type="radio"]', options: { wrapNative: true, checkedClass: 'jcf-checked', uncheckedClass: 'jcf-unchecked', labelActiveClass: 'jcf-label-active', fakeStructure: '<span class="jcf-radio"><span></span></span>' }, matchElement: function(element) { return element.is(':radio'); }, init: function(options) { this.initStructure(); this.attachEvents(); this.refresh(); }, initStructure: function() { // prepare structure this.doc = $(document); this.realElement = $(this.options.element); this.fakeElement = $(this.options.fakeStructure).insertAfter(this.realElement); this.labelElement = this.getLabelFor(); if(this.options.wrapNative) { // wrap native radio inside fake block this.realElement.prependTo(this.fakeElement).css({ position: 'absolute', opacity: 0 }); } else { // just hide native radio this.realElement.addClass(this.options.hiddenClass); } }, attachEvents: function() { // add event handlers this.realElement.on({ focus: this.onFocus, click: this.onRealClick }); this.fakeElement.on('click', this.onFakeClick); this.fakeElement.on('jcf-pointerdown', this.onPress); }, onRealClick: function(e) { // redraw current radio and its group (setTimeout handles click that might be prevented) var self = this; this.savedEventObject = e; setTimeout(function() { self.refreshRadioGroup(); }, 0); }, onFakeClick: function(e) { // skip event if clicked on real element inside wrapper if(this.options.wrapNative && this.realElement.is(e.target)) { return; } // toggle checked class if(!this.realElement.is(':disabled')) { delete this.savedEventObject; this.currentActiveRadio = this.getCurrentActiveRadio(); this.stateChecked = this.realElement.prop('checked'); this.realElement.prop('checked', true); this.fireNativeEvent(this.realElement, 'click'); if(this.savedEventObject && this.savedEventObject.isDefaultPrevented()) { this.realElement.prop('checked', this.stateChecked); this.currentActiveRadio.prop('checked', true); } else { this.fireNativeEvent(this.realElement, 'change'); } delete this.savedEventObject; } }, onFocus: function() { if(!this.pressedFlag || !this.focusedFlag) { this.focusedFlag = true; this.fakeElement.addClass(this.options.focusClass); this.realElement.on('blur', this.onBlur); } }, onBlur: function() { if(!this.pressedFlag) { this.focusedFlag = false; this.fakeElement.removeClass(this.options.focusClass); this.realElement.off('blur', this.onBlur); } }, onPress: function(e) { if(!this.focusedFlag && e.pointerType === 'mouse') { this.realElement.focus(); } this.pressedFlag = true; this.fakeElement.addClass(this.options.pressedClass); this.doc.on('jcf-pointerup', this.onRelease); }, onRelease: function(e) { if(this.focusedFlag && e.pointerType === 'mouse') { this.realElement.focus(); } this.pressedFlag = false; this.fakeElement.removeClass(this.options.pressedClass); this.doc.off('jcf-pointerup', this.onRelease); }, getCurrentActiveRadio: function() { return this.getRadioGroup(this.realElement).filter(':checked'); }, getRadioGroup: function(radio) { // find radio group for specified radio button var name = radio.attr('name'), parentForm = radio.parents('form'); if(name) { if(parentForm.length) { return parentForm.find('input[name="' + name + '"]'); } else { return $('input[name="' + name + '"]:not(form input)'); } } else { return radio; } }, getLabelFor: function() { var parentLabel = this.realElement.closest('label'), elementId = this.realElement.prop('id'); if(!parentLabel.length && elementId) { parentLabel = $('label[for="' + elementId + '"]'); } return parentLabel.length ? parentLabel : null; }, refreshRadioGroup: function() { // redraw current radio and its group this.getRadioGroup(this.realElement).each(function() { jcf.refresh(this); }); }, refresh: function() { // redraw current radio button var isChecked = this.realElement.is(':checked'), isDisabled = this.realElement.is(':disabled'); this.fakeElement.toggleClass(this.options.checkedClass, isChecked) .toggleClass(this.options.uncheckedClass, !isChecked) .toggleClass(this.options.disabledClass, isDisabled); if(this.labelElement) { this.labelElement.toggleClass(this.options.labelActiveClass, isChecked); } }, destroy: function() { // restore structure if(this.options.wrapNative) { this.realElement.insertBefore(this.fakeElement).css({ position: '', width: '', height: '', opacity: '', margin: '' }); } else { this.realElement.removeClass(this.options.hiddenClass); } // removing element will also remove its event handlers this.fakeElement.off('jcf-pointerdown', this.onPress); this.fakeElement.remove(); // remove other event handlers this.doc.off('jcf-pointerup', this.onRelease); this.realElement.off({ blur: this.onBlur, focus: this.onFocus, click: this.onRealClick }); } }); }(jQuery, this));
/*! * Vue.js v2.1.4 * (c) 2014-2016 Evan You * Released under the MIT License. */ 'use strict'; /* */ /** * Convert a value to a string that is actually rendered. */ function _toString (val) { return val == null ? '' : typeof val === 'object' ? JSON.stringify(val, null, 2) : String(val) } /** * Convert a input value to a number for persistence. * If the conversion fails, return original string. */ function toNumber (val) { var n = parseFloat(val, 10); return (n || n === 0) ? n : val } /** * Make a map and return a function for checking if a key * is in that map. */ function makeMap ( str, expectsLowerCase ) { var map = Object.create(null); var list = str.split(','); for (var i = 0; i < list.length; i++) { map[list[i]] = true; } return expectsLowerCase ? function (val) { return map[val.toLowerCase()]; } : function (val) { return map[val]; } } /** * Check if a tag is a built-in tag. */ var isBuiltInTag = makeMap('slot,component', true); /** * Remove an item from an array */ function remove$1 (arr, item) { if (arr.length) { var index = arr.indexOf(item); if (index > -1) { return arr.splice(index, 1) } } } /** * Check whether the object has the property. */ var hasOwnProperty = Object.prototype.hasOwnProperty; function hasOwn (obj, key) { return hasOwnProperty.call(obj, key) } /** * Check if value is primitive */ function isPrimitive (value) { return typeof value === 'string' || typeof value === 'number' } /** * Create a cached version of a pure function. */ function cached (fn) { var cache = Object.create(null); return function cachedFn (str) { var hit = cache[str]; return hit || (cache[str] = fn(str)) } } /** * Camelize a hyphen-delmited string. */ var camelizeRE = /-(\w)/g; var camelize = cached(function (str) { return str.replace(camelizeRE, function (_, c) { return c ? c.toUpperCase() : ''; }) }); /** * Capitalize a string. */ var capitalize = cached(function (str) { return str.charAt(0).toUpperCase() + str.slice(1) }); /** * Hyphenate a camelCase string. */ var hyphenateRE = /([^-])([A-Z])/g; var hyphenate = cached(function (str) { return str .replace(hyphenateRE, '$1-$2') .replace(hyphenateRE, '$1-$2') .toLowerCase() }); /** * Simple bind, faster than native */ function bind$1 (fn, ctx) { function boundFn (a) { var l = arguments.length; return l ? l > 1 ? fn.apply(ctx, arguments) : fn.call(ctx, a) : fn.call(ctx) } // record original fn length boundFn._length = fn.length; return boundFn } /** * Convert an Array-like object to a real Array. */ function toArray (list, start) { start = start || 0; var i = list.length - start; var ret = new Array(i); while (i--) { ret[i] = list[i + start]; } return ret } /** * Mix properties into target object. */ function extend (to, _from) { for (var key in _from) { to[key] = _from[key]; } return to } /** * Quick object check - this is primarily used to tell * Objects from primitive values when we know the value * is a JSON-compliant type. */ function isObject (obj) { return obj !== null && typeof obj === 'object' } /** * Strict object type check. Only returns true * for plain JavaScript objects. */ var toString = Object.prototype.toString; var OBJECT_STRING = '[object Object]'; function isPlainObject (obj) { return toString.call(obj) === OBJECT_STRING } /** * Merge an Array of Objects into a single Object. */ function toObject (arr) { var res = {}; for (var i = 0; i < arr.length; i++) { if (arr[i]) { extend(res, arr[i]); } } return res } /** * Perform no operation. */ function noop () {} /** * Always return false. */ var no = function () { return false; }; /** * Generate a static keys string from compiler modules. */ function genStaticKeys (modules) { return modules.reduce(function (keys, m) { return keys.concat(m.staticKeys || []) }, []).join(',') } /** * Check if two values are loosely equal - that is, * if they are plain objects, do they have the same shape? */ function looseEqual (a, b) { /* eslint-disable eqeqeq */ return a == b || ( isObject(a) && isObject(b) ? JSON.stringify(a) === JSON.stringify(b) : false ) /* eslint-enable eqeqeq */ } function looseIndexOf (arr, val) { for (var i = 0; i < arr.length; i++) { if (looseEqual(arr[i], val)) { return i } } return -1 } /* */ var config = { /** * Option merge strategies (used in core/util/options) */ optionMergeStrategies: Object.create(null), /** * Whether to suppress warnings. */ silent: false, /** * Whether to enable devtools */ devtools: process.env.NODE_ENV !== 'production', /** * Error handler for watcher errors */ errorHandler: null, /** * Ignore certain custom elements */ ignoredElements: null, /** * Custom user key aliases for v-on */ keyCodes: Object.create(null), /** * Check if a tag is reserved so that it cannot be registered as a * component. This is platform-dependent and may be overwritten. */ isReservedTag: no, /** * Check if a tag is an unknown element. * Platform-dependent. */ isUnknownElement: no, /** * Get the namespace of an element */ getTagNamespace: noop, /** * Check if an attribute must be bound using property, e.g. value * Platform-dependent. */ mustUseProp: no, /** * List of asset types that a component can own. */ _assetTypes: [ 'component', 'directive', 'filter' ], /** * List of lifecycle hooks. */ _lifecycleHooks: [ 'beforeCreate', 'created', 'beforeMount', 'mounted', 'beforeUpdate', 'updated', 'beforeDestroy', 'destroyed', 'activated', 'deactivated' ], /** * Max circular updates allowed in a scheduler flush cycle. */ _maxUpdateCount: 100 }; /* */ /** * Check if a string starts with $ or _ */ function isReserved (str) { var c = (str + '').charCodeAt(0); return c === 0x24 || c === 0x5F } /** * Define a property. */ function def (obj, key, val, enumerable) { Object.defineProperty(obj, key, { value: val, enumerable: !!enumerable, writable: true, configurable: true }); } /** * Parse simple path. */ var bailRE = /[^\w.$]/; function parsePath (path) { if (bailRE.test(path)) { return } else { var segments = path.split('.'); return function (obj) { for (var i = 0; i < segments.length; i++) { if (!obj) { return } obj = obj[segments[i]]; } return obj } } } /* */ /* globals MutationObserver */ // can we use __proto__? var hasProto = '__proto__' in {}; // Browser environment sniffing var inBrowser = typeof window !== 'undefined'; var UA = inBrowser && window.navigator.userAgent.toLowerCase(); var isIE = UA && /msie|trident/.test(UA); var isIE9 = UA && UA.indexOf('msie 9.0') > 0; var isEdge = UA && UA.indexOf('edge/') > 0; var isAndroid = UA && UA.indexOf('android') > 0; var isIOS = UA && /iphone|ipad|ipod|ios/.test(UA); // this needs to be lazy-evaled because vue may be required before // vue-server-renderer can set VUE_ENV var _isServer; var isServerRendering = function () { if (_isServer === undefined) { /* istanbul ignore if */ if (!inBrowser && typeof global !== 'undefined') { // detect presence of vue-server-renderer and avoid // Webpack shimming the process _isServer = global['process'].env.VUE_ENV === 'server'; } else { _isServer = false; } } return _isServer }; // detect devtools var devtools = inBrowser && window.__VUE_DEVTOOLS_GLOBAL_HOOK__; /* istanbul ignore next */ function isNative (Ctor) { return /native code/.test(Ctor.toString()) } /** * Defer a task to execute it asynchronously. */ var nextTick = (function () { var callbacks = []; var pending = false; var timerFunc; function nextTickHandler () { pending = false; var copies = callbacks.slice(0); callbacks.length = 0; for (var i = 0; i < copies.length; i++) { copies[i](); } } // the nextTick behavior leverages the microtask queue, which can be accessed // via either native Promise.then or MutationObserver. // MutationObserver has wider support, however it is seriously bugged in // UIWebView in iOS >= 9.3.3 when triggered in touch event handlers. It // completely stops working after triggering a few times... so, if native // Promise is available, we will use it: /* istanbul ignore if */ if (typeof Promise !== 'undefined' && isNative(Promise)) { var p = Promise.resolve(); var logError = function (err) { console.error(err); }; timerFunc = function () { p.then(nextTickHandler).catch(logError); // in problematic UIWebViews, Promise.then doesn't completely break, but // it can get stuck in a weird state where callbacks are pushed into the // microtask queue but the queue isn't being flushed, until the browser // needs to do some other work, e.g. handle a timer. Therefore we can // "force" the microtask queue to be flushed by adding an empty timer. if (isIOS) { setTimeout(noop); } }; } else if (typeof MutationObserver !== 'undefined' && ( isNative(MutationObserver) || // PhantomJS and iOS 7.x MutationObserver.toString() === '[object MutationObserverConstructor]' )) { // use MutationObserver where native Promise is not available, // e.g. PhantomJS IE11, iOS7, Android 4.4 var counter = 1; var observer = new MutationObserver(nextTickHandler); var textNode = document.createTextNode(String(counter)); observer.observe(textNode, { characterData: true }); timerFunc = function () { counter = (counter + 1) % 2; textNode.data = String(counter); }; } else { // fallback to setTimeout /* istanbul ignore next */ timerFunc = function () { setTimeout(nextTickHandler, 0); }; } return function queueNextTick (cb, ctx) { var _resolve; callbacks.push(function () { if (cb) { cb.call(ctx); } if (_resolve) { _resolve(ctx); } }); if (!pending) { pending = true; timerFunc(); } if (!cb && typeof Promise !== 'undefined') { return new Promise(function (resolve) { _resolve = resolve; }) } } })(); var _Set; /* istanbul ignore if */ if (typeof Set !== 'undefined' && isNative(Set)) { // use native Set when available. _Set = Set; } else { // a non-standard Set polyfill that only works with primitive keys. _Set = (function () { function Set () { this.set = Object.create(null); } Set.prototype.has = function has (key) { return this.set[key] !== undefined }; Set.prototype.add = function add (key) { this.set[key] = 1; }; Set.prototype.clear = function clear () { this.set = Object.create(null); }; return Set; }()); } var warn = noop; var formatComponentName; if (process.env.NODE_ENV !== 'production') { var hasConsole = typeof console !== 'undefined'; warn = function (msg, vm) { if (hasConsole && (!config.silent)) { console.error("[Vue warn]: " + msg + " " + ( vm ? formatLocation(formatComponentName(vm)) : '' )); } }; formatComponentName = function (vm) { if (vm.$root === vm) { return 'root instance' } var name = vm._isVue ? vm.$options.name || vm.$options._componentTag : vm.name; return ( (name ? ("component <" + name + ">") : "anonymous component") + (vm._isVue && vm.$options.__file ? (" at " + (vm.$options.__file)) : '') ) }; var formatLocation = function (str) { if (str === 'anonymous component') { str += " - use the \"name\" option for better debugging messages."; } return ("\n(found in " + str + ")") }; } /* */ var uid$1 = 0; /** * A dep is an observable that can have multiple * directives subscribing to it. */ var Dep = function Dep () { this.id = uid$1++; this.subs = []; }; Dep.prototype.addSub = function addSub (sub) { this.subs.push(sub); }; Dep.prototype.removeSub = function removeSub (sub) { remove$1(this.subs, sub); }; Dep.prototype.depend = function depend () { if (Dep.target) { Dep.target.addDep(this); } }; Dep.prototype.notify = function notify () { // stablize the subscriber list first var subs = this.subs.slice(); for (var i = 0, l = subs.length; i < l; i++) { subs[i].update(); } }; // the current target watcher being evaluated. // this is globally unique because there could be only one // watcher being evaluated at any time. Dep.target = null; var targetStack = []; function pushTarget (_target) { if (Dep.target) { targetStack.push(Dep.target); } Dep.target = _target; } function popTarget () { Dep.target = targetStack.pop(); } /* * not type checking this file because flow doesn't play well with * dynamically accessing methods on Array prototype */ var arrayProto = Array.prototype; var arrayMethods = Object.create(arrayProto);[ 'push', 'pop', 'shift', 'unshift', 'splice', 'sort', 'reverse' ] .forEach(function (method) { // cache original method var original = arrayProto[method]; def(arrayMethods, method, function mutator () { var arguments$1 = arguments; // avoid leaking arguments: // http://jsperf.com/closure-with-arguments var i = arguments.length; var args = new Array(i); while (i--) { args[i] = arguments$1[i]; } var result = original.apply(this, args); var ob = this.__ob__; var inserted; switch (method) { case 'push': inserted = args; break case 'unshift': inserted = args; break case 'splice': inserted = args.slice(2); break } if (inserted) { ob.observeArray(inserted); } // notify change ob.dep.notify(); return result }); }); /* */ var arrayKeys = Object.getOwnPropertyNames(arrayMethods); /** * By default, when a reactive property is set, the new value is * also converted to become reactive. However when passing down props, * we don't want to force conversion because the value may be a nested value * under a frozen data structure. Converting it would defeat the optimization. */ var observerState = { shouldConvert: true, isSettingProps: false }; /** * Observer class that are attached to each observed * object. Once attached, the observer converts target * object's property keys into getter/setters that * collect dependencies and dispatches updates. */ var Observer = function Observer (value) { this.value = value; this.dep = new Dep(); this.vmCount = 0; def(value, '__ob__', this); if (Array.isArray(value)) { var augment = hasProto ? protoAugment : copyAugment; augment(value, arrayMethods, arrayKeys); this.observeArray(value); } else { this.walk(value); } }; /** * Walk through each property and convert them into * getter/setters. This method should only be called when * value type is Object. */ Observer.prototype.walk = function walk (obj) { var keys = Object.keys(obj); for (var i = 0; i < keys.length; i++) { defineReactive$$1(obj, keys[i], obj[keys[i]]); } }; /** * Observe a list of Array items. */ Observer.prototype.observeArray = function observeArray (items) { for (var i = 0, l = items.length; i < l; i++) { observe(items[i]); } }; // helpers /** * Augment an target Object or Array by intercepting * the prototype chain using __proto__ */ function protoAugment (target, src) { /* eslint-disable no-proto */ target.__proto__ = src; /* eslint-enable no-proto */ } /** * Augment an target Object or Array by defining * hidden properties. * * istanbul ignore next */ function copyAugment (target, src, keys) { for (var i = 0, l = keys.length; i < l; i++) { var key = keys[i]; def(target, key, src[key]); } } /** * Attempt to create an observer instance for a value, * returns the new observer if successfully observed, * or the existing observer if the value already has one. */ function observe (value) { if (!isObject(value)) { return } var ob; if (hasOwn(value, '__ob__') && value.__ob__ instanceof Observer) { ob = value.__ob__; } else if ( observerState.shouldConvert && !isServerRendering() && (Array.isArray(value) || isPlainObject(value)) && Object.isExtensible(value) && !value._isVue ) { ob = new Observer(value); } return ob } /** * Define a reactive property on an Object. */ function defineReactive$$1 ( obj, key, val, customSetter ) { var dep = new Dep(); var property = Object.getOwnPropertyDescriptor(obj, key); if (property && property.configurable === false) { return } // cater for pre-defined getter/setters var getter = property && property.get; var setter = property && property.set; var childOb = observe(val); Object.defineProperty(obj, key, { enumerable: true, configurable: true, get: function reactiveGetter () { var value = getter ? getter.call(obj) : val; if (Dep.target) { dep.depend(); if (childOb) { childOb.dep.depend(); } if (Array.isArray(value)) { dependArray(value); } } return value }, set: function reactiveSetter (newVal) { var value = getter ? getter.call(obj) : val; /* eslint-disable no-self-compare */ if (newVal === value || (newVal !== newVal && value !== value)) { return } /* eslint-enable no-self-compare */ if (process.env.NODE_ENV !== 'production' && customSetter) { customSetter(); } if (setter) { setter.call(obj, newVal); } else { val = newVal; } childOb = observe(newVal); dep.notify(); } }); } /** * Set a property on an object. Adds the new property and * triggers change notification if the property doesn't * already exist. */ function set$1 (obj, key, val) { if (Array.isArray(obj)) { obj.length = Math.max(obj.length, key); obj.splice(key, 1, val); return val } if (hasOwn(obj, key)) { obj[key] = val; return } var ob = obj.__ob__; if (obj._isVue || (ob && ob.vmCount)) { process.env.NODE_ENV !== 'production' && warn( 'Avoid adding reactive properties to a Vue instance or its root $data ' + 'at runtime - declare it upfront in the data option.' ); return } if (!ob) { obj[key] = val; return } defineReactive$$1(ob.value, key, val); ob.dep.notify(); return val } /** * Delete a property and trigger change if necessary. */ function del (obj, key) { var ob = obj.__ob__; if (obj._isVue || (ob && ob.vmCount)) { process.env.NODE_ENV !== 'production' && warn( 'Avoid deleting properties on a Vue instance or its root $data ' + '- just set it to null.' ); return } if (!hasOwn(obj, key)) { return } delete obj[key]; if (!ob) { return } ob.dep.notify(); } /** * Collect dependencies on array elements when the array is touched, since * we cannot intercept array element access like property getters. */ function dependArray (value) { for (var e = (void 0), i = 0, l = value.length; i < l; i++) { e = value[i]; e && e.__ob__ && e.__ob__.dep.depend(); if (Array.isArray(e)) { dependArray(e); } } } /* */ /** * Option overwriting strategies are functions that handle * how to merge a parent option value and a child option * value into the final value. */ var strats = config.optionMergeStrategies; /** * Options with restrictions */ if (process.env.NODE_ENV !== 'production') { strats.el = strats.propsData = function (parent, child, vm, key) { if (!vm) { warn( "option \"" + key + "\" can only be used during instance " + 'creation with the `new` keyword.' ); } return defaultStrat(parent, child) }; } /** * Helper that recursively merges two data objects together. */ function mergeData (to, from) { if (!from) { return to } var key, toVal, fromVal; var keys = Object.keys(from); for (var i = 0; i < keys.length; i++) { key = keys[i]; toVal = to[key]; fromVal = from[key]; if (!hasOwn(to, key)) { set$1(to, key, fromVal); } else if (isPlainObject(toVal) && isPlainObject(fromVal)) { mergeData(toVal, fromVal); } } return to } /** * Data */ strats.data = function ( parentVal, childVal, vm ) { if (!vm) { // in a Vue.extend merge, both should be functions if (!childVal) { return parentVal } if (typeof childVal !== 'function') { process.env.NODE_ENV !== 'production' && warn( 'The "data" option should be a function ' + 'that returns a per-instance value in component ' + 'definitions.', vm ); return parentVal } if (!parentVal) { return childVal } // when parentVal & childVal are both present, // we need to return a function that returns the // merged result of both functions... no need to // check if parentVal is a function here because // it has to be a function to pass previous merges. return function mergedDataFn () { return mergeData( childVal.call(this), parentVal.call(this) ) } } else if (parentVal || childVal) { return function mergedInstanceDataFn () { // instance merge var instanceData = typeof childVal === 'function' ? childVal.call(vm) : childVal; var defaultData = typeof parentVal === 'function' ? parentVal.call(vm) : undefined; if (instanceData) { return mergeData(instanceData, defaultData) } else { return defaultData } } } }; /** * Hooks and param attributes are merged as arrays. */ function mergeHook ( parentVal, childVal ) { return childVal ? parentVal ? parentVal.concat(childVal) : Array.isArray(childVal) ? childVal : [childVal] : parentVal } config._lifecycleHooks.forEach(function (hook) { strats[hook] = mergeHook; }); /** * Assets * * When a vm is present (instance creation), we need to do * a three-way merge between constructor options, instance * options and parent options. */ function mergeAssets (parentVal, childVal) { var res = Object.create(parentVal || null); return childVal ? extend(res, childVal) : res } config._assetTypes.forEach(function (type) { strats[type + 's'] = mergeAssets; }); /** * Watchers. * * Watchers hashes should not overwrite one * another, so we merge them as arrays. */ strats.watch = function (parentVal, childVal) { /* istanbul ignore if */ if (!childVal) { return parentVal } if (!parentVal) { return childVal } var ret = {}; extend(ret, parentVal); for (var key in childVal) { var parent = ret[key]; var child = childVal[key]; if (parent && !Array.isArray(parent)) { parent = [parent]; } ret[key] = parent ? parent.concat(child) : [child]; } return ret }; /** * Other object hashes. */ strats.props = strats.methods = strats.computed = function (parentVal, childVal) { if (!childVal) { return parentVal } if (!parentVal) { return childVal } var ret = Object.create(null); extend(ret, parentVal); extend(ret, childVal); return ret }; /** * Default strategy. */ var defaultStrat = function (parentVal, childVal) { return childVal === undefined ? parentVal : childVal }; /** * Validate component names */ function checkComponents (options) { for (var key in options.components) { var lower = key.toLowerCase(); if (isBuiltInTag(lower) || config.isReservedTag(lower)) { warn( 'Do not use built-in or reserved HTML elements as component ' + 'id: ' + key ); } } } /** * Ensure all props option syntax are normalized into the * Object-based format. */ function normalizeProps (options) { var props = options.props; if (!props) { return } var res = {}; var i, val, name; if (Array.isArray(props)) { i = props.length; while (i--) { val = props[i]; if (typeof val === 'string') { name = camelize(val); res[name] = { type: null }; } else if (process.env.NODE_ENV !== 'production') { warn('props must be strings when using array syntax.'); } } } else if (isPlainObject(props)) { for (var key in props) { val = props[key]; name = camelize(key); res[name] = isPlainObject(val) ? val : { type: val }; } } options.props = res; } /** * Normalize raw function directives into object format. */ function normalizeDirectives (options) { var dirs = options.directives; if (dirs) { for (var key in dirs) { var def = dirs[key]; if (typeof def === 'function') { dirs[key] = { bind: def, update: def }; } } } } /** * Merge two option objects into a new one. * Core utility used in both instantiation and inheritance. */ function mergeOptions ( parent, child, vm ) { if (process.env.NODE_ENV !== 'production') { checkComponents(child); } normalizeProps(child); normalizeDirectives(child); var extendsFrom = child.extends; if (extendsFrom) { parent = typeof extendsFrom === 'function' ? mergeOptions(parent, extendsFrom.options, vm) : mergeOptions(parent, extendsFrom, vm); } if (child.mixins) { for (var i = 0, l = child.mixins.length; i < l; i++) { var mixin = child.mixins[i]; if (mixin.prototype instanceof Vue$3) { mixin = mixin.options; } parent = mergeOptions(parent, mixin, vm); } } var options = {}; var key; for (key in parent) { mergeField(key); } for (key in child) { if (!hasOwn(parent, key)) { mergeField(key); } } function mergeField (key) { var strat = strats[key] || defaultStrat; options[key] = strat(parent[key], child[key], vm, key); } return options } /** * Resolve an asset. * This function is used because child instances need access * to assets defined in its ancestor chain. */ function resolveAsset ( options, type, id, warnMissing ) { /* istanbul ignore if */ if (typeof id !== 'string') { return } var assets = options[type]; var res = assets[id] || // camelCase ID assets[camelize(id)] || // Pascal Case ID assets[capitalize(camelize(id))]; if (process.env.NODE_ENV !== 'production' && warnMissing && !res) { warn( 'Failed to resolve ' + type.slice(0, -1) + ': ' + id, options ); } return res } /* */ function validateProp ( key, propOptions, propsData, vm ) { var prop = propOptions[key]; var absent = !hasOwn(propsData, key); var value = propsData[key]; // handle boolean props if (isBooleanType(prop.type)) { if (absent && !hasOwn(prop, 'default')) { value = false; } else if (value === '' || value === hyphenate(key)) { value = true; } } // check default value if (value === undefined) { value = getPropDefaultValue(vm, prop, key); // since the default value is a fresh copy, // make sure to observe it. var prevShouldConvert = observerState.shouldConvert; observerState.shouldConvert = true; observe(value); observerState.shouldConvert = prevShouldConvert; } if (process.env.NODE_ENV !== 'production') { assertProp(prop, key, value, vm, absent); } return value } /** * Get the default value of a prop. */ function getPropDefaultValue (vm, prop, key) { // no default, return undefined if (!hasOwn(prop, 'default')) { return undefined } var def = prop.default; // warn against non-factory defaults for Object & Array if (isObject(def)) { process.env.NODE_ENV !== 'production' && warn( 'Invalid default value for prop "' + key + '": ' + 'Props with type Object/Array must use a factory function ' + 'to return the default value.', vm ); } // the raw prop value was also undefined from previous render, // return previous default value to avoid unnecessary watcher trigger if (vm && vm.$options.propsData && vm.$options.propsData[key] === undefined && vm[key] !== undefined) { return vm[key] } // call factory function for non-Function types return typeof def === 'function' && prop.type !== Function ? def.call(vm) : def } /** * Assert whether a prop is valid. */ function assertProp ( prop, name, value, vm, absent ) { if (prop.required && absent) { warn( 'Missing required prop: "' + name + '"', vm ); return } if (value == null && !prop.required) { return } var type = prop.type; var valid = !type || type === true; var expectedTypes = []; if (type) { if (!Array.isArray(type)) { type = [type]; } for (var i = 0; i < type.length && !valid; i++) { var assertedType = assertType(value, type[i]); expectedTypes.push(assertedType.expectedType); valid = assertedType.valid; } } if (!valid) { warn( 'Invalid prop: type check failed for prop "' + name + '".' + ' Expected ' + expectedTypes.map(capitalize).join(', ') + ', got ' + Object.prototype.toString.call(value).slice(8, -1) + '.', vm ); return } var validator = prop.validator; if (validator) { if (!validator(value)) { warn( 'Invalid prop: custom validator check failed for prop "' + name + '".', vm ); } } } /** * Assert the type of a value */ function assertType (value, type) { var valid; var expectedType = getType(type); if (expectedType === 'String') { valid = typeof value === (expectedType = 'string'); } else if (expectedType === 'Number') { valid = typeof value === (expectedType = 'number'); } else if (expectedType === 'Boolean') { valid = typeof value === (expectedType = 'boolean'); } else if (expectedType === 'Function') { valid = typeof value === (expectedType = 'function'); } else if (expectedType === 'Object') { valid = isPlainObject(value); } else if (expectedType === 'Array') { valid = Array.isArray(value); } else { valid = value instanceof type; } return { valid: valid, expectedType: expectedType } } /** * Use function string name to check built-in types, * because a simple equality check will fail when running * across different vms / iframes. */ function getType (fn) { var match = fn && fn.toString().match(/^\s*function (\w+)/); return match && match[1] } function isBooleanType (fn) { if (!Array.isArray(fn)) { return getType(fn) === 'Boolean' } for (var i = 0, len = fn.length; i < len; i++) { if (getType(fn[i]) === 'Boolean') { return true } } /* istanbul ignore next */ return false } var util = Object.freeze({ defineReactive: defineReactive$$1, _toString: _toString, toNumber: toNumber, makeMap: makeMap, isBuiltInTag: isBuiltInTag, remove: remove$1, hasOwn: hasOwn, isPrimitive: isPrimitive, cached: cached, camelize: camelize, capitalize: capitalize, hyphenate: hyphenate, bind: bind$1, toArray: toArray, extend: extend, isObject: isObject, isPlainObject: isPlainObject, toObject: toObject, noop: noop, no: no, genStaticKeys: genStaticKeys, looseEqual: looseEqual, looseIndexOf: looseIndexOf, isReserved: isReserved, def: def, parsePath: parsePath, hasProto: hasProto, inBrowser: inBrowser, UA: UA, isIE: isIE, isIE9: isIE9, isEdge: isEdge, isAndroid: isAndroid, isIOS: isIOS, isServerRendering: isServerRendering, devtools: devtools, nextTick: nextTick, get _Set () { return _Set; }, mergeOptions: mergeOptions, resolveAsset: resolveAsset, get warn () { return warn; }, get formatComponentName () { return formatComponentName; }, validateProp: validateProp }); /* not type checking this file because flow doesn't play well with Proxy */ var initProxy; if (process.env.NODE_ENV !== 'production') { var allowedGlobals = makeMap( 'Infinity,undefined,NaN,isFinite,isNaN,' + 'parseFloat,parseInt,decodeURI,decodeURIComponent,encodeURI,encodeURIComponent,' + 'Math,Number,Date,Array,Object,Boolean,String,RegExp,Map,Set,JSON,Intl,' + 'require' // for Webpack/Browserify ); var warnNonPresent = function (target, key) { warn( "Property or method \"" + key + "\" is not defined on the instance but " + "referenced during render. Make sure to declare reactive data " + "properties in the data option.", target ); }; var hasProxy = typeof Proxy !== 'undefined' && Proxy.toString().match(/native code/); if (hasProxy) { var isBuiltInModifier = makeMap('stop,prevent,self,ctrl,shift,alt,meta'); config.keyCodes = new Proxy(config.keyCodes, { set: function set (target, key, value) { if (isBuiltInModifier(key)) { warn(("Avoid overwriting built-in modifier in config.keyCodes: ." + key)); return false } else { target[key] = value; return true } } }); } var hasHandler = { has: function has (target, key) { var has = key in target; var isAllowed = allowedGlobals(key) || key.charAt(0) === '_'; if (!has && !isAllowed) { warnNonPresent(target, key); } return has || !isAllowed } }; var getHandler = { get: function get (target, key) { if (typeof key === 'string' && !(key in target)) { warnNonPresent(target, key); } return target[key] } }; initProxy = function initProxy (vm) { if (hasProxy) { // determine which proxy handler to use var options = vm.$options; var handlers = options.render && options.render._withStripped ? getHandler : hasHandler; vm._renderProxy = new Proxy(vm, handlers); } else { vm._renderProxy = vm; } }; } /* */ var queue = []; var has$1 = {}; var circular = {}; var waiting = false; var flushing = false; var index = 0; /** * Reset the scheduler's state. */ function resetSchedulerState () { queue.length = 0; has$1 = {}; if (process.env.NODE_ENV !== 'production') { circular = {}; } waiting = flushing = false; } /** * Flush both queues and run the watchers. */ function flushSchedulerQueue () { flushing = true; // Sort queue before flush. // This ensures that: // 1. Components are updated from parent to child. (because parent is always // created before the child) // 2. A component's user watchers are run before its render watcher (because // user watchers are created before the render watcher) // 3. If a component is destroyed during a parent component's watcher run, // its watchers can be skipped. queue.sort(function (a, b) { return a.id - b.id; }); // do not cache length because more watchers might be pushed // as we run existing watchers for (index = 0; index < queue.length; index++) { var watcher = queue[index]; var id = watcher.id; has$1[id] = null; watcher.run(); // in dev build, check and stop circular updates. if (process.env.NODE_ENV !== 'production' && has$1[id] != null) { circular[id] = (circular[id] || 0) + 1; if (circular[id] > config._maxUpdateCount) { warn( 'You may have an infinite update loop ' + ( watcher.user ? ("in watcher with expression \"" + (watcher.expression) + "\"") : "in a component render function." ), watcher.vm ); break } } } // devtool hook /* istanbul ignore if */ if (devtools && config.devtools) { devtools.emit('flush'); } resetSchedulerState(); } /** * Push a watcher into the watcher queue. * Jobs with duplicate IDs will be skipped unless it's * pushed when the queue is being flushed. */ function queueWatcher (watcher) { var id = watcher.id; if (has$1[id] == null) { has$1[id] = true; if (!flushing) { queue.push(watcher); } else { // if already flushing, splice the watcher based on its id // if already past its id, it will be run next immediately. var i = queue.length - 1; while (i >= 0 && queue[i].id > watcher.id) { i--; } queue.splice(Math.max(i, index) + 1, 0, watcher); } // queue the flush if (!waiting) { waiting = true; nextTick(flushSchedulerQueue); } } } /* */ var uid$2 = 0; /** * A watcher parses an expression, collects dependencies, * and fires callback when the expression value changes. * This is used for both the $watch() api and directives. */ var Watcher = function Watcher ( vm, expOrFn, cb, options ) { if ( options === void 0 ) options = {}; this.vm = vm; vm._watchers.push(this); // options this.deep = !!options.deep; this.user = !!options.user; this.lazy = !!options.lazy; this.sync = !!options.sync; this.expression = expOrFn.toString(); this.cb = cb; this.id = ++uid$2; // uid for batching this.active = true; this.dirty = this.lazy; // for lazy watchers this.deps = []; this.newDeps = []; this.depIds = new _Set(); this.newDepIds = new _Set(); // parse expression for getter if (typeof expOrFn === 'function') { this.getter = expOrFn; } else { this.getter = parsePath(expOrFn); if (!this.getter) { this.getter = function () {}; process.env.NODE_ENV !== 'production' && warn( "Failed watching path: \"" + expOrFn + "\" " + 'Watcher only accepts simple dot-delimited paths. ' + 'For full control, use a function instead.', vm ); } } this.value = this.lazy ? undefined : this.get(); }; /** * Evaluate the getter, and re-collect dependencies. */ Watcher.prototype.get = function get () { pushTarget(this); var value = this.getter.call(this.vm, this.vm); // "touch" every property so they are all tracked as // dependencies for deep watching if (this.deep) { traverse(value); } popTarget(); this.cleanupDeps(); return value }; /** * Add a dependency to this directive. */ Watcher.prototype.addDep = function addDep (dep) { var id = dep.id; if (!this.newDepIds.has(id)) { this.newDepIds.add(id); this.newDeps.push(dep); if (!this.depIds.has(id)) { dep.addSub(this); } } }; /** * Clean up for dependency collection. */ Watcher.prototype.cleanupDeps = function cleanupDeps () { var this$1 = this; var i = this.deps.length; while (i--) { var dep = this$1.deps[i]; if (!this$1.newDepIds.has(dep.id)) { dep.removeSub(this$1); } } var tmp = this.depIds; this.depIds = this.newDepIds; this.newDepIds = tmp; this.newDepIds.clear(); tmp = this.deps; this.deps = this.newDeps; this.newDeps = tmp; this.newDeps.length = 0; }; /** * Subscriber interface. * Will be called when a dependency changes. */ Watcher.prototype.update = function update () { /* istanbul ignore else */ if (this.lazy) { this.dirty = true; } else if (this.sync) { this.run(); } else { queueWatcher(this); } }; /** * Scheduler job interface. * Will be called by the scheduler. */ Watcher.prototype.run = function run () { if (this.active) { var value = this.get(); if ( value !== this.value || // Deep watchers and watchers on Object/Arrays should fire even // when the value is the same, because the value may // have mutated. isObject(value) || this.deep ) { // set new value var oldValue = this.value; this.value = value; if (this.user) { try { this.cb.call(this.vm, value, oldValue); } catch (e) { /* istanbul ignore else */ if (config.errorHandler) { config.errorHandler.call(null, e, this.vm); } else { process.env.NODE_ENV !== 'production' && warn( ("Error in watcher \"" + (this.expression) + "\""), this.vm ); throw e } } } else { this.cb.call(this.vm, value, oldValue); } } } }; /** * Evaluate the value of the watcher. * This only gets called for lazy watchers. */ Watcher.prototype.evaluate = function evaluate () { this.value = this.get(); this.dirty = false; }; /** * Depend on all deps collected by this watcher. */ Watcher.prototype.depend = function depend () { var this$1 = this; var i = this.deps.length; while (i--) { this$1.deps[i].depend(); } }; /** * Remove self from all dependencies' subscriber list. */ Watcher.prototype.teardown = function teardown () { var this$1 = this; if (this.active) { // remove self from vm's watcher list // this is a somewhat expensive operation so we skip it // if the vm is being destroyed or is performing a v-for // re-render (the watcher list is then filtered by v-for). if (!this.vm._isBeingDestroyed && !this.vm._vForRemoving) { remove$1(this.vm._watchers, this); } var i = this.deps.length; while (i--) { this$1.deps[i].removeSub(this$1); } this.active = false; } }; /** * Recursively traverse an object to evoke all converted * getters, so that every nested property inside the object * is collected as a "deep" dependency. */ var seenObjects = new _Set(); function traverse (val) { seenObjects.clear(); _traverse(val, seenObjects); } function _traverse (val, seen) { var i, keys; var isA = Array.isArray(val); if ((!isA && !isObject(val)) || !Object.isExtensible(val)) { return } if (val.__ob__) { var depId = val.__ob__.dep.id; if (seen.has(depId)) { return } seen.add(depId); } if (isA) { i = val.length; while (i--) { _traverse(val[i], seen); } } else { keys = Object.keys(val); i = keys.length; while (i--) { _traverse(val[keys[i]], seen); } } } /* */ function initState (vm) { vm._watchers = []; initProps(vm); initMethods(vm); initData(vm); initComputed(vm); initWatch(vm); } var isReservedProp = { key: 1, ref: 1, slot: 1 }; function initProps (vm) { var props = vm.$options.props; if (props) { var propsData = vm.$options.propsData || {}; var keys = vm.$options._propKeys = Object.keys(props); var isRoot = !vm.$parent; // root instance props should be converted observerState.shouldConvert = isRoot; var loop = function ( i ) { var key = keys[i]; /* istanbul ignore else */ if (process.env.NODE_ENV !== 'production') { if (isReservedProp[key]) { warn( ("\"" + key + "\" is a reserved attribute and cannot be used as component prop."), vm ); } defineReactive$$1(vm, key, validateProp(key, props, propsData, vm), function () { if (vm.$parent && !observerState.isSettingProps) { warn( "Avoid mutating a prop directly since the value will be " + "overwritten whenever the parent component re-renders. " + "Instead, use a data or computed property based on the prop's " + "value. Prop being mutated: \"" + key + "\"", vm ); } }); } else { defineReactive$$1(vm, key, validateProp(key, props, propsData, vm)); } }; for (var i = 0; i < keys.length; i++) loop( i ); observerState.shouldConvert = true; } } function initData (vm) { var data = vm.$options.data; data = vm._data = typeof data === 'function' ? data.call(vm) : data || {}; if (!isPlainObject(data)) { data = {}; process.env.NODE_ENV !== 'production' && warn( 'data functions should return an object.', vm ); } // proxy data on instance var keys = Object.keys(data); var props = vm.$options.props; var i = keys.length; while (i--) { if (props && hasOwn(props, keys[i])) { process.env.NODE_ENV !== 'production' && warn( "The data property \"" + (keys[i]) + "\" is already declared as a prop. " + "Use prop default value instead.", vm ); } else { proxy(vm, keys[i]); } } // observe data observe(data); data.__ob__ && data.__ob__.vmCount++; } var computedSharedDefinition = { enumerable: true, configurable: true, get: noop, set: noop }; function initComputed (vm) { var computed = vm.$options.computed; if (computed) { for (var key in computed) { var userDef = computed[key]; if (typeof userDef === 'function') { computedSharedDefinition.get = makeComputedGetter(userDef, vm); computedSharedDefinition.set = noop; } else { computedSharedDefinition.get = userDef.get ? userDef.cache !== false ? makeComputedGetter(userDef.get, vm) : bind$1(userDef.get, vm) : noop; computedSharedDefinition.set = userDef.set ? bind$1(userDef.set, vm) : noop; } Object.defineProperty(vm, key, computedSharedDefinition); } } } function makeComputedGetter (getter, owner) { var watcher = new Watcher(owner, getter, noop, { lazy: true }); return function computedGetter () { if (watcher.dirty) { watcher.evaluate(); } if (Dep.target) { watcher.depend(); } return watcher.value } } function initMethods (vm) { var methods = vm.$options.methods; if (methods) { for (var key in methods) { vm[key] = methods[key] == null ? noop : bind$1(methods[key], vm); if (process.env.NODE_ENV !== 'production' && methods[key] == null) { warn( "method \"" + key + "\" has an undefined value in the component definition. " + "Did you reference the function correctly?", vm ); } } } } function initWatch (vm) { var watch = vm.$options.watch; if (watch) { for (var key in watch) { var handler = watch[key]; if (Array.isArray(handler)) { for (var i = 0; i < handler.length; i++) { createWatcher(vm, key, handler[i]); } } else { createWatcher(vm, key, handler); } } } } function createWatcher (vm, key, handler) { var options; if (isPlainObject(handler)) { options = handler; handler = handler.handler; } if (typeof handler === 'string') { handler = vm[handler]; } vm.$watch(key, handler, options); } function stateMixin (Vue) { // flow somehow has problems with directly declared definition object // when using Object.defineProperty, so we have to procedurally build up // the object here. var dataDef = {}; dataDef.get = function () { return this._data }; if (process.env.NODE_ENV !== 'production') { dataDef.set = function (newData) { warn( 'Avoid replacing instance root $data. ' + 'Use nested data properties instead.', this ); }; } Object.defineProperty(Vue.prototype, '$data', dataDef); Vue.prototype.$set = set$1; Vue.prototype.$delete = del; Vue.prototype.$watch = function ( expOrFn, cb, options ) { var vm = this; options = options || {}; options.user = true; var watcher = new Watcher(vm, expOrFn, cb, options); if (options.immediate) { cb.call(vm, watcher.value); } return function unwatchFn () { watcher.teardown(); } }; } function proxy (vm, key) { if (!isReserved(key)) { Object.defineProperty(vm, key, { configurable: true, enumerable: true, get: function proxyGetter () { return vm._data[key] }, set: function proxySetter (val) { vm._data[key] = val; } }); } } /* */ var VNode = function VNode ( tag, data, children, text, elm, ns, context, componentOptions ) { this.tag = tag; this.data = data; this.children = children; this.text = text; this.elm = elm; this.ns = ns; this.context = context; this.functionalContext = undefined; this.key = data && data.key; this.componentOptions = componentOptions; this.child = undefined; this.parent = undefined; this.raw = false; this.isStatic = false; this.isRootInsert = true; this.isComment = false; this.isCloned = false; this.isOnce = false; }; var emptyVNode = function () { var node = new VNode(); node.text = ''; node.isComment = true; return node }; // optimized shallow clone // used for static nodes and slot nodes because they may be reused across // multiple renders, cloning them avoids errors when DOM manipulations rely // on their elm reference. function cloneVNode (vnode) { var cloned = new VNode( vnode.tag, vnode.data, vnode.children, vnode.text, vnode.elm, vnode.ns, vnode.context, vnode.componentOptions ); cloned.isStatic = vnode.isStatic; cloned.key = vnode.key; cloned.isCloned = true; return cloned } function cloneVNodes (vnodes) { var res = new Array(vnodes.length); for (var i = 0; i < vnodes.length; i++) { res[i] = cloneVNode(vnodes[i]); } return res } /* */ function mergeVNodeHook (def, hookKey, hook, key) { key = key + hookKey; var injectedHash = def.__injected || (def.__injected = {}); if (!injectedHash[key]) { injectedHash[key] = true; var oldHook = def[hookKey]; if (oldHook) { def[hookKey] = function () { oldHook.apply(this, arguments); hook.apply(this, arguments); }; } else { def[hookKey] = hook; } } } /* */ function updateListeners ( on, oldOn, add, remove$$1, vm ) { var name, cur, old, fn, event, capture, once; for (name in on) { cur = on[name]; old = oldOn[name]; if (!cur) { process.env.NODE_ENV !== 'production' && warn( "Invalid handler for event \"" + name + "\": got " + String(cur), vm ); } else if (!old) { once = name.charAt(0) === '~'; // Prefixed last, checked first event = once ? name.slice(1) : name; capture = event.charAt(0) === '!'; event = capture ? event.slice(1) : event; if (Array.isArray(cur)) { add(event, (cur.invoker = arrInvoker(cur)), once, capture); } else { if (!cur.invoker) { fn = cur; cur = on[name] = {}; cur.fn = fn; cur.invoker = fnInvoker(cur); } add(event, cur.invoker, once, capture); } } else if (cur !== old) { if (Array.isArray(old)) { old.length = cur.length; for (var i = 0; i < old.length; i++) { old[i] = cur[i]; } on[name] = old; } else { old.fn = cur; on[name] = old; } } } for (name in oldOn) { if (!on[name]) { once = name.charAt(0) === '~'; // Prefixed last, checked first event = once ? name.slice(1) : name; capture = event.charAt(0) === '!'; event = capture ? event.slice(1) : event; remove$$1(event, oldOn[name].invoker, capture); } } } function arrInvoker (arr) { return function (ev) { var arguments$1 = arguments; var single = arguments.length === 1; for (var i = 0; i < arr.length; i++) { single ? arr[i](ev) : arr[i].apply(null, arguments$1); } } } function fnInvoker (o) { return function (ev) { var single = arguments.length === 1; single ? o.fn(ev) : o.fn.apply(null, arguments); } } /* */ function normalizeChildren ( children, ns, nestedIndex ) { if (isPrimitive(children)) { return [createTextVNode(children)] } if (Array.isArray(children)) { var res = []; for (var i = 0, l = children.length; i < l; i++) { var c = children[i]; var last = res[res.length - 1]; // nested if (Array.isArray(c)) { res.push.apply(res, normalizeChildren(c, ns, ((nestedIndex || '') + "_" + i))); } else if (isPrimitive(c)) { if (last && last.text) { last.text += String(c); } else if (c !== '') { // convert primitive to vnode res.push(createTextVNode(c)); } } else if (c instanceof VNode) { if (c.text && last && last.text) { if (!last.isCloned) { last.text += c.text; } } else { // inherit parent namespace if (ns) { applyNS(c, ns); } // default key for nested array children (likely generated by v-for) if (c.tag && c.key == null && nestedIndex != null) { c.key = "__vlist" + nestedIndex + "_" + i + "__"; } res.push(c); } } } return res } } function createTextVNode (val) { return new VNode(undefined, undefined, undefined, String(val)) } function applyNS (vnode, ns) { if (vnode.tag && !vnode.ns) { vnode.ns = ns; if (vnode.children) { for (var i = 0, l = vnode.children.length; i < l; i++) { applyNS(vnode.children[i], ns); } } } } /* */ function getFirstComponentChild (children) { return children && children.filter(function (c) { return c && c.componentOptions; })[0] } /* */ var activeInstance = null; function initLifecycle (vm) { var options = vm.$options; // locate first non-abstract parent var parent = options.parent; if (parent && !options.abstract) { while (parent.$options.abstract && parent.$parent) { parent = parent.$parent; } parent.$children.push(vm); } vm.$parent = parent; vm.$root = parent ? parent.$root : vm; vm.$children = []; vm.$refs = {}; vm._watcher = null; vm._inactive = false; vm._isMounted = false; vm._isDestroyed = false; vm._isBeingDestroyed = false; } function lifecycleMixin (Vue) { Vue.prototype._mount = function ( el, hydrating ) { var vm = this; vm.$el = el; if (!vm.$options.render) { vm.$options.render = emptyVNode; if (process.env.NODE_ENV !== 'production') { /* istanbul ignore if */ if (vm.$options.template && vm.$options.template.charAt(0) !== '#') { warn( 'You are using the runtime-only build of Vue where the template ' + 'option is not available. Either pre-compile the templates into ' + 'render functions, or use the compiler-included build.', vm ); } else { warn( 'Failed to mount component: template or render function not defined.', vm ); } } } callHook(vm, 'beforeMount'); vm._watcher = new Watcher(vm, function () { vm._update(vm._render(), hydrating); }, noop); hydrating = false; // manually mounted instance, call mounted on self // mounted is called for render-created child components in its inserted hook if (vm.$vnode == null) { vm._isMounted = true; callHook(vm, 'mounted'); } return vm }; Vue.prototype._update = function (vnode, hydrating) { var vm = this; if (vm._isMounted) { callHook(vm, 'beforeUpdate'); } var prevEl = vm.$el; var prevVnode = vm._vnode; var prevActiveInstance = activeInstance; activeInstance = vm; vm._vnode = vnode; // Vue.prototype.__patch__ is injected in entry points // based on the rendering backend used. if (!prevVnode) { // initial render vm.$el = vm.__patch__( vm.$el, vnode, hydrating, false /* removeOnly */, vm.$options._parentElm, vm.$options._refElm ); } else { // updates vm.$el = vm.__patch__(prevVnode, vnode); } activeInstance = prevActiveInstance; // update __vue__ reference if (prevEl) { prevEl.__vue__ = null; } if (vm.$el) { vm.$el.__vue__ = vm; } // if parent is an HOC, update its $el as well if (vm.$vnode && vm.$parent && vm.$vnode === vm.$parent._vnode) { vm.$parent.$el = vm.$el; } if (vm._isMounted) { callHook(vm, 'updated'); } }; Vue.prototype._updateFromParent = function ( propsData, listeners, parentVnode, renderChildren ) { var vm = this; var hasChildren = !!(vm.$options._renderChildren || renderChildren); vm.$options._parentVnode = parentVnode; vm.$vnode = parentVnode; // update vm's placeholder node without re-render if (vm._vnode) { // update child tree's parent vm._vnode.parent = parentVnode; } vm.$options._renderChildren = renderChildren; // update props if (propsData && vm.$options.props) { observerState.shouldConvert = false; if (process.env.NODE_ENV !== 'production') { observerState.isSettingProps = true; } var propKeys = vm.$options._propKeys || []; for (var i = 0; i < propKeys.length; i++) { var key = propKeys[i]; vm[key] = validateProp(key, vm.$options.props, propsData, vm); } observerState.shouldConvert = true; if (process.env.NODE_ENV !== 'production') { observerState.isSettingProps = false; } vm.$options.propsData = propsData; } // update listeners if (listeners) { var oldListeners = vm.$options._parentListeners; vm.$options._parentListeners = listeners; vm._updateListeners(listeners, oldListeners); } // resolve slots + force update if has children if (hasChildren) { vm.$slots = resolveSlots(renderChildren, parentVnode.context); vm.$forceUpdate(); } }; Vue.prototype.$forceUpdate = function () { var vm = this; if (vm._watcher) { vm._watcher.update(); } }; Vue.prototype.$destroy = function () { var vm = this; if (vm._isBeingDestroyed) { return } callHook(vm, 'beforeDestroy'); vm._isBeingDestroyed = true; // remove self from parent var parent = vm.$parent; if (parent && !parent._isBeingDestroyed && !vm.$options.abstract) { remove$1(parent.$children, vm); } // teardown watchers if (vm._watcher) { vm._watcher.teardown(); } var i = vm._watchers.length; while (i--) { vm._watchers[i].teardown(); } // remove reference from data ob // frozen object may not have observer. if (vm._data.__ob__) { vm._data.__ob__.vmCount--; } // call the last hook... vm._isDestroyed = true; callHook(vm, 'destroyed'); // turn off all instance listeners. vm.$off(); // remove __vue__ reference if (vm.$el) { vm.$el.__vue__ = null; } // invoke destroy hooks on current rendered tree vm.__patch__(vm._vnode, null); }; } function callHook (vm, hook) { var handlers = vm.$options[hook]; if (handlers) { for (var i = 0, j = handlers.length; i < j; i++) { handlers[i].call(vm); } } vm.$emit('hook:' + hook); } /* */ var hooks = { init: init, prepatch: prepatch, insert: insert, destroy: destroy$1 }; var hooksToMerge = Object.keys(hooks); function createComponent ( Ctor, data, context, children, tag ) { if (!Ctor) { return } var baseCtor = context.$options._base; if (isObject(Ctor)) { Ctor = baseCtor.extend(Ctor); } if (typeof Ctor !== 'function') { if (process.env.NODE_ENV !== 'production') { warn(("Invalid Component definition: " + (String(Ctor))), context); } return } // async component if (!Ctor.cid) { if (Ctor.resolved) { Ctor = Ctor.resolved; } else { Ctor = resolveAsyncComponent(Ctor, baseCtor, function () { // it's ok to queue this on every render because // $forceUpdate is buffered by the scheduler. context.$forceUpdate(); }); if (!Ctor) { // return nothing if this is indeed an async component // wait for the callback to trigger parent update. return } } } // resolve constructor options in case global mixins are applied after // component constructor creation resolveConstructorOptions(Ctor); data = data || {}; // extract props var propsData = extractProps(data, Ctor); // functional component if (Ctor.options.functional) { return createFunctionalComponent(Ctor, propsData, data, context, children) } // extract listeners, since these needs to be treated as // child component listeners instead of DOM listeners var listeners = data.on; // replace with listeners with .native modifier data.on = data.nativeOn; if (Ctor.options.abstract) { // abstract components do not keep anything // other than props & listeners data = {}; } // merge component management hooks onto the placeholder node mergeHooks(data); // return a placeholder vnode var name = Ctor.options.name || tag; var vnode = new VNode( ("vue-component-" + (Ctor.cid) + (name ? ("-" + name) : '')), data, undefined, undefined, undefined, undefined, context, { Ctor: Ctor, propsData: propsData, listeners: listeners, tag: tag, children: children } ); return vnode } function createFunctionalComponent ( Ctor, propsData, data, context, children ) { var props = {}; var propOptions = Ctor.options.props; if (propOptions) { for (var key in propOptions) { props[key] = validateProp(key, propOptions, propsData); } } var vnode = Ctor.options.render.call( null, // ensure the createElement function in functional components // gets a unique context - this is necessary for correct named slot check bind$1(createElement, { _self: Object.create(context) }), { props: props, data: data, parent: context, children: normalizeChildren(children), slots: function () { return resolveSlots(children, context); } } ); if (vnode instanceof VNode) { vnode.functionalContext = context; if (data.slot) { (vnode.data || (vnode.data = {})).slot = data.slot; } } return vnode } function createComponentInstanceForVnode ( vnode, // we know it's MountedComponentVNode but flow doesn't parent, // activeInstance in lifecycle state parentElm, refElm ) { var vnodeComponentOptions = vnode.componentOptions; var options = { _isComponent: true, parent: parent, propsData: vnodeComponentOptions.propsData, _componentTag: vnodeComponentOptions.tag, _parentVnode: vnode, _parentListeners: vnodeComponentOptions.listeners, _renderChildren: vnodeComponentOptions.children, _parentElm: parentElm || null, _refElm: refElm || null }; // check inline-template render functions var inlineTemplate = vnode.data.inlineTemplate; if (inlineTemplate) { options.render = inlineTemplate.render; options.staticRenderFns = inlineTemplate.staticRenderFns; } return new vnodeComponentOptions.Ctor(options) } function init ( vnode, hydrating, parentElm, refElm ) { if (!vnode.child || vnode.child._isDestroyed) { var child = vnode.child = createComponentInstanceForVnode( vnode, activeInstance, parentElm, refElm ); child.$mount(hydrating ? vnode.elm : undefined, hydrating); } else if (vnode.data.keepAlive) { // kept-alive components, treat as a patch var mountedNode = vnode; // work around flow prepatch(mountedNode, mountedNode); } } function prepatch ( oldVnode, vnode ) { var options = vnode.componentOptions; var child = vnode.child = oldVnode.child; child._updateFromParent( options.propsData, // updated props options.listeners, // updated listeners vnode, // new parent vnode options.children // new children ); } function insert (vnode) { if (!vnode.child._isMounted) { vnode.child._isMounted = true; callHook(vnode.child, 'mounted'); } if (vnode.data.keepAlive) { vnode.child._inactive = false; callHook(vnode.child, 'activated'); } } function destroy$1 (vnode) { if (!vnode.child._isDestroyed) { if (!vnode.data.keepAlive) { vnode.child.$destroy(); } else { vnode.child._inactive = true; callHook(vnode.child, 'deactivated'); } } } function resolveAsyncComponent ( factory, baseCtor, cb ) { if (factory.requested) { // pool callbacks factory.pendingCallbacks.push(cb); } else { factory.requested = true; var cbs = factory.pendingCallbacks = [cb]; var sync = true; var resolve = function (res) { if (isObject(res)) { res = baseCtor.extend(res); } // cache resolved factory.resolved = res; // invoke callbacks only if this is not a synchronous resolve // (async resolves are shimmed as synchronous during SSR) if (!sync) { for (var i = 0, l = cbs.length; i < l; i++) { cbs[i](res); } } }; var reject = function (reason) { process.env.NODE_ENV !== 'production' && warn( "Failed to resolve async component: " + (String(factory)) + (reason ? ("\nReason: " + reason) : '') ); }; var res = factory(resolve, reject); // handle promise if (res && typeof res.then === 'function' && !factory.resolved) { res.then(resolve, reject); } sync = false; // return in case resolved synchronously return factory.resolved } } function extractProps (data, Ctor) { // we are only extracting raw values here. // validation and default values are handled in the child // component itself. var propOptions = Ctor.options.props; if (!propOptions) { return } var res = {}; var attrs = data.attrs; var props = data.props; var domProps = data.domProps; if (attrs || props || domProps) { for (var key in propOptions) { var altKey = hyphenate(key); checkProp(res, props, key, altKey, true) || checkProp(res, attrs, key, altKey) || checkProp(res, domProps, key, altKey); } } return res } function checkProp ( res, hash, key, altKey, preserve ) { if (hash) { if (hasOwn(hash, key)) { res[key] = hash[key]; if (!preserve) { delete hash[key]; } return true } else if (hasOwn(hash, altKey)) { res[key] = hash[altKey]; if (!preserve) { delete hash[altKey]; } return true } } return false } function mergeHooks (data) { if (!data.hook) { data.hook = {}; } for (var i = 0; i < hooksToMerge.length; i++) { var key = hooksToMerge[i]; var fromParent = data.hook[key]; var ours = hooks[key]; data.hook[key] = fromParent ? mergeHook$1(ours, fromParent) : ours; } } function mergeHook$1 (one, two) { return function (a, b, c, d) { one(a, b, c, d); two(a, b, c, d); } } /* */ // wrapper function for providing a more flexible interface // without getting yelled at by flow function createElement ( tag, data, children ) { if (data && (Array.isArray(data) || typeof data !== 'object')) { children = data; data = undefined; } // make sure to use real instance instead of proxy as context return _createElement(this._self, tag, data, children) } function _createElement ( context, tag, data, children ) { if (data && data.__ob__) { process.env.NODE_ENV !== 'production' && warn( "Avoid using observed data object as vnode data: " + (JSON.stringify(data)) + "\n" + 'Always create fresh vnode data objects in each render!', context ); return } if (!tag) { // in case of component :is set to falsy value return emptyVNode() } // support single function children as default scoped slot if (Array.isArray(children) && typeof children[0] === 'function') { data = data || {}; data.scopedSlots = { default: children[0] }; children.length = 0; } if (typeof tag === 'string') { var Ctor; var ns = config.getTagNamespace(tag); if (config.isReservedTag(tag)) { // platform built-in elements return new VNode( tag, data, normalizeChildren(children, ns), undefined, undefined, ns, context ) } else if ((Ctor = resolveAsset(context.$options, 'components', tag))) { // component return createComponent(Ctor, data, context, children, tag) } else { // unknown or unlisted namespaced elements // check at runtime because it may get assigned a namespace when its // parent normalizes children var childNs = tag === 'foreignObject' ? 'xhtml' : ns; return new VNode( tag, data, normalizeChildren(children, childNs), undefined, undefined, ns, context ) } } else { // direct component options / constructor return createComponent(tag, data, context, children) } } /* */ function initRender (vm) { vm.$vnode = null; // the placeholder node in parent tree vm._vnode = null; // the root of the child tree vm._staticTrees = null; var parentVnode = vm.$options._parentVnode; var renderContext = parentVnode && parentVnode.context; vm.$slots = resolveSlots(vm.$options._renderChildren, renderContext); vm.$scopedSlots = {}; // bind the public createElement fn to this instance // so that we get proper render context inside it. vm.$createElement = bind$1(createElement, vm); if (vm.$options.el) { vm.$mount(vm.$options.el); } } function renderMixin (Vue) { Vue.prototype.$nextTick = function (fn) { return nextTick(fn, this) }; Vue.prototype._render = function () { var vm = this; var ref = vm.$options; var render = ref.render; var staticRenderFns = ref.staticRenderFns; var _parentVnode = ref._parentVnode; if (vm._isMounted) { // clone slot nodes on re-renders for (var key in vm.$slots) { vm.$slots[key] = cloneVNodes(vm.$slots[key]); } } if (_parentVnode && _parentVnode.data.scopedSlots) { vm.$scopedSlots = _parentVnode.data.scopedSlots; } if (staticRenderFns && !vm._staticTrees) { vm._staticTrees = []; } // set parent vnode. this allows render functions to have access // to the data on the placeholder node. vm.$vnode = _parentVnode; // render self var vnode; try { vnode = render.call(vm._renderProxy, vm.$createElement); } catch (e) { /* istanbul ignore else */ if (config.errorHandler) { config.errorHandler.call(null, e, vm); } else { if (process.env.NODE_ENV !== 'production') { warn(("Error when rendering " + (formatComponentName(vm)) + ":")); } throw e } // return previous vnode to prevent render error causing blank component vnode = vm._vnode; } // return empty vnode in case the render function errored out if (!(vnode instanceof VNode)) { if (process.env.NODE_ENV !== 'production' && Array.isArray(vnode)) { warn( 'Multiple root nodes returned from render function. Render function ' + 'should return a single root node.', vm ); } vnode = emptyVNode(); } // set parent vnode.parent = _parentVnode; return vnode }; // shorthands used in render functions Vue.prototype._h = createElement; // toString for mustaches Vue.prototype._s = _toString; // number conversion Vue.prototype._n = toNumber; // empty vnode Vue.prototype._e = emptyVNode; // loose equal Vue.prototype._q = looseEqual; // loose indexOf Vue.prototype._i = looseIndexOf; // render static tree by index Vue.prototype._m = function renderStatic ( index, isInFor ) { var tree = this._staticTrees[index]; // if has already-rendered static tree and not inside v-for, // we can reuse the same tree by doing a shallow clone. if (tree && !isInFor) { return Array.isArray(tree) ? cloneVNodes(tree) : cloneVNode(tree) } // otherwise, render a fresh tree. tree = this._staticTrees[index] = this.$options.staticRenderFns[index].call(this._renderProxy); markStatic(tree, ("__static__" + index), false); return tree }; // mark node as static (v-once) Vue.prototype._o = function markOnce ( tree, index, key ) { markStatic(tree, ("__once__" + index + (key ? ("_" + key) : "")), true); return tree }; function markStatic (tree, key, isOnce) { if (Array.isArray(tree)) { for (var i = 0; i < tree.length; i++) { if (tree[i] && typeof tree[i] !== 'string') { markStaticNode(tree[i], (key + "_" + i), isOnce); } } } else { markStaticNode(tree, key, isOnce); } } function markStaticNode (node, key, isOnce) { node.isStatic = true; node.key = key; node.isOnce = isOnce; } // filter resolution helper var identity = function (_) { return _; }; Vue.prototype._f = function resolveFilter (id) { return resolveAsset(this.$options, 'filters', id, true) || identity }; // render v-for Vue.prototype._l = function renderList ( val, render ) { var ret, i, l, keys, key; if (Array.isArray(val)) { ret = new Array(val.length); for (i = 0, l = val.length; i < l; i++) { ret[i] = render(val[i], i); } } else if (typeof val === 'number') { ret = new Array(val); for (i = 0; i < val; i++) { ret[i] = render(i + 1, i); } } else if (isObject(val)) { keys = Object.keys(val); ret = new Array(keys.length); for (i = 0, l = keys.length; i < l; i++) { key = keys[i]; ret[i] = render(val[key], key, i); } } return ret }; // renderSlot Vue.prototype._t = function ( name, fallback, props ) { var scopedSlotFn = this.$scopedSlots[name]; if (scopedSlotFn) { // scoped slot return scopedSlotFn(props || {}) || fallback } else { var slotNodes = this.$slots[name]; // warn duplicate slot usage if (slotNodes && process.env.NODE_ENV !== 'production') { slotNodes._rendered && warn( "Duplicate presence of slot \"" + name + "\" found in the same render tree " + "- this will likely cause render errors.", this ); slotNodes._rendered = true; } return slotNodes || fallback } }; // apply v-bind object Vue.prototype._b = function bindProps ( data, tag, value, asProp ) { if (value) { if (!isObject(value)) { process.env.NODE_ENV !== 'production' && warn( 'v-bind without argument expects an Object or Array value', this ); } else { if (Array.isArray(value)) { value = toObject(value); } for (var key in value) { if (key === 'class' || key === 'style') { data[key] = value[key]; } else { var hash = asProp || config.mustUseProp(tag, key) ? data.domProps || (data.domProps = {}) : data.attrs || (data.attrs = {}); hash[key] = value[key]; } } } } return data }; // check v-on keyCodes Vue.prototype._k = function checkKeyCodes ( eventKeyCode, key, builtInAlias ) { var keyCodes = config.keyCodes[key] || builtInAlias; if (Array.isArray(keyCodes)) { return keyCodes.indexOf(eventKeyCode) === -1 } else { return keyCodes !== eventKeyCode } }; } function resolveSlots ( renderChildren, context ) { var slots = {}; if (!renderChildren) { return slots } var children = normalizeChildren(renderChildren) || []; var defaultSlot = []; var name, child; for (var i = 0, l = children.length; i < l; i++) { child = children[i]; // named slots should only be respected if the vnode was rendered in the // same context. if ((child.context === context || child.functionalContext === context) && child.data && (name = child.data.slot)) { var slot = (slots[name] || (slots[name] = [])); if (child.tag === 'template') { slot.push.apply(slot, child.children); } else { slot.push(child); } } else { defaultSlot.push(child); } } // ignore single whitespace if (defaultSlot.length && !( defaultSlot.length === 1 && (defaultSlot[0].text === ' ' || defaultSlot[0].isComment) )) { slots.default = defaultSlot; } return slots } /* */ function initEvents (vm) { vm._events = Object.create(null); // init parent attached events var listeners = vm.$options._parentListeners; var add = function (event, fn, once) { once ? vm.$once(event, fn) : vm.$on(event, fn); }; var remove$$1 = bind$1(vm.$off, vm); vm._updateListeners = function (listeners, oldListeners) { updateListeners(listeners, oldListeners || {}, add, remove$$1, vm); }; if (listeners) { vm._updateListeners(listeners); } } function eventsMixin (Vue) { Vue.prototype.$on = function (event, fn) { var vm = this;(vm._events[event] || (vm._events[event] = [])).push(fn); return vm }; Vue.prototype.$once = function (event, fn) { var vm = this; function on () { vm.$off(event, on); fn.apply(vm, arguments); } on.fn = fn; vm.$on(event, on); return vm }; Vue.prototype.$off = function (event, fn) { var vm = this; // all if (!arguments.length) { vm._events = Object.create(null); return vm } // specific event var cbs = vm._events[event]; if (!cbs) { return vm } if (arguments.length === 1) { vm._events[event] = null; return vm } // specific handler var cb; var i = cbs.length; while (i--) { cb = cbs[i]; if (cb === fn || cb.fn === fn) { cbs.splice(i, 1); break } } return vm }; Vue.prototype.$emit = function (event) { var vm = this; var cbs = vm._events[event]; if (cbs) { cbs = cbs.length > 1 ? toArray(cbs) : cbs; var args = toArray(arguments, 1); for (var i = 0, l = cbs.length; i < l; i++) { cbs[i].apply(vm, args); } } return vm }; } /* */ var uid = 0; function initMixin (Vue) { Vue.prototype._init = function (options) { var vm = this; // a uid vm._uid = uid++; // a flag to avoid this being observed vm._isVue = true; // merge options if (options && options._isComponent) { // optimize internal component instantiation // since dynamic options merging is pretty slow, and none of the // internal component options needs special treatment. initInternalComponent(vm, options); } else { vm.$options = mergeOptions( resolveConstructorOptions(vm.constructor), options || {}, vm ); } /* istanbul ignore else */ if (process.env.NODE_ENV !== 'production') { initProxy(vm); } else { vm._renderProxy = vm; } // expose real self vm._self = vm; initLifecycle(vm); initEvents(vm); callHook(vm, 'beforeCreate'); initState(vm); callHook(vm, 'created'); initRender(vm); }; } function initInternalComponent (vm, options) { var opts = vm.$options = Object.create(vm.constructor.options); // doing this because it's faster than dynamic enumeration. opts.parent = options.parent; opts.propsData = options.propsData; opts._parentVnode = options._parentVnode; opts._parentListeners = options._parentListeners; opts._renderChildren = options._renderChildren; opts._componentTag = options._componentTag; opts._parentElm = options._parentElm; opts._refElm = options._refElm; if (options.render) { opts.render = options.render; opts.staticRenderFns = options.staticRenderFns; } } function resolveConstructorOptions (Ctor) { var options = Ctor.options; if (Ctor.super) { var superOptions = Ctor.super.options; var cachedSuperOptions = Ctor.superOptions; var extendOptions = Ctor.extendOptions; if (superOptions !== cachedSuperOptions) { // super option changed Ctor.superOptions = superOptions; extendOptions.render = options.render; extendOptions.staticRenderFns = options.staticRenderFns; extendOptions._scopeId = options._scopeId; options = Ctor.options = mergeOptions(superOptions, extendOptions); if (options.name) { options.components[options.name] = Ctor; } } } return options } function Vue$3 (options) { if (process.env.NODE_ENV !== 'production' && !(this instanceof Vue$3)) { warn('Vue is a constructor and should be called with the `new` keyword'); } this._init(options); } initMixin(Vue$3); stateMixin(Vue$3); eventsMixin(Vue$3); lifecycleMixin(Vue$3); renderMixin(Vue$3); /* */ function initUse (Vue) { Vue.use = function (plugin) { /* istanbul ignore if */ if (plugin.installed) { return } // additional parameters var args = toArray(arguments, 1); args.unshift(this); if (typeof plugin.install === 'function') { plugin.install.apply(plugin, args); } else { plugin.apply(null, args); } plugin.installed = true; return this }; } /* */ function initMixin$1 (Vue) { Vue.mixin = function (mixin) { this.options = mergeOptions(this.options, mixin); }; } /* */ function initExtend (Vue) { /** * Each instance constructor, including Vue, has a unique * cid. This enables us to create wrapped "child * constructors" for prototypal inheritance and cache them. */ Vue.cid = 0; var cid = 1; /** * Class inheritance */ Vue.extend = function (extendOptions) { extendOptions = extendOptions || {}; var Super = this; var SuperId = Super.cid; var cachedCtors = extendOptions._Ctor || (extendOptions._Ctor = {}); if (cachedCtors[SuperId]) { return cachedCtors[SuperId] } var name = extendOptions.name || Super.options.name; if (process.env.NODE_ENV !== 'production') { if (!/^[a-zA-Z][\w-]*$/.test(name)) { warn( 'Invalid component name: "' + name + '". Component names ' + 'can only contain alphanumeric characaters and the hyphen.' ); } } var Sub = function VueComponent (options) { this._init(options); }; Sub.prototype = Object.create(Super.prototype); Sub.prototype.constructor = Sub; Sub.cid = cid++; Sub.options = mergeOptions( Super.options, extendOptions ); Sub['super'] = Super; // allow further extension/mixin/plugin usage Sub.extend = Super.extend; Sub.mixin = Super.mixin; Sub.use = Super.use; // create asset registers, so extended classes // can have their private assets too. config._assetTypes.forEach(function (type) { Sub[type] = Super[type]; }); // enable recursive self-lookup if (name) { Sub.options.components[name] = Sub; } // keep a reference to the super options at extension time. // later at instantiation we can check if Super's options have // been updated. Sub.superOptions = Super.options; Sub.extendOptions = extendOptions; // cache constructor cachedCtors[SuperId] = Sub; return Sub }; } /* */ function initAssetRegisters (Vue) { /** * Create asset registration methods. */ config._assetTypes.forEach(function (type) { Vue[type] = function ( id, definition ) { if (!definition) { return this.options[type + 's'][id] } else { /* istanbul ignore if */ if (process.env.NODE_ENV !== 'production') { if (type === 'component' && config.isReservedTag(id)) { warn( 'Do not use built-in or reserved HTML elements as component ' + 'id: ' + id ); } } if (type === 'component' && isPlainObject(definition)) { definition.name = definition.name || id; definition = this.options._base.extend(definition); } if (type === 'directive' && typeof definition === 'function') { definition = { bind: definition, update: definition }; } this.options[type + 's'][id] = definition; return definition } }; }); } /* */ var patternTypes = [String, RegExp]; function matches (pattern, name) { if (typeof pattern === 'string') { return pattern.split(',').indexOf(name) > -1 } else { return pattern.test(name) } } var KeepAlive = { name: 'keep-alive', abstract: true, props: { include: patternTypes, exclude: patternTypes }, created: function created () { this.cache = Object.create(null); }, render: function render () { var vnode = getFirstComponentChild(this.$slots.default); if (vnode && vnode.componentOptions) { var opts = vnode.componentOptions; // check pattern var name = opts.Ctor.options.name || opts.tag; if (name && ( (this.include && !matches(this.include, name)) || (this.exclude && matches(this.exclude, name)) )) { return vnode } var key = vnode.key == null // same constructor may get registered as different local components // so cid alone is not enough (#3269) ? opts.Ctor.cid + (opts.tag ? ("::" + (opts.tag)) : '') : vnode.key; if (this.cache[key]) { vnode.child = this.cache[key].child; } else { this.cache[key] = vnode; } vnode.data.keepAlive = true; } return vnode }, destroyed: function destroyed () { var this$1 = this; for (var key in this.cache) { var vnode = this$1.cache[key]; callHook(vnode.child, 'deactivated'); vnode.child.$destroy(); } } }; var builtInComponents = { KeepAlive: KeepAlive }; /* */ function initGlobalAPI (Vue) { // config var configDef = {}; configDef.get = function () { return config; }; if (process.env.NODE_ENV !== 'production') { configDef.set = function () { warn( 'Do not replace the Vue.config object, set individual fields instead.' ); }; } Object.defineProperty(Vue, 'config', configDef); Vue.util = util; Vue.set = set$1; Vue.delete = del; Vue.nextTick = nextTick; Vue.options = Object.create(null); config._assetTypes.forEach(function (type) { Vue.options[type + 's'] = Object.create(null); }); // this is used to identify the "base" constructor to extend all plain-object // components with in Weex's multi-instance scenarios. Vue.options._base = Vue; extend(Vue.options.components, builtInComponents); initUse(Vue); initMixin$1(Vue); initExtend(Vue); initAssetRegisters(Vue); } initGlobalAPI(Vue$3); Object.defineProperty(Vue$3.prototype, '$isServer', { get: isServerRendering }); Vue$3.version = '2.1.4'; /* */ // attributes that should be using props for binding var mustUseProp = function (tag, attr) { return ( (attr === 'value' && (tag === 'input' || tag === 'textarea' || tag === 'option')) || (attr === 'selected' && tag === 'option') || (attr === 'checked' && tag === 'input') || (attr === 'muted' && tag === 'video') ) }; var isEnumeratedAttr = makeMap('contenteditable,draggable,spellcheck'); var isBooleanAttr = makeMap( 'allowfullscreen,async,autofocus,autoplay,checked,compact,controls,declare,' + 'default,defaultchecked,defaultmuted,defaultselected,defer,disabled,' + 'enabled,formnovalidate,hidden,indeterminate,inert,ismap,itemscope,loop,multiple,' + 'muted,nohref,noresize,noshade,novalidate,nowrap,open,pauseonexit,readonly,' + 'required,reversed,scoped,seamless,selected,sortable,translate,' + 'truespeed,typemustmatch,visible' ); var xlinkNS = 'http://www.w3.org/1999/xlink'; var isXlink = function (name) { return name.charAt(5) === ':' && name.slice(0, 5) === 'xlink' }; var getXlinkProp = function (name) { return isXlink(name) ? name.slice(6, name.length) : '' }; var isFalsyAttrValue = function (val) { return val == null || val === false }; /* */ function genClassForVnode (vnode) { var data = vnode.data; var parentNode = vnode; var childNode = vnode; while (childNode.child) { childNode = childNode.child._vnode; if (childNode.data) { data = mergeClassData(childNode.data, data); } } while ((parentNode = parentNode.parent)) { if (parentNode.data) { data = mergeClassData(data, parentNode.data); } } return genClassFromData(data) } function mergeClassData (child, parent) { return { staticClass: concat(child.staticClass, parent.staticClass), class: child.class ? [child.class, parent.class] : parent.class } } function genClassFromData (data) { var dynamicClass = data.class; var staticClass = data.staticClass; if (staticClass || dynamicClass) { return concat(staticClass, stringifyClass(dynamicClass)) } /* istanbul ignore next */ return '' } function concat (a, b) { return a ? b ? (a + ' ' + b) : a : (b || '') } function stringifyClass (value) { var res = ''; if (!value) { return res } if (typeof value === 'string') { return value } if (Array.isArray(value)) { var stringified; for (var i = 0, l = value.length; i < l; i++) { if (value[i]) { if ((stringified = stringifyClass(value[i]))) { res += stringified + ' '; } } } return res.slice(0, -1) } if (isObject(value)) { for (var key in value) { if (value[key]) { res += key + ' '; } } return res.slice(0, -1) } /* istanbul ignore next */ return res } /* */ var namespaceMap = { svg: 'http://www.w3.org/2000/svg', math: 'http://www.w3.org/1998/Math/MathML', xhtml: 'http://www.w3.org/1999/xhtml' }; var isHTMLTag = makeMap( 'html,body,base,head,link,meta,style,title,' + 'address,article,aside,footer,header,h1,h2,h3,h4,h5,h6,hgroup,nav,section,' + 'div,dd,dl,dt,figcaption,figure,hr,img,li,main,ol,p,pre,ul,' + 'a,b,abbr,bdi,bdo,br,cite,code,data,dfn,em,i,kbd,mark,q,rp,rt,rtc,ruby,' + 's,samp,small,span,strong,sub,sup,time,u,var,wbr,area,audio,map,track,video,' + 'embed,object,param,source,canvas,script,noscript,del,ins,' + 'caption,col,colgroup,table,thead,tbody,td,th,tr,' + 'button,datalist,fieldset,form,input,label,legend,meter,optgroup,option,' + 'output,progress,select,textarea,' + 'details,dialog,menu,menuitem,summary,' + 'content,element,shadow,template' ); // this map is intentionally selective, only covering SVG elements that may // contain child elements. var isSVG = makeMap( 'svg,animate,circle,clippath,cursor,defs,desc,ellipse,filter,font,' + 'font-face,g,glyph,image,line,marker,mask,missing-glyph,path,pattern,' + 'polygon,polyline,rect,switch,symbol,text,textpath,tspan,use,view', true ); var isPreTag = function (tag) { return tag === 'pre'; }; var isReservedTag = function (tag) { return isHTMLTag(tag) || isSVG(tag) }; function getTagNamespace (tag) { if (isSVG(tag)) { return 'svg' } // basic support for MathML // note it doesn't support other MathML elements being component roots if (tag === 'math') { return 'math' } } var unknownElementCache = Object.create(null); function isUnknownElement (tag) { /* istanbul ignore if */ if (!inBrowser) { return true } if (isReservedTag(tag)) { return false } tag = tag.toLowerCase(); /* istanbul ignore if */ if (unknownElementCache[tag] != null) { return unknownElementCache[tag] } var el = document.createElement(tag); if (tag.indexOf('-') > -1) { // http://stackoverflow.com/a/28210364/1070244 return (unknownElementCache[tag] = ( el.constructor === window.HTMLUnknownElement || el.constructor === window.HTMLElement )) } else { return (unknownElementCache[tag] = /HTMLUnknownElement/.test(el.toString())) } } /* */ /** * Query an element selector if it's not an element already. */ function query (el) { if (typeof el === 'string') { var selector = el; el = document.querySelector(el); if (!el) { process.env.NODE_ENV !== 'production' && warn( 'Cannot find element: ' + selector ); return document.createElement('div') } } return el } /* */ function createElement$1 (tagName, vnode) { var elm = document.createElement(tagName); if (tagName !== 'select') { return elm } if (vnode.data && vnode.data.attrs && 'multiple' in vnode.data.attrs) { elm.setAttribute('multiple', 'multiple'); } return elm } function createElementNS (namespace, tagName) { return document.createElementNS(namespaceMap[namespace], tagName) } function createTextNode (text) { return document.createTextNode(text) } function createComment (text) { return document.createComment(text) } function insertBefore (parentNode, newNode, referenceNode) { parentNode.insertBefore(newNode, referenceNode); } function removeChild (node, child) { node.removeChild(child); } function appendChild (node, child) { node.appendChild(child); } function parentNode (node) { return node.parentNode } function nextSibling (node) { return node.nextSibling } function tagName (node) { return node.tagName } function setTextContent (node, text) { node.textContent = text; } function childNodes (node) { return node.childNodes } function setAttribute (node, key, val) { node.setAttribute(key, val); } var nodeOps = Object.freeze({ createElement: createElement$1, createElementNS: createElementNS, createTextNode: createTextNode, createComment: createComment, insertBefore: insertBefore, removeChild: removeChild, appendChild: appendChild, parentNode: parentNode, nextSibling: nextSibling, tagName: tagName, setTextContent: setTextContent, childNodes: childNodes, setAttribute: setAttribute }); /* */ var ref = { create: function create (_, vnode) { registerRef(vnode); }, update: function update (oldVnode, vnode) { if (oldVnode.data.ref !== vnode.data.ref) { registerRef(oldVnode, true); registerRef(vnode); } }, destroy: function destroy (vnode) { registerRef(vnode, true); } }; function registerRef (vnode, isRemoval) { var key = vnode.data.ref; if (!key) { return } var vm = vnode.context; var ref = vnode.child || vnode.elm; var refs = vm.$refs; if (isRemoval) { if (Array.isArray(refs[key])) { remove$1(refs[key], ref); } else if (refs[key] === ref) { refs[key] = undefined; } } else { if (vnode.data.refInFor) { if (Array.isArray(refs[key]) && refs[key].indexOf(ref) < 0) { refs[key].push(ref); } else { refs[key] = [ref]; } } else { refs[key] = ref; } } } /** * Virtual DOM patching algorithm based on Snabbdom by * Simon Friis Vindum (@paldepind) * Licensed under the MIT License * https://github.com/paldepind/snabbdom/blob/master/LICENSE * * modified by Evan You (@yyx990803) * /* * Not type-checking this because this file is perf-critical and the cost * of making flow understand it is not worth it. */ var emptyNode = new VNode('', {}, []); var hooks$1 = ['create', 'activate', 'update', 'remove', 'destroy']; function isUndef (s) { return s == null } function isDef (s) { return s != null } function sameVnode (vnode1, vnode2) { return ( vnode1.key === vnode2.key && vnode1.tag === vnode2.tag && vnode1.isComment === vnode2.isComment && !vnode1.data === !vnode2.data ) } function createKeyToOldIdx (children, beginIdx, endIdx) { var i, key; var map = {}; for (i = beginIdx; i <= endIdx; ++i) { key = children[i].key; if (isDef(key)) { map[key] = i; } } return map } function createPatchFunction (backend) { var i, j; var cbs = {}; var modules = backend.modules; var nodeOps = backend.nodeOps; for (i = 0; i < hooks$1.length; ++i) { cbs[hooks$1[i]] = []; for (j = 0; j < modules.length; ++j) { if (modules[j][hooks$1[i]] !== undefined) { cbs[hooks$1[i]].push(modules[j][hooks$1[i]]); } } } function emptyNodeAt (elm) { return new VNode(nodeOps.tagName(elm).toLowerCase(), {}, [], undefined, elm) } function createRmCb (childElm, listeners) { function remove$$1 () { if (--remove$$1.listeners === 0) { removeElement(childElm); } } remove$$1.listeners = listeners; return remove$$1 } function removeElement (el) { var parent = nodeOps.parentNode(el); // element may have already been removed due to v-html if (parent) { nodeOps.removeChild(parent, el); } } var inPre = 0; function createElm (vnode, insertedVnodeQueue, parentElm, refElm, nested) { vnode.isRootInsert = !nested; // for transition enter check if (createComponent(vnode, insertedVnodeQueue, parentElm, refElm)) { return } var data = vnode.data; var children = vnode.children; var tag = vnode.tag; if (isDef(tag)) { if (process.env.NODE_ENV !== 'production') { if (data && data.pre) { inPre++; } if ( !inPre && !vnode.ns && !(config.ignoredElements && config.ignoredElements.indexOf(tag) > -1) && config.isUnknownElement(tag) ) { warn( 'Unknown custom element: <' + tag + '> - did you ' + 'register the component correctly? For recursive components, ' + 'make sure to provide the "name" option.', vnode.context ); } } vnode.elm = vnode.ns ? nodeOps.createElementNS(vnode.ns, tag) : nodeOps.createElement(tag, vnode); setScope(vnode); /* istanbul ignore if */ { createChildren(vnode, children, insertedVnodeQueue); if (isDef(data)) { invokeCreateHooks(vnode, insertedVnodeQueue); } insert(parentElm, vnode.elm, refElm); } if (process.env.NODE_ENV !== 'production' && data && data.pre) { inPre--; } } else if (vnode.isComment) { vnode.elm = nodeOps.createComment(vnode.text); insert(parentElm, vnode.elm, refElm); } else { vnode.elm = nodeOps.createTextNode(vnode.text); insert(parentElm, vnode.elm, refElm); } } function createComponent (vnode, insertedVnodeQueue, parentElm, refElm) { var i = vnode.data; if (isDef(i)) { var isReactivated = isDef(vnode.child) && i.keepAlive; if (isDef(i = i.hook) && isDef(i = i.init)) { i(vnode, false /* hydrating */, parentElm, refElm); } // after calling the init hook, if the vnode is a child component // it should've created a child instance and mounted it. the child // component also has set the placeholder vnode's elm. // in that case we can just return the element and be done. if (isDef(vnode.child)) { initComponent(vnode, insertedVnodeQueue); if (isReactivated) { reactivateComponent(vnode, insertedVnodeQueue, parentElm, refElm); } return true } } } function reactivateComponent (vnode, insertedVnodeQueue, parentElm, refElm) { var i; // hack for #4339: a reactivated component with inner transition // does not trigger because the inner node's created hooks are not called // again. It's not ideal to involve module-specific logic in here but // there doesn't seem to be a better way to do it. var innerNode = vnode; while (innerNode.child) { innerNode = innerNode.child._vnode; if (isDef(i = innerNode.data) && isDef(i = i.transition)) { for (i = 0; i < cbs.activate.length; ++i) { cbs.activate[i](emptyNode, innerNode); } insertedVnodeQueue.push(innerNode); break } } // unlike a newly created component, // a reactivated keep-alive component doesn't insert itself insert(parentElm, vnode.elm, refElm); } function insert (parent, elm, ref) { if (parent) { nodeOps.insertBefore(parent, elm, ref); } } function createChildren (vnode, children, insertedVnodeQueue) { if (Array.isArray(children)) { for (var i = 0; i < children.length; ++i) { createElm(children[i], insertedVnodeQueue, vnode.elm, null, true); } } else if (isPrimitive(vnode.text)) { nodeOps.appendChild(vnode.elm, nodeOps.createTextNode(vnode.text)); } } function isPatchable (vnode) { while (vnode.child) { vnode = vnode.child._vnode; } return isDef(vnode.tag) } function invokeCreateHooks (vnode, insertedVnodeQueue) { for (var i$1 = 0; i$1 < cbs.create.length; ++i$1) { cbs.create[i$1](emptyNode, vnode); } i = vnode.data.hook; // Reuse variable if (isDef(i)) { if (i.create) { i.create(emptyNode, vnode); } if (i.insert) { insertedVnodeQueue.push(vnode); } } } function initComponent (vnode, insertedVnodeQueue) { if (vnode.data.pendingInsert) { insertedVnodeQueue.push.apply(insertedVnodeQueue, vnode.data.pendingInsert); } vnode.elm = vnode.child.$el; if (isPatchable(vnode)) { invokeCreateHooks(vnode, insertedVnodeQueue); setScope(vnode); } else { // empty component root. // skip all element-related modules except for ref (#3455) registerRef(vnode); // make sure to invoke the insert hook insertedVnodeQueue.push(vnode); } } // set scope id attribute for scoped CSS. // this is implemented as a special case to avoid the overhead // of going through the normal attribute patching process. function setScope (vnode) { var i; if (isDef(i = vnode.context) && isDef(i = i.$options._scopeId)) { nodeOps.setAttribute(vnode.elm, i, ''); } if (isDef(i = activeInstance) && i !== vnode.context && isDef(i = i.$options._scopeId)) { nodeOps.setAttribute(vnode.elm, i, ''); } } function addVnodes (parentElm, refElm, vnodes, startIdx, endIdx, insertedVnodeQueue) { for (; startIdx <= endIdx; ++startIdx) { createElm(vnodes[startIdx], insertedVnodeQueue, parentElm, refElm); } } function invokeDestroyHook (vnode) { var i, j; var data = vnode.data; if (isDef(data)) { if (isDef(i = data.hook) && isDef(i = i.destroy)) { i(vnode); } for (i = 0; i < cbs.destroy.length; ++i) { cbs.destroy[i](vnode); } } if (isDef(i = vnode.children)) { for (j = 0; j < vnode.children.length; ++j) { invokeDestroyHook(vnode.children[j]); } } } function removeVnodes (parentElm, vnodes, startIdx, endIdx) { for (; startIdx <= endIdx; ++startIdx) { var ch = vnodes[startIdx]; if (isDef(ch)) { if (isDef(ch.tag)) { removeAndInvokeRemoveHook(ch); invokeDestroyHook(ch); } else { // Text node nodeOps.removeChild(parentElm, ch.elm); } } } } function removeAndInvokeRemoveHook (vnode, rm) { if (rm || isDef(vnode.data)) { var listeners = cbs.remove.length + 1; if (!rm) { // directly removing rm = createRmCb(vnode.elm, listeners); } else { // we have a recursively passed down rm callback // increase the listeners count rm.listeners += listeners; } // recursively invoke hooks on child component root node if (isDef(i = vnode.child) && isDef(i = i._vnode) && isDef(i.data)) { removeAndInvokeRemoveHook(i, rm); } for (i = 0; i < cbs.remove.length; ++i) { cbs.remove[i](vnode, rm); } if (isDef(i = vnode.data.hook) && isDef(i = i.remove)) { i(vnode, rm); } else { rm(); } } else { removeElement(vnode.elm); } } function updateChildren (parentElm, oldCh, newCh, insertedVnodeQueue, removeOnly) { var oldStartIdx = 0; var newStartIdx = 0; var oldEndIdx = oldCh.length - 1; var oldStartVnode = oldCh[0]; var oldEndVnode = oldCh[oldEndIdx]; var newEndIdx = newCh.length - 1; var newStartVnode = newCh[0]; var newEndVnode = newCh[newEndIdx]; var oldKeyToIdx, idxInOld, elmToMove, refElm; // removeOnly is a special flag used only by <transition-group> // to ensure removed elements stay in correct relative positions // during leaving transitions var canMove = !removeOnly; while (oldStartIdx <= oldEndIdx && newStartIdx <= newEndIdx) { if (isUndef(oldStartVnode)) { oldStartVnode = oldCh[++oldStartIdx]; // Vnode has been moved left } else if (isUndef(oldEndVnode)) { oldEndVnode = oldCh[--oldEndIdx]; } else if (sameVnode(oldStartVnode, newStartVnode)) { patchVnode(oldStartVnode, newStartVnode, insertedVnodeQueue); oldStartVnode = oldCh[++oldStartIdx]; newStartVnode = newCh[++newStartIdx]; } else if (sameVnode(oldEndVnode, newEndVnode)) { patchVnode(oldEndVnode, newEndVnode, insertedVnodeQueue); oldEndVnode = oldCh[--oldEndIdx]; newEndVnode = newCh[--newEndIdx]; } else if (sameVnode(oldStartVnode, newEndVnode)) { // Vnode moved right patchVnode(oldStartVnode, newEndVnode, insertedVnodeQueue); canMove && nodeOps.insertBefore(parentElm, oldStartVnode.elm, nodeOps.nextSibling(oldEndVnode.elm)); oldStartVnode = oldCh[++oldStartIdx]; newEndVnode = newCh[--newEndIdx]; } else if (sameVnode(oldEndVnode, newStartVnode)) { // Vnode moved left patchVnode(oldEndVnode, newStartVnode, insertedVnodeQueue); canMove && nodeOps.insertBefore(parentElm, oldEndVnode.elm, oldStartVnode.elm); oldEndVnode = oldCh[--oldEndIdx]; newStartVnode = newCh[++newStartIdx]; } else { if (isUndef(oldKeyToIdx)) { oldKeyToIdx = createKeyToOldIdx(oldCh, oldStartIdx, oldEndIdx); } idxInOld = isDef(newStartVnode.key) ? oldKeyToIdx[newStartVnode.key] : null; if (isUndef(idxInOld)) { // New element createElm(newStartVnode, insertedVnodeQueue, parentElm, oldStartVnode.elm); newStartVnode = newCh[++newStartIdx]; } else { elmToMove = oldCh[idxInOld]; /* istanbul ignore if */ if (process.env.NODE_ENV !== 'production' && !elmToMove) { warn( 'It seems there are duplicate keys that is causing an update error. ' + 'Make sure each v-for item has a unique key.' ); } if (elmToMove.tag !== newStartVnode.tag) { // same key but different element. treat as new element createElm(newStartVnode, insertedVnodeQueue, parentElm, oldStartVnode.elm); newStartVnode = newCh[++newStartIdx]; } else { patchVnode(elmToMove, newStartVnode, insertedVnodeQueue); oldCh[idxInOld] = undefined; canMove && nodeOps.insertBefore(parentElm, newStartVnode.elm, oldStartVnode.elm); newStartVnode = newCh[++newStartIdx]; } } } } if (oldStartIdx > oldEndIdx) { refElm = isUndef(newCh[newEndIdx + 1]) ? null : newCh[newEndIdx + 1].elm; addVnodes(parentElm, refElm, newCh, newStartIdx, newEndIdx, insertedVnodeQueue); } else if (newStartIdx > newEndIdx) { removeVnodes(parentElm, oldCh, oldStartIdx, oldEndIdx); } } function patchVnode (oldVnode, vnode, insertedVnodeQueue, removeOnly) { if (oldVnode === vnode) { return } // reuse element for static trees. // note we only do this if the vnode is cloned - // if the new node is not cloned it means the render functions have been // reset by the hot-reload-api and we need to do a proper re-render. if (vnode.isStatic && oldVnode.isStatic && vnode.key === oldVnode.key && (vnode.isCloned || vnode.isOnce)) { vnode.elm = oldVnode.elm; vnode.child = oldVnode.child; return } var i; var data = vnode.data; var hasData = isDef(data); if (hasData && isDef(i = data.hook) && isDef(i = i.prepatch)) { i(oldVnode, vnode); } var elm = vnode.elm = oldVnode.elm; var oldCh = oldVnode.children; var ch = vnode.children; if (hasData && isPatchable(vnode)) { for (i = 0; i < cbs.update.length; ++i) { cbs.update[i](oldVnode, vnode); } if (isDef(i = data.hook) && isDef(i = i.update)) { i(oldVnode, vnode); } } if (isUndef(vnode.text)) { if (isDef(oldCh) && isDef(ch)) { if (oldCh !== ch) { updateChildren(elm, oldCh, ch, insertedVnodeQueue, removeOnly); } } else if (isDef(ch)) { if (isDef(oldVnode.text)) { nodeOps.setTextContent(elm, ''); } addVnodes(elm, null, ch, 0, ch.length - 1, insertedVnodeQueue); } else if (isDef(oldCh)) { removeVnodes(elm, oldCh, 0, oldCh.length - 1); } else if (isDef(oldVnode.text)) { nodeOps.setTextContent(elm, ''); } } else if (oldVnode.text !== vnode.text) { nodeOps.setTextContent(elm, vnode.text); } if (hasData) { if (isDef(i = data.hook) && isDef(i = i.postpatch)) { i(oldVnode, vnode); } } } function invokeInsertHook (vnode, queue, initial) { // delay insert hooks for component root nodes, invoke them after the // element is really inserted if (initial && vnode.parent) { vnode.parent.data.pendingInsert = queue; } else { for (var i = 0; i < queue.length; ++i) { queue[i].data.hook.insert(queue[i]); } } } var bailed = false; function hydrate (elm, vnode, insertedVnodeQueue) { if (process.env.NODE_ENV !== 'production') { if (!assertNodeMatch(elm, vnode)) { return false } } vnode.elm = elm; var tag = vnode.tag; var data = vnode.data; var children = vnode.children; if (isDef(data)) { if (isDef(i = data.hook) && isDef(i = i.init)) { i(vnode, true /* hydrating */); } if (isDef(i = vnode.child)) { // child component. it should have hydrated its own tree. initComponent(vnode, insertedVnodeQueue); return true } } if (isDef(tag)) { if (isDef(children)) { var childNodes = nodeOps.childNodes(elm); // empty element, allow client to pick up and populate children if (!childNodes.length) { createChildren(vnode, children, insertedVnodeQueue); } else { var childrenMatch = true; if (childNodes.length !== children.length) { childrenMatch = false; } else { for (var i$1 = 0; i$1 < children.length; i$1++) { if (!hydrate(childNodes[i$1], children[i$1], insertedVnodeQueue)) { childrenMatch = false; break } } } if (!childrenMatch) { if (process.env.NODE_ENV !== 'production' && typeof console !== 'undefined' && !bailed) { bailed = true; console.warn('Parent: ', elm); console.warn('Mismatching childNodes vs. VNodes: ', childNodes, children); } return false } } } if (isDef(data)) { invokeCreateHooks(vnode, insertedVnodeQueue); } } return true } function assertNodeMatch (node, vnode) { if (vnode.tag) { return ( vnode.tag.indexOf('vue-component') === 0 || vnode.tag.toLowerCase() === nodeOps.tagName(node).toLowerCase() ) } else { return _toString(vnode.text) === node.data } } return function patch (oldVnode, vnode, hydrating, removeOnly, parentElm, refElm) { if (!vnode) { if (oldVnode) { invokeDestroyHook(oldVnode); } return } var elm, parent; var isInitialPatch = false; var insertedVnodeQueue = []; if (!oldVnode) { // empty mount (likely as component), create new root element isInitialPatch = true; createElm(vnode, insertedVnodeQueue, parentElm, refElm); } else { var isRealElement = isDef(oldVnode.nodeType); if (!isRealElement && sameVnode(oldVnode, vnode)) { // patch existing root node patchVnode(oldVnode, vnode, insertedVnodeQueue, removeOnly); } else { if (isRealElement) { // mounting to a real element // check if this is server-rendered content and if we can perform // a successful hydration. if (oldVnode.nodeType === 1 && oldVnode.hasAttribute('server-rendered')) { oldVnode.removeAttribute('server-rendered'); hydrating = true; } if (hydrating) { if (hydrate(oldVnode, vnode, insertedVnodeQueue)) { invokeInsertHook(vnode, insertedVnodeQueue, true); return oldVnode } else if (process.env.NODE_ENV !== 'production') { warn( 'The client-side rendered virtual DOM tree is not matching ' + 'server-rendered content. This is likely caused by incorrect ' + 'HTML markup, for example nesting block-level elements inside ' + '<p>, or missing <tbody>. Bailing hydration and performing ' + 'full client-side render.' ); } } // either not server-rendered, or hydration failed. // create an empty node and replace it oldVnode = emptyNodeAt(oldVnode); } // replacing existing element elm = oldVnode.elm; parent = nodeOps.parentNode(elm); createElm(vnode, insertedVnodeQueue, parent, nodeOps.nextSibling(elm)); if (vnode.parent) { // component root element replaced. // update parent placeholder node element, recursively var ancestor = vnode.parent; while (ancestor) { ancestor.elm = vnode.elm; ancestor = ancestor.parent; } if (isPatchable(vnode)) { for (var i = 0; i < cbs.create.length; ++i) { cbs.create[i](emptyNode, vnode.parent); } } } if (parent !== null) { removeVnodes(parent, [oldVnode], 0, 0); } else if (isDef(oldVnode.tag)) { invokeDestroyHook(oldVnode); } } } invokeInsertHook(vnode, insertedVnodeQueue, isInitialPatch); return vnode.elm } } /* */ var directives = { create: updateDirectives, update: updateDirectives, destroy: function unbindDirectives (vnode) { updateDirectives(vnode, emptyNode); } }; function updateDirectives ( oldVnode, vnode ) { if (!oldVnode.data.directives && !vnode.data.directives) { return } var isCreate = oldVnode === emptyNode; var oldDirs = normalizeDirectives$1(oldVnode.data.directives, oldVnode.context); var newDirs = normalizeDirectives$1(vnode.data.directives, vnode.context); var dirsWithInsert = []; var dirsWithPostpatch = []; var key, oldDir, dir; for (key in newDirs) { oldDir = oldDirs[key]; dir = newDirs[key]; if (!oldDir) { // new directive, bind callHook$1(dir, 'bind', vnode, oldVnode); if (dir.def && dir.def.inserted) { dirsWithInsert.push(dir); } } else { // existing directive, update dir.oldValue = oldDir.value; callHook$1(dir, 'update', vnode, oldVnode); if (dir.def && dir.def.componentUpdated) { dirsWithPostpatch.push(dir); } } } if (dirsWithInsert.length) { var callInsert = function () { dirsWithInsert.forEach(function (dir) { callHook$1(dir, 'inserted', vnode, oldVnode); }); }; if (isCreate) { mergeVNodeHook(vnode.data.hook || (vnode.data.hook = {}), 'insert', callInsert, 'dir-insert'); } else { callInsert(); } } if (dirsWithPostpatch.length) { mergeVNodeHook(vnode.data.hook || (vnode.data.hook = {}), 'postpatch', function () { dirsWithPostpatch.forEach(function (dir) { callHook$1(dir, 'componentUpdated', vnode, oldVnode); }); }, 'dir-postpatch'); } if (!isCreate) { for (key in oldDirs) { if (!newDirs[key]) { // no longer present, unbind callHook$1(oldDirs[key], 'unbind', oldVnode); } } } } var emptyModifiers = Object.create(null); function normalizeDirectives$1 ( dirs, vm ) { var res = Object.create(null); if (!dirs) { return res } var i, dir; for (i = 0; i < dirs.length; i++) { dir = dirs[i]; if (!dir.modifiers) { dir.modifiers = emptyModifiers; } res[getRawDirName(dir)] = dir; dir.def = resolveAsset(vm.$options, 'directives', dir.name, true); } return res } function getRawDirName (dir) { return dir.rawName || ((dir.name) + "." + (Object.keys(dir.modifiers || {}).join('.'))) } function callHook$1 (dir, hook, vnode, oldVnode) { var fn = dir.def && dir.def[hook]; if (fn) { fn(vnode.elm, dir, vnode, oldVnode); } } var baseModules = [ ref, directives ]; /* */ function updateAttrs (oldVnode, vnode) { if (!oldVnode.data.attrs && !vnode.data.attrs) { return } var key, cur, old; var elm = vnode.elm; var oldAttrs = oldVnode.data.attrs || {}; var attrs = vnode.data.attrs || {}; // clone observed objects, as the user probably wants to mutate it if (attrs.__ob__) { attrs = vnode.data.attrs = extend({}, attrs); } for (key in attrs) { cur = attrs[key]; old = oldAttrs[key]; if (old !== cur) { setAttr(elm, key, cur); } } for (key in oldAttrs) { if (attrs[key] == null) { if (isXlink(key)) { elm.removeAttributeNS(xlinkNS, getXlinkProp(key)); } else if (!isEnumeratedAttr(key)) { elm.removeAttribute(key); } } } } function setAttr (el, key, value) { if (isBooleanAttr(key)) { // set attribute for blank value // e.g. <option disabled>Select one</option> if (isFalsyAttrValue(value)) { el.removeAttribute(key); } else { el.setAttribute(key, key); } } else if (isEnumeratedAttr(key)) { el.setAttribute(key, isFalsyAttrValue(value) || value === 'false' ? 'false' : 'true'); } else if (isXlink(key)) { if (isFalsyAttrValue(value)) { el.removeAttributeNS(xlinkNS, getXlinkProp(key)); } else { el.setAttributeNS(xlinkNS, key, value); } } else { if (isFalsyAttrValue(value)) { el.removeAttribute(key); } else { el.setAttribute(key, value); } } } var attrs = { create: updateAttrs, update: updateAttrs }; /* */ function updateClass (oldVnode, vnode) { var el = vnode.elm; var data = vnode.data; var oldData = oldVnode.data; if (!data.staticClass && !data.class && (!oldData || (!oldData.staticClass && !oldData.class))) { return } var cls = genClassForVnode(vnode); // handle transition classes var transitionClass = el._transitionClasses; if (transitionClass) { cls = concat(cls, stringifyClass(transitionClass)); } // set the class if (cls !== el._prevClass) { el.setAttribute('class', cls); el._prevClass = cls; } } var klass = { create: updateClass, update: updateClass }; // skip type checking this file because we need to attach private properties // to elements function updateDOMListeners (oldVnode, vnode) { if (!oldVnode.data.on && !vnode.data.on) { return } var on = vnode.data.on || {}; var oldOn = oldVnode.data.on || {}; var add = vnode.elm._v_add || ( vnode.elm._v_add = function (event, handler, once, capture) { if (once) { var oldHandler = handler; handler = function (ev) { remove(event, handler, capture); arguments.length === 1 ? oldHandler(ev) : oldHandler.apply(null, arguments); }; } vnode.elm.addEventListener(event, handler, capture); } ); var remove = vnode.elm._v_remove || ( vnode.elm._v_remove = function (event, handler, capture) { vnode.elm.removeEventListener(event, handler, capture); } ); updateListeners(on, oldOn, add, remove, vnode.context); } var events = { create: updateDOMListeners, update: updateDOMListeners }; /* */ function updateDOMProps (oldVnode, vnode) { if (!oldVnode.data.domProps && !vnode.data.domProps) { return } var key, cur; var elm = vnode.elm; var oldProps = oldVnode.data.domProps || {}; var props = vnode.data.domProps || {}; // clone observed objects, as the user probably wants to mutate it if (props.__ob__) { props = vnode.data.domProps = extend({}, props); } for (key in oldProps) { if (props[key] == null) { elm[key] = ''; } } for (key in props) { cur = props[key]; // ignore children if the node has textContent or innerHTML, // as these will throw away existing DOM nodes and cause removal errors // on subsequent patches (#3360) if (key === 'textContent' || key === 'innerHTML') { if (vnode.children) { vnode.children.length = 0; } if (cur === oldProps[key]) { continue } } if (key === 'value') { // store value as _value as well since // non-string values will be stringified elm._value = cur; // avoid resetting cursor position when value is the same var strCur = cur == null ? '' : String(cur); if (elm.value !== strCur && !elm.composing) { elm.value = strCur; } } else { elm[key] = cur; } } } var domProps = { create: updateDOMProps, update: updateDOMProps }; /* */ var parseStyleText = cached(function (cssText) { var res = {}; var listDelimiter = /;(?![^(]*\))/g; var propertyDelimiter = /:(.+)/; cssText.split(listDelimiter).forEach(function (item) { if (item) { var tmp = item.split(propertyDelimiter); tmp.length > 1 && (res[tmp[0].trim()] = tmp[1].trim()); } }); return res }); // merge static and dynamic style data on the same vnode function normalizeStyleData (data) { var style = normalizeStyleBinding(data.style); // static style is pre-processed into an object during compilation // and is always a fresh object, so it's safe to merge into it return data.staticStyle ? extend(data.staticStyle, style) : style } // normalize possible array / string values into Object function normalizeStyleBinding (bindingStyle) { if (Array.isArray(bindingStyle)) { return toObject(bindingStyle) } if (typeof bindingStyle === 'string') { return parseStyleText(bindingStyle) } return bindingStyle } /** * parent component style should be after child's * so that parent component's style could override it */ function getStyle (vnode, checkChild) { var res = {}; var styleData; if (checkChild) { var childNode = vnode; while (childNode.child) { childNode = childNode.child._vnode; if (childNode.data && (styleData = normalizeStyleData(childNode.data))) { extend(res, styleData); } } } if ((styleData = normalizeStyleData(vnode.data))) { extend(res, styleData); } var parentNode = vnode; while ((parentNode = parentNode.parent)) { if (parentNode.data && (styleData = normalizeStyleData(parentNode.data))) { extend(res, styleData); } } return res } /* */ var cssVarRE = /^--/; var importantRE = /\s*!important$/; var setProp = function (el, name, val) { /* istanbul ignore if */ if (cssVarRE.test(name)) { el.style.setProperty(name, val); } else if (importantRE.test(val)) { el.style.setProperty(name, val.replace(importantRE, ''), 'important'); } else { el.style[normalize(name)] = val; } }; var prefixes = ['Webkit', 'Moz', 'ms']; var testEl; var normalize = cached(function (prop) { testEl = testEl || document.createElement('div'); prop = camelize(prop); if (prop !== 'filter' && (prop in testEl.style)) { return prop } var upper = prop.charAt(0).toUpperCase() + prop.slice(1); for (var i = 0; i < prefixes.length; i++) { var prefixed = prefixes[i] + upper; if (prefixed in testEl.style) { return prefixed } } }); function updateStyle (oldVnode, vnode) { var data = vnode.data; var oldData = oldVnode.data; if (!data.staticStyle && !data.style && !oldData.staticStyle && !oldData.style) { return } var cur, name; var el = vnode.elm; var oldStaticStyle = oldVnode.data.staticStyle; var oldStyleBinding = oldVnode.data.style || {}; // if static style exists, stylebinding already merged into it when doing normalizeStyleData var oldStyle = oldStaticStyle || oldStyleBinding; var style = normalizeStyleBinding(vnode.data.style) || {}; vnode.data.style = style.__ob__ ? extend({}, style) : style; var newStyle = getStyle(vnode, true); for (name in oldStyle) { if (newStyle[name] == null) { setProp(el, name, ''); } } for (name in newStyle) { cur = newStyle[name]; if (cur !== oldStyle[name]) { // ie9 setting to null has no effect, must use empty string setProp(el, name, cur == null ? '' : cur); } } } var style = { create: updateStyle, update: updateStyle }; /* */ /** * Add class with compatibility for SVG since classList is not supported on * SVG elements in IE */ function addClass (el, cls) { /* istanbul ignore if */ if (!cls || !cls.trim()) { return } /* istanbul ignore else */ if (el.classList) { if (cls.indexOf(' ') > -1) { cls.split(/\s+/).forEach(function (c) { return el.classList.add(c); }); } else { el.classList.add(cls); } } else { var cur = ' ' + el.getAttribute('class') + ' '; if (cur.indexOf(' ' + cls + ' ') < 0) { el.setAttribute('class', (cur + cls).trim()); } } } /** * Remove class with compatibility for SVG since classList is not supported on * SVG elements in IE */ function removeClass (el, cls) { /* istanbul ignore if */ if (!cls || !cls.trim()) { return } /* istanbul ignore else */ if (el.classList) { if (cls.indexOf(' ') > -1) { cls.split(/\s+/).forEach(function (c) { return el.classList.remove(c); }); } else { el.classList.remove(cls); } } else { var cur = ' ' + el.getAttribute('class') + ' '; var tar = ' ' + cls + ' '; while (cur.indexOf(tar) >= 0) { cur = cur.replace(tar, ' '); } el.setAttribute('class', cur.trim()); } } /* */ var hasTransition = inBrowser && !isIE9; var TRANSITION = 'transition'; var ANIMATION = 'animation'; // Transition property/event sniffing var transitionProp = 'transition'; var transitionEndEvent = 'transitionend'; var animationProp = 'animation'; var animationEndEvent = 'animationend'; if (hasTransition) { /* istanbul ignore if */ if (window.ontransitionend === undefined && window.onwebkittransitionend !== undefined) { transitionProp = 'WebkitTransition'; transitionEndEvent = 'webkitTransitionEnd'; } if (window.onanimationend === undefined && window.onwebkitanimationend !== undefined) { animationProp = 'WebkitAnimation'; animationEndEvent = 'webkitAnimationEnd'; } } var raf = (inBrowser && window.requestAnimationFrame) || setTimeout; function nextFrame (fn) { raf(function () { raf(fn); }); } function addTransitionClass (el, cls) { (el._transitionClasses || (el._transitionClasses = [])).push(cls); addClass(el, cls); } function removeTransitionClass (el, cls) { if (el._transitionClasses) { remove$1(el._transitionClasses, cls); } removeClass(el, cls); } function whenTransitionEnds ( el, expectedType, cb ) { var ref = getTransitionInfo(el, expectedType); var type = ref.type; var timeout = ref.timeout; var propCount = ref.propCount; if (!type) { return cb() } var event = type === TRANSITION ? transitionEndEvent : animationEndEvent; var ended = 0; var end = function () { el.removeEventListener(event, onEnd); cb(); }; var onEnd = function (e) { if (e.target === el) { if (++ended >= propCount) { end(); } } }; setTimeout(function () { if (ended < propCount) { end(); } }, timeout + 1); el.addEventListener(event, onEnd); } var transformRE = /\b(transform|all)(,|$)/; function getTransitionInfo (el, expectedType) { var styles = window.getComputedStyle(el); var transitioneDelays = styles[transitionProp + 'Delay'].split(', '); var transitionDurations = styles[transitionProp + 'Duration'].split(', '); var transitionTimeout = getTimeout(transitioneDelays, transitionDurations); var animationDelays = styles[animationProp + 'Delay'].split(', '); var animationDurations = styles[animationProp + 'Duration'].split(', '); var animationTimeout = getTimeout(animationDelays, animationDurations); var type; var timeout = 0; var propCount = 0; /* istanbul ignore if */ if (expectedType === TRANSITION) { if (transitionTimeout > 0) { type = TRANSITION; timeout = transitionTimeout; propCount = transitionDurations.length; } } else if (expectedType === ANIMATION) { if (animationTimeout > 0) { type = ANIMATION; timeout = animationTimeout; propCount = animationDurations.length; } } else { timeout = Math.max(transitionTimeout, animationTimeout); type = timeout > 0 ? transitionTimeout > animationTimeout ? TRANSITION : ANIMATION : null; propCount = type ? type === TRANSITION ? transitionDurations.length : animationDurations.length : 0; } var hasTransform = type === TRANSITION && transformRE.test(styles[transitionProp + 'Property']); return { type: type, timeout: timeout, propCount: propCount, hasTransform: hasTransform } } function getTimeout (delays, durations) { /* istanbul ignore next */ while (delays.length < durations.length) { delays = delays.concat(delays); } return Math.max.apply(null, durations.map(function (d, i) { return toMs(d) + toMs(delays[i]) })) } function toMs (s) { return Number(s.slice(0, -1)) * 1000 } /* */ function enter (vnode) { var el = vnode.elm; // call leave callback now if (el._leaveCb) { el._leaveCb.cancelled = true; el._leaveCb(); } var data = resolveTransition(vnode.data.transition); if (!data) { return } /* istanbul ignore if */ if (el._enterCb || el.nodeType !== 1) { return } var css = data.css; var type = data.type; var enterClass = data.enterClass; var enterActiveClass = data.enterActiveClass; var appearClass = data.appearClass; var appearActiveClass = data.appearActiveClass; var beforeEnter = data.beforeEnter; var enter = data.enter; var afterEnter = data.afterEnter; var enterCancelled = data.enterCancelled; var beforeAppear = data.beforeAppear; var appear = data.appear; var afterAppear = data.afterAppear; var appearCancelled = data.appearCancelled; // activeInstance will always be the <transition> component managing this // transition. One edge case to check is when the <transition> is placed // as the root node of a child component. In that case we need to check // <transition>'s parent for appear check. var context = activeInstance; var transitionNode = activeInstance.$vnode; while (transitionNode && transitionNode.parent) { transitionNode = transitionNode.parent; context = transitionNode.context; } var isAppear = !context._isMounted || !vnode.isRootInsert; if (isAppear && !appear && appear !== '') { return } var startClass = isAppear ? appearClass : enterClass; var activeClass = isAppear ? appearActiveClass : enterActiveClass; var beforeEnterHook = isAppear ? (beforeAppear || beforeEnter) : beforeEnter; var enterHook = isAppear ? (typeof appear === 'function' ? appear : enter) : enter; var afterEnterHook = isAppear ? (afterAppear || afterEnter) : afterEnter; var enterCancelledHook = isAppear ? (appearCancelled || enterCancelled) : enterCancelled; var expectsCSS = css !== false && !isIE9; var userWantsControl = enterHook && // enterHook may be a bound method which exposes // the length of original fn as _length (enterHook._length || enterHook.length) > 1; var cb = el._enterCb = once(function () { if (expectsCSS) { removeTransitionClass(el, activeClass); } if (cb.cancelled) { if (expectsCSS) { removeTransitionClass(el, startClass); } enterCancelledHook && enterCancelledHook(el); } else { afterEnterHook && afterEnterHook(el); } el._enterCb = null; }); if (!vnode.data.show) { // remove pending leave element on enter by injecting an insert hook mergeVNodeHook(vnode.data.hook || (vnode.data.hook = {}), 'insert', function () { var parent = el.parentNode; var pendingNode = parent && parent._pending && parent._pending[vnode.key]; if (pendingNode && pendingNode.context === vnode.context && pendingNode.tag === vnode.tag && pendingNode.elm._leaveCb) { pendingNode.elm._leaveCb(); } enterHook && enterHook(el, cb); }, 'transition-insert'); } // start enter transition beforeEnterHook && beforeEnterHook(el); if (expectsCSS) { addTransitionClass(el, startClass); addTransitionClass(el, activeClass); nextFrame(function () { removeTransitionClass(el, startClass); if (!cb.cancelled && !userWantsControl) { whenTransitionEnds(el, type, cb); } }); } if (vnode.data.show) { enterHook && enterHook(el, cb); } if (!expectsCSS && !userWantsControl) { cb(); } } function leave (vnode, rm) { var el = vnode.elm; // call enter callback now if (el._enterCb) { el._enterCb.cancelled = true; el._enterCb(); } var data = resolveTransition(vnode.data.transition); if (!data) { return rm() } /* istanbul ignore if */ if (el._leaveCb || el.nodeType !== 1) { return } var css = data.css; var type = data.type; var leaveClass = data.leaveClass; var leaveActiveClass = data.leaveActiveClass; var beforeLeave = data.beforeLeave; var leave = data.leave; var afterLeave = data.afterLeave; var leaveCancelled = data.leaveCancelled; var delayLeave = data.delayLeave; var expectsCSS = css !== false && !isIE9; var userWantsControl = leave && // leave hook may be a bound method which exposes // the length of original fn as _length (leave._length || leave.length) > 1; var cb = el._leaveCb = once(function () { if (el.parentNode && el.parentNode._pending) { el.parentNode._pending[vnode.key] = null; } if (expectsCSS) { removeTransitionClass(el, leaveActiveClass); } if (cb.cancelled) { if (expectsCSS) { removeTransitionClass(el, leaveClass); } leaveCancelled && leaveCancelled(el); } else { rm(); afterLeave && afterLeave(el); } el._leaveCb = null; }); if (delayLeave) { delayLeave(performLeave); } else { performLeave(); } function performLeave () { // the delayed leave may have already been cancelled if (cb.cancelled) { return } // record leaving element if (!vnode.data.show) { (el.parentNode._pending || (el.parentNode._pending = {}))[vnode.key] = vnode; } beforeLeave && beforeLeave(el); if (expectsCSS) { addTransitionClass(el, leaveClass); addTransitionClass(el, leaveActiveClass); nextFrame(function () { removeTransitionClass(el, leaveClass); if (!cb.cancelled && !userWantsControl) { whenTransitionEnds(el, type, cb); } }); } leave && leave(el, cb); if (!expectsCSS && !userWantsControl) { cb(); } } } function resolveTransition (def$$1) { if (!def$$1) { return } /* istanbul ignore else */ if (typeof def$$1 === 'object') { var res = {}; if (def$$1.css !== false) { extend(res, autoCssTransition(def$$1.name || 'v')); } extend(res, def$$1); return res } else if (typeof def$$1 === 'string') { return autoCssTransition(def$$1) } } var autoCssTransition = cached(function (name) { return { enterClass: (name + "-enter"), leaveClass: (name + "-leave"), appearClass: (name + "-enter"), enterActiveClass: (name + "-enter-active"), leaveActiveClass: (name + "-leave-active"), appearActiveClass: (name + "-enter-active") } }); function once (fn) { var called = false; return function () { if (!called) { called = true; fn(); } } } function _enter (_, vnode) { if (!vnode.data.show) { enter(vnode); } } var transition = inBrowser ? { create: _enter, activate: _enter, remove: function remove (vnode, rm) { /* istanbul ignore else */ if (!vnode.data.show) { leave(vnode, rm); } else { rm(); } } } : {}; var platformModules = [ attrs, klass, events, domProps, style, transition ]; /* */ // the directive module should be applied last, after all // built-in modules have been applied. var modules = platformModules.concat(baseModules); var patch$1 = createPatchFunction({ nodeOps: nodeOps, modules: modules }); /** * Not type checking this file because flow doesn't like attaching * properties to Elements. */ var modelableTagRE = /^input|select|textarea|vue-component-[0-9]+(-[0-9a-zA-Z_-]*)?$/; /* istanbul ignore if */ if (isIE9) { // http://www.matts411.com/post/internet-explorer-9-oninput/ document.addEventListener('selectionchange', function () { var el = document.activeElement; if (el && el.vmodel) { trigger(el, 'input'); } }); } var model = { inserted: function inserted (el, binding, vnode) { if (process.env.NODE_ENV !== 'production') { if (!modelableTagRE.test(vnode.tag)) { warn( "v-model is not supported on element type: <" + (vnode.tag) + ">. " + 'If you are working with contenteditable, it\'s recommended to ' + 'wrap a library dedicated for that purpose inside a custom component.', vnode.context ); } } if (vnode.tag === 'select') { var cb = function () { setSelected(el, binding, vnode.context); }; cb(); /* istanbul ignore if */ if (isIE || isEdge) { setTimeout(cb, 0); } } else if ( (vnode.tag === 'textarea' || el.type === 'text') && !binding.modifiers.lazy ) { if (!isAndroid) { el.addEventListener('compositionstart', onCompositionStart); el.addEventListener('compositionend', onCompositionEnd); } /* istanbul ignore if */ if (isIE9) { el.vmodel = true; } } }, componentUpdated: function componentUpdated (el, binding, vnode) { if (vnode.tag === 'select') { setSelected(el, binding, vnode.context); // in case the options rendered by v-for have changed, // it's possible that the value is out-of-sync with the rendered options. // detect such cases and filter out values that no longer has a matching // option in the DOM. var needReset = el.multiple ? binding.value.some(function (v) { return hasNoMatchingOption(v, el.options); }) : binding.value !== binding.oldValue && hasNoMatchingOption(binding.value, el.options); if (needReset) { trigger(el, 'change'); } } } }; function setSelected (el, binding, vm) { var value = binding.value; var isMultiple = el.multiple; if (isMultiple && !Array.isArray(value)) { process.env.NODE_ENV !== 'production' && warn( "<select multiple v-model=\"" + (binding.expression) + "\"> " + "expects an Array value for its binding, but got " + (Object.prototype.toString.call(value).slice(8, -1)), vm ); return } var selected, option; for (var i = 0, l = el.options.length; i < l; i++) { option = el.options[i]; if (isMultiple) { selected = looseIndexOf(value, getValue(option)) > -1; if (option.selected !== selected) { option.selected = selected; } } else { if (looseEqual(getValue(option), value)) { if (el.selectedIndex !== i) { el.selectedIndex = i; } return } } } if (!isMultiple) { el.selectedIndex = -1; } } function hasNoMatchingOption (value, options) { for (var i = 0, l = options.length; i < l; i++) { if (looseEqual(getValue(options[i]), value)) { return false } } return true } function getValue (option) { return '_value' in option ? option._value : option.value } function onCompositionStart (e) { e.target.composing = true; } function onCompositionEnd (e) { e.target.composing = false; trigger(e.target, 'input'); } function trigger (el, type) { var e = document.createEvent('HTMLEvents'); e.initEvent(type, true, true); el.dispatchEvent(e); } /* */ // recursively search for possible transition defined inside the component root function locateNode (vnode) { return vnode.child && (!vnode.data || !vnode.data.transition) ? locateNode(vnode.child._vnode) : vnode } var show = { bind: function bind (el, ref, vnode) { var value = ref.value; vnode = locateNode(vnode); var transition = vnode.data && vnode.data.transition; if (value && transition && !isIE9) { enter(vnode); } var originalDisplay = el.style.display === 'none' ? '' : el.style.display; el.style.display = value ? originalDisplay : 'none'; el.__vOriginalDisplay = originalDisplay; }, update: function update (el, ref, vnode) { var value = ref.value; var oldValue = ref.oldValue; /* istanbul ignore if */ if (value === oldValue) { return } vnode = locateNode(vnode); var transition = vnode.data && vnode.data.transition; if (transition && !isIE9) { if (value) { enter(vnode); el.style.display = el.__vOriginalDisplay; } else { leave(vnode, function () { el.style.display = 'none'; }); } } else { el.style.display = value ? el.__vOriginalDisplay : 'none'; } } }; var platformDirectives = { model: model, show: show }; /* */ // Provides transition support for a single element/component. // supports transition mode (out-in / in-out) var transitionProps = { name: String, appear: Boolean, css: Boolean, mode: String, type: String, enterClass: String, leaveClass: String, enterActiveClass: String, leaveActiveClass: String, appearClass: String, appearActiveClass: String }; // in case the child is also an abstract component, e.g. <keep-alive> // we want to recursively retrieve the real component to be rendered function getRealChild (vnode) { var compOptions = vnode && vnode.componentOptions; if (compOptions && compOptions.Ctor.options.abstract) { return getRealChild(getFirstComponentChild(compOptions.children)) } else { return vnode } } function extractTransitionData (comp) { var data = {}; var options = comp.$options; // props for (var key in options.propsData) { data[key] = comp[key]; } // events. // extract listeners and pass them directly to the transition methods var listeners = options._parentListeners; for (var key$1 in listeners) { data[camelize(key$1)] = listeners[key$1].fn; } return data } function placeholder (h, rawChild) { return /\d-keep-alive$/.test(rawChild.tag) ? h('keep-alive') : null } function hasParentTransition (vnode) { while ((vnode = vnode.parent)) { if (vnode.data.transition) { return true } } } var Transition = { name: 'transition', props: transitionProps, abstract: true, render: function render (h) { var this$1 = this; var children = this.$slots.default; if (!children) { return } // filter out text nodes (possible whitespaces) children = children.filter(function (c) { return c.tag; }); /* istanbul ignore if */ if (!children.length) { return } // warn multiple elements if (process.env.NODE_ENV !== 'production' && children.length > 1) { warn( '<transition> can only be used on a single element. Use ' + '<transition-group> for lists.', this.$parent ); } var mode = this.mode; // warn invalid mode if (process.env.NODE_ENV !== 'production' && mode && mode !== 'in-out' && mode !== 'out-in') { warn( 'invalid <transition> mode: ' + mode, this.$parent ); } var rawChild = children[0]; // if this is a component root node and the component's // parent container node also has transition, skip. if (hasParentTransition(this.$vnode)) { return rawChild } // apply transition data to child // use getRealChild() to ignore abstract components e.g. keep-alive var child = getRealChild(rawChild); /* istanbul ignore if */ if (!child) { return rawChild } if (this._leaving) { return placeholder(h, rawChild) } var key = child.key = child.key == null || child.isStatic ? ("__v" + (child.tag + this._uid) + "__") : child.key; var data = (child.data || (child.data = {})).transition = extractTransitionData(this); var oldRawChild = this._vnode; var oldChild = getRealChild(oldRawChild); // mark v-show // so that the transition module can hand over the control to the directive if (child.data.directives && child.data.directives.some(function (d) { return d.name === 'show'; })) { child.data.show = true; } if (oldChild && oldChild.data && oldChild.key !== key) { // replace old child transition data with fresh one // important for dynamic transitions! var oldData = oldChild.data.transition = extend({}, data); // handle transition mode if (mode === 'out-in') { // return placeholder node and queue update when leave finishes this._leaving = true; mergeVNodeHook(oldData, 'afterLeave', function () { this$1._leaving = false; this$1.$forceUpdate(); }, key); return placeholder(h, rawChild) } else if (mode === 'in-out') { var delayedLeave; var performLeave = function () { delayedLeave(); }; mergeVNodeHook(data, 'afterEnter', performLeave, key); mergeVNodeHook(data, 'enterCancelled', performLeave, key); mergeVNodeHook(oldData, 'delayLeave', function (leave) { delayedLeave = leave; }, key); } } return rawChild } }; /* */ // Provides transition support for list items. // supports move transitions using the FLIP technique. // Because the vdom's children update algorithm is "unstable" - i.e. // it doesn't guarantee the relative positioning of removed elements, // we force transition-group to update its children into two passes: // in the first pass, we remove all nodes that need to be removed, // triggering their leaving transition; in the second pass, we insert/move // into the final disired state. This way in the second pass removed // nodes will remain where they should be. var props = extend({ tag: String, moveClass: String }, transitionProps); delete props.mode; var TransitionGroup = { props: props, render: function render (h) { var tag = this.tag || this.$vnode.data.tag || 'span'; var map = Object.create(null); var prevChildren = this.prevChildren = this.children; var rawChildren = this.$slots.default || []; var children = this.children = []; var transitionData = extractTransitionData(this); for (var i = 0; i < rawChildren.length; i++) { var c = rawChildren[i]; if (c.tag) { if (c.key != null && String(c.key).indexOf('__vlist') !== 0) { children.push(c); map[c.key] = c ;(c.data || (c.data = {})).transition = transitionData; } else if (process.env.NODE_ENV !== 'production') { var opts = c.componentOptions; var name = opts ? (opts.Ctor.options.name || opts.tag) : c.tag; warn(("<transition-group> children must be keyed: <" + name + ">")); } } } if (prevChildren) { var kept = []; var removed = []; for (var i$1 = 0; i$1 < prevChildren.length; i$1++) { var c$1 = prevChildren[i$1]; c$1.data.transition = transitionData; c$1.data.pos = c$1.elm.getBoundingClientRect(); if (map[c$1.key]) { kept.push(c$1); } else { removed.push(c$1); } } this.kept = h(tag, null, kept); this.removed = removed; } return h(tag, null, children) }, beforeUpdate: function beforeUpdate () { // force removing pass this.__patch__( this._vnode, this.kept, false, // hydrating true // removeOnly (!important, avoids unnecessary moves) ); this._vnode = this.kept; }, updated: function updated () { var children = this.prevChildren; var moveClass = this.moveClass || ((this.name || 'v') + '-move'); if (!children.length || !this.hasMove(children[0].elm, moveClass)) { return } // we divide the work into three loops to avoid mixing DOM reads and writes // in each iteration - which helps prevent layout thrashing. children.forEach(callPendingCbs); children.forEach(recordPosition); children.forEach(applyTranslation); // force reflow to put everything in position var f = document.body.offsetHeight; // eslint-disable-line children.forEach(function (c) { if (c.data.moved) { var el = c.elm; var s = el.style; addTransitionClass(el, moveClass); s.transform = s.WebkitTransform = s.transitionDuration = ''; el.addEventListener(transitionEndEvent, el._moveCb = function cb (e) { if (!e || /transform$/.test(e.propertyName)) { el.removeEventListener(transitionEndEvent, cb); el._moveCb = null; removeTransitionClass(el, moveClass); } }); } }); }, methods: { hasMove: function hasMove (el, moveClass) { /* istanbul ignore if */ if (!hasTransition) { return false } if (this._hasMove != null) { return this._hasMove } addTransitionClass(el, moveClass); var info = getTransitionInfo(el); removeTransitionClass(el, moveClass); return (this._hasMove = info.hasTransform) } } }; function callPendingCbs (c) { /* istanbul ignore if */ if (c.elm._moveCb) { c.elm._moveCb(); } /* istanbul ignore if */ if (c.elm._enterCb) { c.elm._enterCb(); } } function recordPosition (c) { c.data.newPos = c.elm.getBoundingClientRect(); } function applyTranslation (c) { var oldPos = c.data.pos; var newPos = c.data.newPos; var dx = oldPos.left - newPos.left; var dy = oldPos.top - newPos.top; if (dx || dy) { c.data.moved = true; var s = c.elm.style; s.transform = s.WebkitTransform = "translate(" + dx + "px," + dy + "px)"; s.transitionDuration = '0s'; } } var platformComponents = { Transition: Transition, TransitionGroup: TransitionGroup }; /* */ // install platform specific utils Vue$3.config.isUnknownElement = isUnknownElement; Vue$3.config.isReservedTag = isReservedTag; Vue$3.config.getTagNamespace = getTagNamespace; Vue$3.config.mustUseProp = mustUseProp; // install platform runtime directives & components extend(Vue$3.options.directives, platformDirectives); extend(Vue$3.options.components, platformComponents); // install platform patch function Vue$3.prototype.__patch__ = inBrowser ? patch$1 : noop; // wrap mount Vue$3.prototype.$mount = function ( el, hydrating ) { el = el && inBrowser ? query(el) : undefined; return this._mount(el, hydrating) }; // devtools global hook /* istanbul ignore next */ setTimeout(function () { if (config.devtools) { if (devtools) { devtools.emit('init', Vue$3); } else if ( process.env.NODE_ENV !== 'production' && inBrowser && /Chrome\/\d+/.test(window.navigator.userAgent) ) { console.log( 'Download the Vue Devtools for a better development experience:\n' + 'https://github.com/vuejs/vue-devtools' ); } } }, 0); /* */ // check whether current browser encodes a char inside attribute values function shouldDecode (content, encoded) { var div = document.createElement('div'); div.innerHTML = "<div a=\"" + content + "\">"; return div.innerHTML.indexOf(encoded) > 0 } // #3663 // IE encodes newlines inside attribute values while other browsers don't var shouldDecodeNewlines = inBrowser ? shouldDecode('\n', '&#10;') : false; /* */ var decoder; function decode (html) { decoder = decoder || document.createElement('div'); decoder.innerHTML = html; return decoder.textContent } /* */ var isUnaryTag = makeMap( 'area,base,br,col,embed,frame,hr,img,input,isindex,keygen,' + 'link,meta,param,source,track,wbr', true ); // Elements that you can, intentionally, leave open // (and which close themselves) var canBeLeftOpenTag = makeMap( 'colgroup,dd,dt,li,options,p,td,tfoot,th,thead,tr,source', true ); // HTML5 tags https://html.spec.whatwg.org/multipage/indices.html#elements-3 // Phrasing Content https://html.spec.whatwg.org/multipage/dom.html#phrasing-content var isNonPhrasingTag = makeMap( 'address,article,aside,base,blockquote,body,caption,col,colgroup,dd,' + 'details,dialog,div,dl,dt,fieldset,figcaption,figure,footer,form,' + 'h1,h2,h3,h4,h5,h6,head,header,hgroup,hr,html,legend,li,menuitem,meta,' + 'optgroup,option,param,rp,rt,source,style,summary,tbody,td,tfoot,th,thead,' + 'title,tr,track', true ); /** * Not type-checking this file because it's mostly vendor code. */ /*! * HTML Parser By John Resig (ejohn.org) * Modified by Juriy "kangax" Zaytsev * Original code by Erik Arvidsson, Mozilla Public License * http://erik.eae.net/simplehtmlparser/simplehtmlparser.js */ // Regular Expressions for parsing tags and attributes var singleAttrIdentifier = /([^\s"'<>/=]+)/; var singleAttrAssign = /(?:=)/; var singleAttrValues = [ // attr value double quotes /"([^"]*)"+/.source, // attr value, single quotes /'([^']*)'+/.source, // attr value, no quotes /([^\s"'=<>`]+)/.source ]; var attribute = new RegExp( '^\\s*' + singleAttrIdentifier.source + '(?:\\s*(' + singleAttrAssign.source + ')' + '\\s*(?:' + singleAttrValues.join('|') + '))?' ); // could use https://www.w3.org/TR/1999/REC-xml-names-19990114/#NT-QName // but for Vue templates we can enforce a simple charset var ncname = '[a-zA-Z_][\\w\\-\\.]*'; var qnameCapture = '((?:' + ncname + '\\:)?' + ncname + ')'; var startTagOpen = new RegExp('^<' + qnameCapture); var startTagClose = /^\s*(\/?)>/; var endTag = new RegExp('^<\\/' + qnameCapture + '[^>]*>'); var doctype = /^<!DOCTYPE [^>]+>/i; var comment = /^<!--/; var conditionalComment = /^<!\[/; var IS_REGEX_CAPTURING_BROKEN = false; 'x'.replace(/x(.)?/g, function (m, g) { IS_REGEX_CAPTURING_BROKEN = g === ''; }); // Special Elements (can contain anything) var isScriptOrStyle = makeMap('script,style', true); var hasLang = function (attr) { return attr.name === 'lang' && attr.value !== 'html'; }; var isSpecialTag = function (tag, isSFC, stack) { if (isScriptOrStyle(tag)) { return true } if (isSFC && stack.length === 1) { // top-level template that has no pre-processor if (tag === 'template' && !stack[0].attrs.some(hasLang)) { return false } else { return true } } return false }; var reCache = {}; var ltRE = /&lt;/g; var gtRE = /&gt;/g; var nlRE = /&#10;/g; var ampRE = /&amp;/g; var quoteRE = /&quot;/g; function decodeAttr (value, shouldDecodeNewlines) { if (shouldDecodeNewlines) { value = value.replace(nlRE, '\n'); } return value .replace(ltRE, '<') .replace(gtRE, '>') .replace(ampRE, '&') .replace(quoteRE, '"') } function parseHTML (html, options) { var stack = []; var expectHTML = options.expectHTML; var isUnaryTag$$1 = options.isUnaryTag || no; var index = 0; var last, lastTag; while (html) { last = html; // Make sure we're not in a script or style element if (!lastTag || !isSpecialTag(lastTag, options.sfc, stack)) { var textEnd = html.indexOf('<'); if (textEnd === 0) { // Comment: if (comment.test(html)) { var commentEnd = html.indexOf('-->'); if (commentEnd >= 0) { advance(commentEnd + 3); continue } } // http://en.wikipedia.org/wiki/Conditional_comment#Downlevel-revealed_conditional_comment if (conditionalComment.test(html)) { var conditionalEnd = html.indexOf(']>'); if (conditionalEnd >= 0) { advance(conditionalEnd + 2); continue } } // Doctype: var doctypeMatch = html.match(doctype); if (doctypeMatch) { advance(doctypeMatch[0].length); continue } // End tag: var endTagMatch = html.match(endTag); if (endTagMatch) { var curIndex = index; advance(endTagMatch[0].length); parseEndTag(endTagMatch[0], endTagMatch[1], curIndex, index); continue } // Start tag: var startTagMatch = parseStartTag(); if (startTagMatch) { handleStartTag(startTagMatch); continue } } var text = (void 0), rest$1 = (void 0), next = (void 0); if (textEnd > 0) { rest$1 = html.slice(textEnd); while ( !endTag.test(rest$1) && !startTagOpen.test(rest$1) && !comment.test(rest$1) && !conditionalComment.test(rest$1) ) { // < in plain text, be forgiving and treat it as text next = rest$1.indexOf('<', 1); if (next < 0) { break } textEnd += next; rest$1 = html.slice(textEnd); } text = html.substring(0, textEnd); advance(textEnd); } if (textEnd < 0) { text = html; html = ''; } if (options.chars && text) { options.chars(text); } } else { var stackedTag = lastTag.toLowerCase(); var reStackedTag = reCache[stackedTag] || (reCache[stackedTag] = new RegExp('([\\s\\S]*?)(</' + stackedTag + '[^>]*>)', 'i')); var endTagLength = 0; var rest = html.replace(reStackedTag, function (all, text, endTag) { endTagLength = endTag.length; if (stackedTag !== 'script' && stackedTag !== 'style' && stackedTag !== 'noscript') { text = text .replace(/<!--([\s\S]*?)-->/g, '$1') .replace(/<!\[CDATA\[([\s\S]*?)]]>/g, '$1'); } if (options.chars) { options.chars(text); } return '' }); index += html.length - rest.length; html = rest; parseEndTag('</' + stackedTag + '>', stackedTag, index - endTagLength, index); } if (html === last && options.chars) { options.chars(html); break } } // Clean up any remaining tags parseEndTag(); function advance (n) { index += n; html = html.substring(n); } function parseStartTag () { var start = html.match(startTagOpen); if (start) { var match = { tagName: start[1], attrs: [], start: index }; advance(start[0].length); var end, attr; while (!(end = html.match(startTagClose)) && (attr = html.match(attribute))) { advance(attr[0].length); match.attrs.push(attr); } if (end) { match.unarySlash = end[1]; advance(end[0].length); match.end = index; return match } } } function handleStartTag (match) { var tagName = match.tagName; var unarySlash = match.unarySlash; if (expectHTML) { if (lastTag === 'p' && isNonPhrasingTag(tagName)) { parseEndTag('', lastTag); } if (canBeLeftOpenTag(tagName) && lastTag === tagName) { parseEndTag('', tagName); } } var unary = isUnaryTag$$1(tagName) || tagName === 'html' && lastTag === 'head' || !!unarySlash; var l = match.attrs.length; var attrs = new Array(l); for (var i = 0; i < l; i++) { var args = match.attrs[i]; // hackish work around FF bug https://bugzilla.mozilla.org/show_bug.cgi?id=369778 if (IS_REGEX_CAPTURING_BROKEN && args[0].indexOf('""') === -1) { if (args[3] === '') { delete args[3]; } if (args[4] === '') { delete args[4]; } if (args[5] === '') { delete args[5]; } } var value = args[3] || args[4] || args[5] || ''; attrs[i] = { name: args[1], value: decodeAttr( value, options.shouldDecodeNewlines ) }; } if (!unary) { stack.push({ tag: tagName, attrs: attrs }); lastTag = tagName; unarySlash = ''; } if (options.start) { options.start(tagName, attrs, unary, match.start, match.end); } } function parseEndTag (tag, tagName, start, end) { var pos; if (start == null) { start = index; } if (end == null) { end = index; } // Find the closest opened tag of the same type if (tagName) { var needle = tagName.toLowerCase(); for (pos = stack.length - 1; pos >= 0; pos--) { if (stack[pos].tag.toLowerCase() === needle) { break } } } else { // If no tag name is provided, clean shop pos = 0; } if (pos >= 0) { // Close all the open elements, up the stack for (var i = stack.length - 1; i >= pos; i--) { if (options.end) { options.end(stack[i].tag, start, end); } } // Remove the open elements from the stack stack.length = pos; lastTag = pos && stack[pos - 1].tag; } else if (tagName.toLowerCase() === 'br') { if (options.start) { options.start(tagName, [], true, start, end); } } else if (tagName.toLowerCase() === 'p') { if (options.start) { options.start(tagName, [], false, start, end); } if (options.end) { options.end(tagName, start, end); } } } } /* */ function parseFilters (exp) { var inSingle = false; var inDouble = false; var inTemplateString = false; var inRegex = false; var curly = 0; var square = 0; var paren = 0; var lastFilterIndex = 0; var c, prev, i, expression, filters; for (i = 0; i < exp.length; i++) { prev = c; c = exp.charCodeAt(i); if (inSingle) { if (c === 0x27 && prev !== 0x5C) { inSingle = false; } } else if (inDouble) { if (c === 0x22 && prev !== 0x5C) { inDouble = false; } } else if (inTemplateString) { if (c === 0x60 && prev !== 0x5C) { inTemplateString = false; } } else if (inRegex) { if (c === 0x2f && prev !== 0x5C) { inRegex = false; } } else if ( c === 0x7C && // pipe exp.charCodeAt(i + 1) !== 0x7C && exp.charCodeAt(i - 1) !== 0x7C && !curly && !square && !paren ) { if (expression === undefined) { // first filter, end of expression lastFilterIndex = i + 1; expression = exp.slice(0, i).trim(); } else { pushFilter(); } } else { switch (c) { case 0x22: inDouble = true; break // " case 0x27: inSingle = true; break // ' case 0x60: inTemplateString = true; break // ` case 0x2f: inRegex = true; break // / case 0x28: paren++; break // ( case 0x29: paren--; break // ) case 0x5B: square++; break // [ case 0x5D: square--; break // ] case 0x7B: curly++; break // { case 0x7D: curly--; break // } } } } if (expression === undefined) { expression = exp.slice(0, i).trim(); } else if (lastFilterIndex !== 0) { pushFilter(); } function pushFilter () { (filters || (filters = [])).push(exp.slice(lastFilterIndex, i).trim()); lastFilterIndex = i + 1; } if (filters) { for (i = 0; i < filters.length; i++) { expression = wrapFilter(expression, filters[i]); } } return expression } function wrapFilter (exp, filter) { var i = filter.indexOf('('); if (i < 0) { // _f: resolveFilter return ("_f(\"" + filter + "\")(" + exp + ")") } else { var name = filter.slice(0, i); var args = filter.slice(i + 1); return ("_f(\"" + name + "\")(" + exp + "," + args) } } /* */ var defaultTagRE = /\{\{((?:.|\n)+?)\}\}/g; var regexEscapeRE = /[-.*+?^${}()|[\]/\\]/g; var buildRegex = cached(function (delimiters) { var open = delimiters[0].replace(regexEscapeRE, '\\$&'); var close = delimiters[1].replace(regexEscapeRE, '\\$&'); return new RegExp(open + '((?:.|\\n)+?)' + close, 'g') }); function parseText ( text, delimiters ) { var tagRE = delimiters ? buildRegex(delimiters) : defaultTagRE; if (!tagRE.test(text)) { return } var tokens = []; var lastIndex = tagRE.lastIndex = 0; var match, index; while ((match = tagRE.exec(text))) { index = match.index; // push text token if (index > lastIndex) { tokens.push(JSON.stringify(text.slice(lastIndex, index))); } // tag token var exp = parseFilters(match[1].trim()); tokens.push(("_s(" + exp + ")")); lastIndex = index + match[0].length; } if (lastIndex < text.length) { tokens.push(JSON.stringify(text.slice(lastIndex))); } return tokens.join('+') } /* */ function baseWarn (msg) { console.error(("[Vue parser]: " + msg)); } function pluckModuleFunction ( modules, key ) { return modules ? modules.map(function (m) { return m[key]; }).filter(function (_) { return _; }) : [] } function addProp (el, name, value) { (el.props || (el.props = [])).push({ name: name, value: value }); } function addAttr (el, name, value) { (el.attrs || (el.attrs = [])).push({ name: name, value: value }); } function addDirective ( el, name, rawName, value, arg, modifiers ) { (el.directives || (el.directives = [])).push({ name: name, rawName: rawName, value: value, arg: arg, modifiers: modifiers }); } function addHandler ( el, name, value, modifiers, important ) { // check capture modifier if (modifiers && modifiers.capture) { delete modifiers.capture; name = '!' + name; // mark the event as captured } if (modifiers && modifiers.once) { delete modifiers.once; name = '~' + name; // mark the event as once } var events; if (modifiers && modifiers.native) { delete modifiers.native; events = el.nativeEvents || (el.nativeEvents = {}); } else { events = el.events || (el.events = {}); } var newHandler = { value: value, modifiers: modifiers }; var handlers = events[name]; /* istanbul ignore if */ if (Array.isArray(handlers)) { important ? handlers.unshift(newHandler) : handlers.push(newHandler); } else if (handlers) { events[name] = important ? [newHandler, handlers] : [handlers, newHandler]; } else { events[name] = newHandler; } } function getBindingAttr ( el, name, getStatic ) { var dynamicValue = getAndRemoveAttr(el, ':' + name) || getAndRemoveAttr(el, 'v-bind:' + name); if (dynamicValue != null) { return parseFilters(dynamicValue) } else if (getStatic !== false) { var staticValue = getAndRemoveAttr(el, name); if (staticValue != null) { return JSON.stringify(staticValue) } } } function getAndRemoveAttr (el, name) { var val; if ((val = el.attrsMap[name]) != null) { var list = el.attrsList; for (var i = 0, l = list.length; i < l; i++) { if (list[i].name === name) { list.splice(i, 1); break } } } return val } var len; var str; var chr; var index$1; var expressionPos; var expressionEndPos; /** * parse directive model to do the array update transform. a[idx] = val => $$a.splice($$idx, 1, val) * * for loop possible cases: * * - test * - test[idx] * - test[test1[idx]] * - test["a"][idx] * - xxx.test[a[a].test1[idx]] * - test.xxx.a["asa"][test1[idx]] * */ function parseModel (val) { str = val; len = str.length; index$1 = expressionPos = expressionEndPos = 0; if (val.indexOf('[') < 0 || val.lastIndexOf(']') < len - 1) { return { exp: val, idx: null } } while (!eof()) { chr = next(); /* istanbul ignore if */ if (isStringStart(chr)) { parseString(chr); } else if (chr === 0x5B) { parseBracket(chr); } } return { exp: val.substring(0, expressionPos), idx: val.substring(expressionPos + 1, expressionEndPos) } } function next () { return str.charCodeAt(++index$1) } function eof () { return index$1 >= len } function isStringStart (chr) { return chr === 0x22 || chr === 0x27 } function parseBracket (chr) { var inBracket = 1; expressionPos = index$1; while (!eof()) { chr = next(); if (isStringStart(chr)) { parseString(chr); continue } if (chr === 0x5B) { inBracket++; } if (chr === 0x5D) { inBracket--; } if (inBracket === 0) { expressionEndPos = index$1; break } } } function parseString (chr) { var stringQuote = chr; while (!eof()) { chr = next(); if (chr === stringQuote) { break } } } /* */ var dirRE = /^v-|^@|^:/; var forAliasRE = /(.*?)\s+(?:in|of)\s+(.*)/; var forIteratorRE = /\((\{[^}]*\}|[^,]*),([^,]*)(?:,([^,]*))?\)/; var bindRE = /^:|^v-bind:/; var onRE = /^@|^v-on:/; var argRE = /:(.*)$/; var modifierRE = /\.[^.]+/g; var decodeHTMLCached = cached(decode); // configurable state var warn$1; var platformGetTagNamespace; var platformMustUseProp; var platformIsPreTag; var preTransforms; var transforms; var postTransforms; var delimiters; /** * Convert HTML string to AST. */ function parse ( template, options ) { warn$1 = options.warn || baseWarn; platformGetTagNamespace = options.getTagNamespace || no; platformMustUseProp = options.mustUseProp || no; platformIsPreTag = options.isPreTag || no; preTransforms = pluckModuleFunction(options.modules, 'preTransformNode'); transforms = pluckModuleFunction(options.modules, 'transformNode'); postTransforms = pluckModuleFunction(options.modules, 'postTransformNode'); delimiters = options.delimiters; var stack = []; var preserveWhitespace = options.preserveWhitespace !== false; var root; var currentParent; var inVPre = false; var inPre = false; var warned = false; parseHTML(template, { expectHTML: options.expectHTML, isUnaryTag: options.isUnaryTag, shouldDecodeNewlines: options.shouldDecodeNewlines, start: function start (tag, attrs, unary) { // check namespace. // inherit parent ns if there is one var ns = (currentParent && currentParent.ns) || platformGetTagNamespace(tag); // handle IE svg bug /* istanbul ignore if */ if (isIE && ns === 'svg') { attrs = guardIESVGBug(attrs); } var element = { type: 1, tag: tag, attrsList: attrs, attrsMap: makeAttrsMap(attrs), parent: currentParent, children: [] }; if (ns) { element.ns = ns; } if (isForbiddenTag(element) && !isServerRendering()) { element.forbidden = true; process.env.NODE_ENV !== 'production' && warn$1( 'Templates should only be responsible for mapping the state to the ' + 'UI. Avoid placing tags with side-effects in your templates, such as ' + "<" + tag + ">." ); } // apply pre-transforms for (var i = 0; i < preTransforms.length; i++) { preTransforms[i](element, options); } if (!inVPre) { processPre(element); if (element.pre) { inVPre = true; } } if (platformIsPreTag(element.tag)) { inPre = true; } if (inVPre) { processRawAttrs(element); } else { processFor(element); processIf(element); processOnce(element); processKey(element); // determine whether this is a plain element after // removing structural attributes element.plain = !element.key && !attrs.length; processRef(element); processSlot(element); processComponent(element); for (var i$1 = 0; i$1 < transforms.length; i$1++) { transforms[i$1](element, options); } processAttrs(element); } function checkRootConstraints (el) { if (process.env.NODE_ENV !== 'production' && !warned) { if (el.tag === 'slot' || el.tag === 'template') { warned = true; warn$1( "Cannot use <" + (el.tag) + "> as component root element because it may " + 'contain multiple nodes:\n' + template ); } if (el.attrsMap.hasOwnProperty('v-for')) { warned = true; warn$1( 'Cannot use v-for on stateful component root element because ' + 'it renders multiple elements:\n' + template ); } } } // tree management if (!root) { root = element; checkRootConstraints(root); } else if (!stack.length) { // allow root elements with v-if, v-else-if and v-else if (root.if && (element.elseif || element.else)) { checkRootConstraints(element); addIfCondition(root, { exp: element.elseif, block: element }); } else if (process.env.NODE_ENV !== 'production' && !warned) { warned = true; warn$1( "Component template should contain exactly one root element:" + "\n\n" + template + "\n\n" + "If you are using v-if on multiple elements, " + "use v-else-if to chain them instead." ); } } if (currentParent && !element.forbidden) { if (element.elseif || element.else) { processIfConditions(element, currentParent); } else if (element.slotScope) { // scoped slot currentParent.plain = false; var name = element.slotTarget || 'default';(currentParent.scopedSlots || (currentParent.scopedSlots = {}))[name] = element; } else { currentParent.children.push(element); element.parent = currentParent; } } if (!unary) { currentParent = element; stack.push(element); } // apply post-transforms for (var i$2 = 0; i$2 < postTransforms.length; i$2++) { postTransforms[i$2](element, options); } }, end: function end () { // remove trailing whitespace var element = stack[stack.length - 1]; var lastNode = element.children[element.children.length - 1]; if (lastNode && lastNode.type === 3 && lastNode.text === ' ') { element.children.pop(); } // pop stack stack.length -= 1; currentParent = stack[stack.length - 1]; // check pre state if (element.pre) { inVPre = false; } if (platformIsPreTag(element.tag)) { inPre = false; } }, chars: function chars (text) { if (!currentParent) { if (process.env.NODE_ENV !== 'production' && !warned && text === template) { warned = true; warn$1( 'Component template requires a root element, rather than just text:\n\n' + template ); } return } // IE textarea placeholder bug /* istanbul ignore if */ if (isIE && currentParent.tag === 'textarea' && currentParent.attrsMap.placeholder === text) { return } text = inPre || text.trim() ? decodeHTMLCached(text) // only preserve whitespace if its not right after a starting tag : preserveWhitespace && currentParent.children.length ? ' ' : ''; if (text) { var expression; if (!inVPre && text !== ' ' && (expression = parseText(text, delimiters))) { currentParent.children.push({ type: 2, expression: expression, text: text }); } else { currentParent.children.push({ type: 3, text: text }); } } } }); return root } function processPre (el) { if (getAndRemoveAttr(el, 'v-pre') != null) { el.pre = true; } } function processRawAttrs (el) { var l = el.attrsList.length; if (l) { var attrs = el.attrs = new Array(l); for (var i = 0; i < l; i++) { attrs[i] = { name: el.attrsList[i].name, value: JSON.stringify(el.attrsList[i].value) }; } } else if (!el.pre) { // non root node in pre blocks with no attributes el.plain = true; } } function processKey (el) { var exp = getBindingAttr(el, 'key'); if (exp) { if (process.env.NODE_ENV !== 'production' && el.tag === 'template') { warn$1("<template> cannot be keyed. Place the key on real elements instead."); } el.key = exp; } } function processRef (el) { var ref = getBindingAttr(el, 'ref'); if (ref) { el.ref = ref; el.refInFor = checkInFor(el); } } function processFor (el) { var exp; if ((exp = getAndRemoveAttr(el, 'v-for'))) { var inMatch = exp.match(forAliasRE); if (!inMatch) { process.env.NODE_ENV !== 'production' && warn$1( ("Invalid v-for expression: " + exp) ); return } el.for = inMatch[2].trim(); var alias = inMatch[1].trim(); var iteratorMatch = alias.match(forIteratorRE); if (iteratorMatch) { el.alias = iteratorMatch[1].trim(); el.iterator1 = iteratorMatch[2].trim(); if (iteratorMatch[3]) { el.iterator2 = iteratorMatch[3].trim(); } } else { el.alias = alias; } } } function processIf (el) { var exp = getAndRemoveAttr(el, 'v-if'); if (exp) { el.if = exp; addIfCondition(el, { exp: exp, block: el }); } else { if (getAndRemoveAttr(el, 'v-else') != null) { el.else = true; } var elseif = getAndRemoveAttr(el, 'v-else-if'); if (elseif) { el.elseif = elseif; } } } function processIfConditions (el, parent) { var prev = findPrevElement(parent.children); if (prev && prev.if) { addIfCondition(prev, { exp: el.elseif, block: el }); } else if (process.env.NODE_ENV !== 'production') { warn$1( "v-" + (el.elseif ? ('else-if="' + el.elseif + '"') : 'else') + " " + "used on element <" + (el.tag) + "> without corresponding v-if." ); } } function addIfCondition (el, condition) { if (!el.ifConditions) { el.ifConditions = []; } el.ifConditions.push(condition); } function processOnce (el) { var once = getAndRemoveAttr(el, 'v-once'); if (once != null) { el.once = true; } } function processSlot (el) { if (el.tag === 'slot') { el.slotName = getBindingAttr(el, 'name'); if (process.env.NODE_ENV !== 'production' && el.key) { warn$1( "`key` does not work on <slot> because slots are abstract outlets " + "and can possibly expand into multiple elements. " + "Use the key on a wrapping element instead." ); } } else { var slotTarget = getBindingAttr(el, 'slot'); if (slotTarget) { el.slotTarget = slotTarget === '""' ? '"default"' : slotTarget; } if (el.tag === 'template') { el.slotScope = getAndRemoveAttr(el, 'scope'); } } } function processComponent (el) { var binding; if ((binding = getBindingAttr(el, 'is'))) { el.component = binding; } if (getAndRemoveAttr(el, 'inline-template') != null) { el.inlineTemplate = true; } } function processAttrs (el) { var list = el.attrsList; var i, l, name, rawName, value, arg, modifiers, isProp; for (i = 0, l = list.length; i < l; i++) { name = rawName = list[i].name; value = list[i].value; if (dirRE.test(name)) { // mark element as dynamic el.hasBindings = true; // modifiers modifiers = parseModifiers(name); if (modifiers) { name = name.replace(modifierRE, ''); } if (bindRE.test(name)) { // v-bind name = name.replace(bindRE, ''); value = parseFilters(value); if (modifiers) { if (modifiers.prop) { isProp = true; name = camelize(name); if (name === 'innerHtml') { name = 'innerHTML'; } } if (modifiers.camel) { name = camelize(name); } } if (isProp || platformMustUseProp(el.tag, name)) { addProp(el, name, value); } else { addAttr(el, name, value); } } else if (onRE.test(name)) { // v-on name = name.replace(onRE, ''); addHandler(el, name, value, modifiers); } else { // normal directives name = name.replace(dirRE, ''); // parse arg var argMatch = name.match(argRE); if (argMatch && (arg = argMatch[1])) { name = name.slice(0, -(arg.length + 1)); } addDirective(el, name, rawName, value, arg, modifiers); if (process.env.NODE_ENV !== 'production' && name === 'model') { checkForAliasModel(el, value); } } } else { // literal attribute if (process.env.NODE_ENV !== 'production') { var expression = parseText(value, delimiters); if (expression) { warn$1( name + "=\"" + value + "\": " + 'Interpolation inside attributes has been removed. ' + 'Use v-bind or the colon shorthand instead. For example, ' + 'instead of <div id="{{ val }}">, use <div :id="val">.' ); } } addAttr(el, name, JSON.stringify(value)); } } } function checkInFor (el) { var parent = el; while (parent) { if (parent.for !== undefined) { return true } parent = parent.parent; } return false } function parseModifiers (name) { var match = name.match(modifierRE); if (match) { var ret = {}; match.forEach(function (m) { ret[m.slice(1)] = true; }); return ret } } function makeAttrsMap (attrs) { var map = {}; for (var i = 0, l = attrs.length; i < l; i++) { if (process.env.NODE_ENV !== 'production' && map[attrs[i].name] && !isIE) { warn$1('duplicate attribute: ' + attrs[i].name); } map[attrs[i].name] = attrs[i].value; } return map } function findPrevElement (children) { var i = children.length; while (i--) { if (children[i].tag) { return children[i] } } } function isForbiddenTag (el) { return ( el.tag === 'style' || (el.tag === 'script' && ( !el.attrsMap.type || el.attrsMap.type === 'text/javascript' )) ) } var ieNSBug = /^xmlns:NS\d+/; var ieNSPrefix = /^NS\d+:/; /* istanbul ignore next */ function guardIESVGBug (attrs) { var res = []; for (var i = 0; i < attrs.length; i++) { var attr = attrs[i]; if (!ieNSBug.test(attr.name)) { attr.name = attr.name.replace(ieNSPrefix, ''); res.push(attr); } } return res } function checkForAliasModel (el, value) { var _el = el; while (_el) { if (_el.for && _el.alias === value) { warn$1( "<" + (el.tag) + " v-model=\"" + value + "\">: " + "You are binding v-model directly to a v-for iteration alias. " + "This will not be able to modify the v-for source array because " + "writing to the alias is like modifying a function local variable. " + "Consider using an array of objects and use v-model on an object property instead." ); } _el = _el.parent; } } /* */ var isStaticKey; var isPlatformReservedTag; var genStaticKeysCached = cached(genStaticKeys$1); /** * Goal of the optimizer: walk the generated template AST tree * and detect sub-trees that are purely static, i.e. parts of * the DOM that never needs to change. * * Once we detect these sub-trees, we can: * * 1. Hoist them into constants, so that we no longer need to * create fresh nodes for them on each re-render; * 2. Completely skip them in the patching process. */ function optimize (root, options) { if (!root) { return } isStaticKey = genStaticKeysCached(options.staticKeys || ''); isPlatformReservedTag = options.isReservedTag || no; // first pass: mark all non-static nodes. markStatic(root); // second pass: mark static roots. markStaticRoots(root, false); } function genStaticKeys$1 (keys) { return makeMap( 'type,tag,attrsList,attrsMap,plain,parent,children,attrs' + (keys ? ',' + keys : '') ) } function markStatic (node) { node.static = isStatic(node); if (node.type === 1) { // do not make component slot content static. this avoids // 1. components not able to mutate slot nodes // 2. static slot content fails for hot-reloading if ( !isPlatformReservedTag(node.tag) && node.tag !== 'slot' && node.attrsMap['inline-template'] == null ) { return } for (var i = 0, l = node.children.length; i < l; i++) { var child = node.children[i]; markStatic(child); if (!child.static) { node.static = false; } } } } function markStaticRoots (node, isInFor) { if (node.type === 1) { if (node.static || node.once) { node.staticInFor = isInFor; } // For a node to qualify as a static root, it should have children that // are not just static text. Otherwise the cost of hoisting out will // outweigh the benefits and it's better off to just always render it fresh. if (node.static && node.children.length && !( node.children.length === 1 && node.children[0].type === 3 )) { node.staticRoot = true; return } else { node.staticRoot = false; } if (node.children) { for (var i = 0, l = node.children.length; i < l; i++) { markStaticRoots(node.children[i], isInFor || !!node.for); } } if (node.ifConditions) { walkThroughConditionsBlocks(node.ifConditions, isInFor); } } } function walkThroughConditionsBlocks (conditionBlocks, isInFor) { for (var i = 1, len = conditionBlocks.length; i < len; i++) { markStaticRoots(conditionBlocks[i].block, isInFor); } } function isStatic (node) { if (node.type === 2) { // expression return false } if (node.type === 3) { // text return true } return !!(node.pre || ( !node.hasBindings && // no dynamic bindings !node.if && !node.for && // not v-if or v-for or v-else !isBuiltInTag(node.tag) && // not a built-in isPlatformReservedTag(node.tag) && // not a component !isDirectChildOfTemplateFor(node) && Object.keys(node).every(isStaticKey) )) } function isDirectChildOfTemplateFor (node) { while (node.parent) { node = node.parent; if (node.tag !== 'template') { return false } if (node.for) { return true } } return false } /* */ var fnExpRE = /^\s*([\w$_]+|\([^)]*?\))\s*=>|^function\s*\(/; var simplePathRE = /^\s*[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*|\['.*?']|\[".*?"]|\[\d+]|\[[A-Za-z_$][\w$]*])*\s*$/; // keyCode aliases var keyCodes = { esc: 27, tab: 9, enter: 13, space: 32, up: 38, left: 37, right: 39, down: 40, 'delete': [8, 46] }; var modifierCode = { stop: '$event.stopPropagation();', prevent: '$event.preventDefault();', self: 'if($event.target !== $event.currentTarget)return;', ctrl: 'if(!$event.ctrlKey)return;', shift: 'if(!$event.shiftKey)return;', alt: 'if(!$event.altKey)return;', meta: 'if(!$event.metaKey)return;' }; function genHandlers (events, native) { var res = native ? 'nativeOn:{' : 'on:{'; for (var name in events) { res += "\"" + name + "\":" + (genHandler(name, events[name])) + ","; } return res.slice(0, -1) + '}' } function genHandler ( name, handler ) { if (!handler) { return 'function(){}' } else if (Array.isArray(handler)) { return ("[" + (handler.map(function (handler) { return genHandler(name, handler); }).join(',')) + "]") } else if (!handler.modifiers) { return fnExpRE.test(handler.value) || simplePathRE.test(handler.value) ? handler.value : ("function($event){" + (handler.value) + "}") } else { var code = ''; var keys = []; for (var key in handler.modifiers) { if (modifierCode[key]) { code += modifierCode[key]; } else { keys.push(key); } } if (keys.length) { code = genKeyFilter(keys) + code; } var handlerCode = simplePathRE.test(handler.value) ? handler.value + '($event)' : handler.value; return 'function($event){' + code + handlerCode + '}' } } function genKeyFilter (keys) { return ("if(" + (keys.map(genFilterCode).join('&&')) + ")return;") } function genFilterCode (key) { var keyVal = parseInt(key, 10); if (keyVal) { return ("$event.keyCode!==" + keyVal) } var alias = keyCodes[key]; return ("_k($event.keyCode," + (JSON.stringify(key)) + (alias ? ',' + JSON.stringify(alias) : '') + ")") } /* */ function bind$2 (el, dir) { el.wrapData = function (code) { return ("_b(" + code + ",'" + (el.tag) + "'," + (dir.value) + (dir.modifiers && dir.modifiers.prop ? ',true' : '') + ")") }; } var baseDirectives = { bind: bind$2, cloak: noop }; /* */ // configurable state var warn$2; var transforms$1; var dataGenFns; var platformDirectives$1; var staticRenderFns; var onceCount; var currentOptions; function generate ( ast, options ) { // save previous staticRenderFns so generate calls can be nested var prevStaticRenderFns = staticRenderFns; var currentStaticRenderFns = staticRenderFns = []; var prevOnceCount = onceCount; onceCount = 0; currentOptions = options; warn$2 = options.warn || baseWarn; transforms$1 = pluckModuleFunction(options.modules, 'transformCode'); dataGenFns = pluckModuleFunction(options.modules, 'genData'); platformDirectives$1 = options.directives || {}; var code = ast ? genElement(ast) : '_h("div")'; staticRenderFns = prevStaticRenderFns; onceCount = prevOnceCount; return { render: ("with(this){return " + code + "}"), staticRenderFns: currentStaticRenderFns } } function genElement (el) { if (el.staticRoot && !el.staticProcessed) { return genStatic(el) } else if (el.once && !el.onceProcessed) { return genOnce(el) } else if (el.for && !el.forProcessed) { return genFor(el) } else if (el.if && !el.ifProcessed) { return genIf(el) } else if (el.tag === 'template' && !el.slotTarget) { return genChildren(el) || 'void 0' } else if (el.tag === 'slot') { return genSlot(el) } else { // component or element var code; if (el.component) { code = genComponent(el.component, el); } else { var data = el.plain ? undefined : genData(el); var children = el.inlineTemplate ? null : genChildren(el); code = "_h('" + (el.tag) + "'" + (data ? ("," + data) : '') + (children ? ("," + children) : '') + ")"; } // module transforms for (var i = 0; i < transforms$1.length; i++) { code = transforms$1[i](el, code); } return code } } // hoist static sub-trees out function genStatic (el) { el.staticProcessed = true; staticRenderFns.push(("with(this){return " + (genElement(el)) + "}")); return ("_m(" + (staticRenderFns.length - 1) + (el.staticInFor ? ',true' : '') + ")") } // v-once function genOnce (el) { el.onceProcessed = true; if (el.if && !el.ifProcessed) { return genIf(el) } else if (el.staticInFor) { var key = ''; var parent = el.parent; while (parent) { if (parent.for) { key = parent.key; break } parent = parent.parent; } if (!key) { process.env.NODE_ENV !== 'production' && warn$2( "v-once can only be used inside v-for that is keyed. " ); return genElement(el) } return ("_o(" + (genElement(el)) + "," + (onceCount++) + (key ? ("," + key) : "") + ")") } else { return genStatic(el) } } function genIf (el) { el.ifProcessed = true; // avoid recursion return genIfConditions(el.ifConditions.slice()) } function genIfConditions (conditions) { if (!conditions.length) { return '_e()' } var condition = conditions.shift(); if (condition.exp) { return ("(" + (condition.exp) + ")?" + (genTernaryExp(condition.block)) + ":" + (genIfConditions(conditions))) } else { return ("" + (genTernaryExp(condition.block))) } // v-if with v-once should generate code like (a)?_m(0):_m(1) function genTernaryExp (el) { return el.once ? genOnce(el) : genElement(el) } } function genFor (el) { var exp = el.for; var alias = el.alias; var iterator1 = el.iterator1 ? ("," + (el.iterator1)) : ''; var iterator2 = el.iterator2 ? ("," + (el.iterator2)) : ''; el.forProcessed = true; // avoid recursion return "_l((" + exp + ")," + "function(" + alias + iterator1 + iterator2 + "){" + "return " + (genElement(el)) + '})' } function genData (el) { var data = '{'; // directives first. // directives may mutate the el's other properties before they are generated. var dirs = genDirectives(el); if (dirs) { data += dirs + ','; } // key if (el.key) { data += "key:" + (el.key) + ","; } // ref if (el.ref) { data += "ref:" + (el.ref) + ","; } if (el.refInFor) { data += "refInFor:true,"; } // pre if (el.pre) { data += "pre:true,"; } // record original tag name for components using "is" attribute if (el.component) { data += "tag:\"" + (el.tag) + "\","; } // module data generation functions for (var i = 0; i < dataGenFns.length; i++) { data += dataGenFns[i](el); } // attributes if (el.attrs) { data += "attrs:{" + (genProps(el.attrs)) + "},"; } // DOM props if (el.props) { data += "domProps:{" + (genProps(el.props)) + "},"; } // event handlers if (el.events) { data += (genHandlers(el.events)) + ","; } if (el.nativeEvents) { data += (genHandlers(el.nativeEvents, true)) + ","; } // slot target if (el.slotTarget) { data += "slot:" + (el.slotTarget) + ","; } // scoped slots if (el.scopedSlots) { data += (genScopedSlots(el.scopedSlots)) + ","; } // inline-template if (el.inlineTemplate) { var inlineTemplate = genInlineTemplate(el); if (inlineTemplate) { data += inlineTemplate + ","; } } data = data.replace(/,$/, '') + '}'; // v-bind data wrap if (el.wrapData) { data = el.wrapData(data); } return data } function genDirectives (el) { var dirs = el.directives; if (!dirs) { return } var res = 'directives:['; var hasRuntime = false; var i, l, dir, needRuntime; for (i = 0, l = dirs.length; i < l; i++) { dir = dirs[i]; needRuntime = true; var gen = platformDirectives$1[dir.name] || baseDirectives[dir.name]; if (gen) { // compile-time directive that manipulates AST. // returns true if it also needs a runtime counterpart. needRuntime = !!gen(el, dir, warn$2); } if (needRuntime) { hasRuntime = true; res += "{name:\"" + (dir.name) + "\",rawName:\"" + (dir.rawName) + "\"" + (dir.value ? (",value:(" + (dir.value) + "),expression:" + (JSON.stringify(dir.value))) : '') + (dir.arg ? (",arg:\"" + (dir.arg) + "\"") : '') + (dir.modifiers ? (",modifiers:" + (JSON.stringify(dir.modifiers))) : '') + "},"; } } if (hasRuntime) { return res.slice(0, -1) + ']' } } function genInlineTemplate (el) { var ast = el.children[0]; if (process.env.NODE_ENV !== 'production' && ( el.children.length > 1 || ast.type !== 1 )) { warn$2('Inline-template components must have exactly one child element.'); } if (ast.type === 1) { var inlineRenderFns = generate(ast, currentOptions); return ("inlineTemplate:{render:function(){" + (inlineRenderFns.render) + "},staticRenderFns:[" + (inlineRenderFns.staticRenderFns.map(function (code) { return ("function(){" + code + "}"); }).join(',')) + "]}") } } function genScopedSlots (slots) { return ("scopedSlots:{" + (Object.keys(slots).map(function (key) { return genScopedSlot(key, slots[key]); }).join(',')) + "}") } function genScopedSlot (key, el) { return key + ":function(" + (String(el.attrsMap.scope)) + "){" + "return " + (el.tag === 'template' ? genChildren(el) || 'void 0' : genElement(el)) + "}" } function genChildren (el) { if (el.children.length) { return '[' + el.children.map(genNode).join(',') + ']' } } function genNode (node) { if (node.type === 1) { return genElement(node) } else { return genText(node) } } function genText (text) { return text.type === 2 ? text.expression // no need for () because already wrapped in _s() : transformSpecialNewlines(JSON.stringify(text.text)) } function genSlot (el) { var slotName = el.slotName || '"default"'; var children = genChildren(el); return ("_t(" + slotName + (children ? ("," + children) : '') + (el.attrs ? ((children ? '' : ',null') + ",{" + (el.attrs.map(function (a) { return ((camelize(a.name)) + ":" + (a.value)); }).join(',')) + "}") : '') + ")") } // componentName is el.component, take it as argument to shun flow's pessimistic refinement function genComponent (componentName, el) { var children = el.inlineTemplate ? null : genChildren(el); return ("_h(" + componentName + "," + (genData(el)) + (children ? ("," + children) : '') + ")") } function genProps (props) { var res = ''; for (var i = 0; i < props.length; i++) { var prop = props[i]; res += "\"" + (prop.name) + "\":" + (transformSpecialNewlines(prop.value)) + ","; } return res.slice(0, -1) } // #3895, #4268 function transformSpecialNewlines (text) { return text .replace(/\u2028/g, '\\u2028') .replace(/\u2029/g, '\\u2029') } /* */ /** * Compile a template. */ function compile$1 ( template, options ) { var ast = parse(template.trim(), options); optimize(ast, options); var code = generate(ast, options); return { ast: ast, render: code.render, staticRenderFns: code.staticRenderFns } } /* */ // operators like typeof, instanceof and in are allowed var prohibitedKeywordRE = new RegExp('\\b' + ( 'do,if,for,let,new,try,var,case,else,with,await,break,catch,class,const,' + 'super,throw,while,yield,delete,export,import,return,switch,default,' + 'extends,finally,continue,debugger,function,arguments' ).split(',').join('\\b|\\b') + '\\b'); // check valid identifier for v-for var identRE = /[A-Za-z_$][\w$]*/; // strip strings in expressions var stripStringRE = /'(?:[^'\\]|\\.)*'|"(?:[^"\\]|\\.)*"|`(?:[^`\\]|\\.)*\$\{|\}(?:[^`\\]|\\.)*`|`(?:[^`\\]|\\.)*`/g; // detect problematic expressions in a template function detectErrors (ast) { var errors = []; if (ast) { checkNode(ast, errors); } return errors } function checkNode (node, errors) { if (node.type === 1) { for (var name in node.attrsMap) { if (dirRE.test(name)) { var value = node.attrsMap[name]; if (value) { if (name === 'v-for') { checkFor(node, ("v-for=\"" + value + "\""), errors); } else { checkExpression(value, (name + "=\"" + value + "\""), errors); } } } } if (node.children) { for (var i = 0; i < node.children.length; i++) { checkNode(node.children[i], errors); } } } else if (node.type === 2) { checkExpression(node.expression, node.text, errors); } } function checkFor (node, text, errors) { checkExpression(node.for || '', text, errors); checkIdentifier(node.alias, 'v-for alias', text, errors); checkIdentifier(node.iterator1, 'v-for iterator', text, errors); checkIdentifier(node.iterator2, 'v-for iterator', text, errors); } function checkIdentifier (ident, type, text, errors) { if (typeof ident === 'string' && !identRE.test(ident)) { errors.push(("- invalid " + type + " \"" + ident + "\" in expression: " + text)); } } function checkExpression (exp, text, errors) { try { new Function(("return " + exp)); } catch (e) { var keywordMatch = exp.replace(stripStringRE, '').match(prohibitedKeywordRE); if (keywordMatch) { errors.push( "- avoid using JavaScript keyword as property name: " + "\"" + (keywordMatch[0]) + "\" in expression " + text ); } else { errors.push(("- invalid expression: " + text)); } } } /* */ function transformNode (el, options) { var warn = options.warn || baseWarn; var staticClass = getAndRemoveAttr(el, 'class'); if (process.env.NODE_ENV !== 'production' && staticClass) { var expression = parseText(staticClass, options.delimiters); if (expression) { warn( "class=\"" + staticClass + "\": " + 'Interpolation inside attributes has been removed. ' + 'Use v-bind or the colon shorthand instead. For example, ' + 'instead of <div class="{{ val }}">, use <div :class="val">.' ); } } if (staticClass) { el.staticClass = JSON.stringify(staticClass); } var classBinding = getBindingAttr(el, 'class', false /* getStatic */); if (classBinding) { el.classBinding = classBinding; } } function genData$1 (el) { var data = ''; if (el.staticClass) { data += "staticClass:" + (el.staticClass) + ","; } if (el.classBinding) { data += "class:" + (el.classBinding) + ","; } return data } var klass$1 = { staticKeys: ['staticClass'], transformNode: transformNode, genData: genData$1 }; /* */ function transformNode$1 (el, options) { var warn = options.warn || baseWarn; var staticStyle = getAndRemoveAttr(el, 'style'); if (staticStyle) { /* istanbul ignore if */ if (process.env.NODE_ENV !== 'production') { var expression = parseText(staticStyle, options.delimiters); if (expression) { warn( "style=\"" + staticStyle + "\": " + 'Interpolation inside attributes has been removed. ' + 'Use v-bind or the colon shorthand instead. For example, ' + 'instead of <div style="{{ val }}">, use <div :style="val">.' ); } } el.staticStyle = JSON.stringify(parseStyleText(staticStyle)); } var styleBinding = getBindingAttr(el, 'style', false /* getStatic */); if (styleBinding) { el.styleBinding = styleBinding; } } function genData$2 (el) { var data = ''; if (el.staticStyle) { data += "staticStyle:" + (el.staticStyle) + ","; } if (el.styleBinding) { data += "style:(" + (el.styleBinding) + "),"; } return data } var style$1 = { staticKeys: ['staticStyle'], transformNode: transformNode$1, genData: genData$2 }; var modules$1 = [ klass$1, style$1 ]; /* */ var warn$3; function model$1 ( el, dir, _warn ) { warn$3 = _warn; var value = dir.value; var modifiers = dir.modifiers; var tag = el.tag; var type = el.attrsMap.type; if (process.env.NODE_ENV !== 'production') { var dynamicType = el.attrsMap['v-bind:type'] || el.attrsMap[':type']; if (tag === 'input' && dynamicType) { warn$3( "<input :type=\"" + dynamicType + "\" v-model=\"" + value + "\">:\n" + "v-model does not support dynamic input types. Use v-if branches instead." ); } } if (tag === 'select') { genSelect(el, value, modifiers); } else if (tag === 'input' && type === 'checkbox') { genCheckboxModel(el, value, modifiers); } else if (tag === 'input' && type === 'radio') { genRadioModel(el, value, modifiers); } else { genDefaultModel(el, value, modifiers); } // ensure runtime directive metadata return true } function genCheckboxModel ( el, value, modifiers ) { if (process.env.NODE_ENV !== 'production' && el.attrsMap.checked != null) { warn$3( "<" + (el.tag) + " v-model=\"" + value + "\" checked>:\n" + "inline checked attributes will be ignored when using v-model. " + 'Declare initial values in the component\'s data option instead.' ); } var number = modifiers && modifiers.number; var valueBinding = getBindingAttr(el, 'value') || 'null'; var trueValueBinding = getBindingAttr(el, 'true-value') || 'true'; var falseValueBinding = getBindingAttr(el, 'false-value') || 'false'; addProp(el, 'checked', "Array.isArray(" + value + ")" + "?_i(" + value + "," + valueBinding + ")>-1" + ":_q(" + value + "," + trueValueBinding + ")" ); addHandler(el, 'change', "var $$a=" + value + "," + '$$el=$event.target,' + "$$c=$$el.checked?(" + trueValueBinding + "):(" + falseValueBinding + ");" + 'if(Array.isArray($$a)){' + "var $$v=" + (number ? '_n(' + valueBinding + ')' : valueBinding) + "," + '$$i=_i($$a,$$v);' + "if($$c){$$i<0&&(" + value + "=$$a.concat($$v))}" + "else{$$i>-1&&(" + value + "=$$a.slice(0,$$i).concat($$a.slice($$i+1)))}" + "}else{" + value + "=$$c}", null, true ); } function genRadioModel ( el, value, modifiers ) { if (process.env.NODE_ENV !== 'production' && el.attrsMap.checked != null) { warn$3( "<" + (el.tag) + " v-model=\"" + value + "\" checked>:\n" + "inline checked attributes will be ignored when using v-model. " + 'Declare initial values in the component\'s data option instead.' ); } var number = modifiers && modifiers.number; var valueBinding = getBindingAttr(el, 'value') || 'null'; valueBinding = number ? ("_n(" + valueBinding + ")") : valueBinding; addProp(el, 'checked', ("_q(" + value + "," + valueBinding + ")")); addHandler(el, 'change', genAssignmentCode(value, valueBinding), null, true); } function genDefaultModel ( el, value, modifiers ) { if (process.env.NODE_ENV !== 'production') { if (el.tag === 'input' && el.attrsMap.value) { warn$3( "<" + (el.tag) + " v-model=\"" + value + "\" value=\"" + (el.attrsMap.value) + "\">:\n" + 'inline value attributes will be ignored when using v-model. ' + 'Declare initial values in the component\'s data option instead.' ); } if (el.tag === 'textarea' && el.children.length) { warn$3( "<textarea v-model=\"" + value + "\">:\n" + 'inline content inside <textarea> will be ignored when using v-model. ' + 'Declare initial values in the component\'s data option instead.' ); } } var type = el.attrsMap.type; var ref = modifiers || {}; var lazy = ref.lazy; var number = ref.number; var trim = ref.trim; var event = lazy || (isIE && type === 'range') ? 'change' : 'input'; var needCompositionGuard = !lazy && type !== 'range'; var isNative = el.tag === 'input' || el.tag === 'textarea'; var valueExpression = isNative ? ("$event.target.value" + (trim ? '.trim()' : '')) : trim ? "(typeof $event === 'string' ? $event.trim() : $event)" : "$event"; valueExpression = number || type === 'number' ? ("_n(" + valueExpression + ")") : valueExpression; var code = genAssignmentCode(value, valueExpression); if (isNative && needCompositionGuard) { code = "if($event.target.composing)return;" + code; } // inputs with type="file" are read only and setting the input's // value will throw an error. if (process.env.NODE_ENV !== 'production' && type === 'file') { warn$3( "<" + (el.tag) + " v-model=\"" + value + "\" type=\"file\">:\n" + "File inputs are read only. Use a v-on:change listener instead." ); } addProp(el, 'value', isNative ? ("_s(" + value + ")") : ("(" + value + ")")); addHandler(el, event, code, null, true); } function genSelect ( el, value, modifiers ) { if (process.env.NODE_ENV !== 'production') { el.children.some(checkOptionWarning); } var number = modifiers && modifiers.number; var assignment = "Array.prototype.filter" + ".call($event.target.options,function(o){return o.selected})" + ".map(function(o){var val = \"_value\" in o ? o._value : o.value;" + "return " + (number ? '_n(val)' : 'val') + "})" + (el.attrsMap.multiple == null ? '[0]' : ''); var code = genAssignmentCode(value, assignment); addHandler(el, 'change', code, null, true); } function checkOptionWarning (option) { if (option.type === 1 && option.tag === 'option' && option.attrsMap.selected != null) { warn$3( "<select v-model=\"" + (option.parent.attrsMap['v-model']) + "\">:\n" + 'inline selected attributes on <option> will be ignored when using v-model. ' + 'Declare initial values in the component\'s data option instead.' ); return true } return false } function genAssignmentCode (value, assignment) { var modelRs = parseModel(value); if (modelRs.idx === null) { return (value + "=" + assignment) } else { return "var $$exp = " + (modelRs.exp) + ", $$idx = " + (modelRs.idx) + ";" + "if (!Array.isArray($$exp)){" + value + "=" + assignment + "}" + "else{$$exp.splice($$idx, 1, " + assignment + ")}" } } /* */ function text (el, dir) { if (dir.value) { addProp(el, 'textContent', ("_s(" + (dir.value) + ")")); } } /* */ function html (el, dir) { if (dir.value) { addProp(el, 'innerHTML', ("_s(" + (dir.value) + ")")); } } var directives$1 = { model: model$1, text: text, html: html }; /* */ var cache = Object.create(null); var baseOptions = { expectHTML: true, modules: modules$1, staticKeys: genStaticKeys(modules$1), directives: directives$1, isReservedTag: isReservedTag, isUnaryTag: isUnaryTag, mustUseProp: mustUseProp, getTagNamespace: getTagNamespace, isPreTag: isPreTag }; function compile$$1 ( template, options ) { options = options ? extend(extend({}, baseOptions), options) : baseOptions; return compile$1(template, options) } function compileToFunctions ( template, options, vm ) { var _warn = (options && options.warn) || warn; // detect possible CSP restriction /* istanbul ignore if */ if (process.env.NODE_ENV !== 'production') { try { new Function('return 1'); } catch (e) { if (e.toString().match(/unsafe-eval|CSP/)) { _warn( 'It seems you are using the standalone build of Vue.js in an ' + 'environment with Content Security Policy that prohibits unsafe-eval. ' + 'The template compiler cannot work in this environment. Consider ' + 'relaxing the policy to allow unsafe-eval or pre-compiling your ' + 'templates into render functions.' ); } } } var key = options && options.delimiters ? String(options.delimiters) + template : template; if (cache[key]) { return cache[key] } var res = {}; var compiled = compile$$1(template, options); res.render = makeFunction(compiled.render); var l = compiled.staticRenderFns.length; res.staticRenderFns = new Array(l); for (var i = 0; i < l; i++) { res.staticRenderFns[i] = makeFunction(compiled.staticRenderFns[i]); } if (process.env.NODE_ENV !== 'production') { if (res.render === noop || res.staticRenderFns.some(function (fn) { return fn === noop; })) { _warn( "failed to compile template:\n\n" + template + "\n\n" + detectErrors(compiled.ast).join('\n') + '\n\n', vm ); } } return (cache[key] = res) } function makeFunction (code) { try { return new Function(code) } catch (e) { return noop } } /* */ var idToTemplate = cached(function (id) { var el = query(id); return el && el.innerHTML }); var mount = Vue$3.prototype.$mount; Vue$3.prototype.$mount = function ( el, hydrating ) { el = el && query(el); /* istanbul ignore if */ if (el === document.body || el === document.documentElement) { process.env.NODE_ENV !== 'production' && warn( "Do not mount Vue to <html> or <body> - mount to normal elements instead." ); return this } var options = this.$options; // resolve template/el and convert to render function if (!options.render) { var template = options.template; if (template) { if (typeof template === 'string') { if (template.charAt(0) === '#') { template = idToTemplate(template); /* istanbul ignore if */ if (process.env.NODE_ENV !== 'production' && !template) { warn( ("Template element not found or is empty: " + (options.template)), this ); } } } else if (template.nodeType) { template = template.innerHTML; } else { if (process.env.NODE_ENV !== 'production') { warn('invalid template option:' + template, this); } return this } } else if (el) { template = getOuterHTML(el); } if (template) { var ref = compileToFunctions(template, { warn: warn, shouldDecodeNewlines: shouldDecodeNewlines, delimiters: options.delimiters }, this); var render = ref.render; var staticRenderFns = ref.staticRenderFns; options.render = render; options.staticRenderFns = staticRenderFns; } } return mount.call(this, el, hydrating) }; /** * Get outerHTML of elements, taking care * of SVG elements in IE as well. */ function getOuterHTML (el) { if (el.outerHTML) { return el.outerHTML } else { var container = document.createElement('div'); container.appendChild(el.cloneNode(true)); return container.innerHTML } } Vue$3.compile = compileToFunctions; module.exports = Vue$3;
(function(global) { 'use strict'; var fabric = global.fabric || (global.fabric = { }), extend = fabric.util.object.extend; /** * Brightness filter class * @class fabric.Image.filters.Brightness * @memberOf fabric.Image.filters * @extends fabric.Image.filters.BaseFilter * @see {@link fabric.Image.filters.Brightness#initialize} for constructor definition * @see {@link http://fabricjs.com/image-filters/|ImageFilters demo} * @example * var filter = new fabric.Image.filters.Brightness({ * brightness: 200 * }); * object.filters.push(filter); * object.applyFilters(canvas.renderAll.bind(canvas)); */ fabric.Image.filters.Brightness = fabric.util.createClass(fabric.Image.filters.BaseFilter, /** @lends fabric.Image.filters.Brightness.prototype */ { /** * Filter type * @param {String} type * @default */ type: 'Brightness', /** * Constructor * @memberOf fabric.Image.filters.Brightness.prototype * @param {Object} [options] Options object * @param {Number} [options.brightness=0] Value to brighten the image up (0..255) */ initialize: function(options) { options = options || { }; this.brightness = options.brightness || 0; }, /** * Applies filter to canvas element * @param {Object} canvasEl Canvas element to apply filter to */ applyTo: function(canvasEl) { var context = canvasEl.getContext('2d'), imageData = context.getImageData(0, 0, canvasEl.width, canvasEl.height), data = imageData.data, brightness = this.brightness; for (var i = 0, len = data.length; i < len; i += 4) { data[i] += brightness; data[i + 1] += brightness; data[i + 2] += brightness; } context.putImageData(imageData, 0, 0); }, /** * Returns object representation of an instance * @return {Object} Object representation of an instance */ toObject: function() { return extend(this.callSuper('toObject'), { brightness: this.brightness }); } }); /** * Returns filter instance from an object representation * @static * @param {Object} object Object to create an instance from * @return {fabric.Image.filters.Brightness} Instance of fabric.Image.filters.Brightness */ fabric.Image.filters.Brightness.fromObject = function(object) { return new fabric.Image.filters.Brightness(object); }; })(typeof exports !== 'undefined' ? exports : this);
/** * jq.appframework.js * @copyright Intel 2013 * @author Ian Maffett * @description A plugin to allow jQuery developers to use App Framework UI */ /* jshint eqeqeq:false */ (function($,window){ "use strict"; jQuery.event.props.push("touches"); jQuery.event.props.push("originalTouches"); jQuery.event.props.push("changedTouches"); var nundefined, document = window.document,classCache = {},isWin8=(typeof(MSApp)==="object"),_jsonPID = 1; function classRE(name) { return name in classCache ? classCache[name] : (classCache[name] = new RegExp("(^|\\s)" + name + "(\\s|$)")); } function _shimNodes(nodes, obj) { if (!nodes) return; if (nodes.nodeType) { obj[obj.length++] = nodes; return; } for (var i = 0, iz = nodes.length; i < iz; i++) obj[obj.length++] = nodes[i]; } $.extend($.fn,{ /* @param {String} attribute to get * @param {String} value to set as * @return {Object} an appframework object * @title $().css(attribute,[value]) */ vendorCss: function (attribute, value, obj) { return this.css($.feat.cssPrefix + attribute, value, obj); }, /** * Performs a css vendor specific transform:translate operation on the collection. * ``` $("#main").cssTranslate('200px,0,0'); ``` * @param {String} Transform values * @return {Object} an appframework object * @title $().vendorCss(value) */ cssTranslate: function (val) { return this.vendorCss("Transform", "translate" + $.feat.cssTransformStart + val + $.feat.cssTransformEnd); }, /** * Gets the computed style of CSS values * ``` $("#main").computedStyle('display'); ``` * @param {String} css property * @return {Int|String|Float|} css vlaue * @title $().computedStyle() */ computedStyle:function(val){ if(this.length===0||val==nundefined) return; return window.getComputedStyle(this[0],"")[val]; }, replaceClass: function(name, newName) { if (name == nundefined || newName == nundefined) return this; var replaceClassFn=function(cname) { classList = classList.replace(classRE(cname), " "); }; for (var i = 0; i < this.length; i++) { if (name == nundefined) { this[i].className = newName; continue; } var classList = this[i].className; name.split(/\s+/g).concat(newName.split(/\s+/g)).forEach(replaceClassFn); classList = classList.trim(); if (classList.length > 0) { this[i].className = (classList + " " + newName).trim(); } else this[i].className = newName; } return this; } }); function detectUA($, userAgent) { $.os = {}; $.os.webkit = userAgent.match(/WebKit\/([\d.]+)/) ? true : false; $.os.android = userAgent.match(/(Android)\s+([\d.]+)/) || userAgent.match(/Silk-Accelerated/) ? true : false; $.os.androidICS = $.os.android && userAgent.match(/(Android)\s4/) ? true : false; $.os.ipad = userAgent.match(/(iPad).*OS\s([\d_]+)/) ? true : false; $.os.iphone = !$.os.ipad && userAgent.match(/(iPhone\sOS)\s([\d_]+)/) ? true : false; $.os.ios7 = ($.os.ipad||$.os.iphone)&&userAgent.match(/7_/)||($.os.ipad||$.os.iphone)&&userAgent.match(/8_/) ? true : false; $.os.webos = userAgent.match(/(webOS|hpwOS)[\s\/]([\d.]+)/) ? true : false; $.os.touchpad = $.os.webos && userAgent.match(/TouchPad/) ? true : false; $.os.ios = $.os.ipad || $.os.iphone; $.os.playbook = userAgent.match(/PlayBook/) ? true : false; $.os.blackberry10 = userAgent.match(/BB10/) ? true : false; $.os.blackberry = $.os.playbook || $.os.blackberry10|| userAgent.match(/BlackBerry/) ? true : false; $.os.chrome = userAgent.match(/Chrome/) ? true : false; $.os.opera = userAgent.match(/Opera/) ? true : false; $.os.fennec = userAgent.match(/fennec/i) ? true : userAgent.match(/Firefox/) ? true : false; $.os.ie = userAgent.match(/MSIE 10.0/i)||userAgent.match(/Trident\/7/i) ? true : false; $.os.ieTouch = $.os.ie && userAgent.toLowerCase().match(/touch/i) ? true : false; $.os.tizen = userAgent.match(/Tizen/i)?true:false; $.os.supportsTouch = ((window.DocumentTouch && document instanceof window.DocumentTouch) || "ontouchstart" in window); $.os.kindle=userAgent.match(/Silk-Accelerated/)?true:false; if($.os.ios) { if(Promise&&Promise.toString().indexOf("native")!==-1) $.os.ios7=true; } //features $.feat = {}; var head = document.documentElement.getElementsByTagName("head")[0]; $.feat.nativeTouchScroll = typeof(head.style["-webkit-overflow-scrolling"]) !== "undefined" && ($.os.ios||$.os.blackberry10); $.feat.cssPrefix = $.os.webkit ? "Webkit" : $.os.fennec ? "Moz" : $.os.ie ? "ms" : $.os.opera ? "O" : ""; $.feat.cssTransformStart = !$.os.opera ? "3d(" : "("; $.feat.cssTransformEnd = !$.os.opera ? ",0)" : ")"; if ($.os.android && !$.os.webkit) $.os.android = false; } detectUA($, navigator.userAgent); $.__detectUA = detectUA; //needed for unit tests /** * Utility function to create a psuedo GUID ``` var id= $.uuid(); ``` * @title $.uuid */ $.uuid = function () { var S4 = function () { return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1); }; return (S4() + S4() + "-" + S4() + "-" + S4() + "-" + S4() + "-" + S4() + S4() + S4()); }; /** * Gets the css matrix, or creates a fake one ``` $.getCssMatrix(domElement) ``` @returns matrix with postion */ $.getCssMatrix = function(ele) { if ($.is$(ele)) ele = ele.get(0); var matrixFn = window.WebKitCSSMatrix || window.MSCSSMatrix; if (ele === nundefined) { if (matrixFn) { return new matrixFn(); } else { return { a: 0, b: 0, c: 0, d: 0, e: 0, f: 0 }; } } var computedStyle = window.getComputedStyle(ele); var transform = computedStyle.webkitTransform || computedStyle.transform || computedStyle[$.feat.cssPrefix + "Transform"]; if (matrixFn) return new matrixFn(transform); else if (transform) { //fake css matrix var mat = transform.replace(/[^0-9\-.,]/g, "").split(","); return { a: +mat[0], b: +mat[1], c: +mat[2], d: +mat[3], e: +mat[4], f: +mat[5] }; } else { return { a: 0, b: 0, c: 0, d: 0, e: 0, f: 0 }; } }; /** * $.create - a faster alertnative to $("<div id='main'>this is some text</div>"); ``` $.create("div",{id:'main',innerHTML:'this is some text'}); $.create("<div id='main'>this is some text</div>"); ``` * @param {String} DOM Element type or html * @param [{Object}] properties to apply to the element * @return {Object} Returns an appframework object * @title $.create(type,[params]) */ $.create = function(type, props) { var elem; var f = new $(); if (props || type[0] !== "<") { if (props.html){ props.innerHTML = props.html; delete props.html; } elem = document.createElement(type); for (var j in props) { elem[j] = props[j]; } f[f.length++] = elem; } else { elem = document.createElement("div"); if (isWin8) { MSApp.execUnsafeLocalFunction(function() { elem.innerHTML = type.trim(); }); } else elem.innerHTML = type; _shimNodes(elem.childNodes, f); } return f; }; /** * $.query - a faster alertnative to $("div"); ``` $.query(".panel"); ``` * @param {String} selector * @param {Object} [context] * @return {Object} Returns an appframework object * @title $.query(selector,[context]) */ $.query = function (sel, what) { try { return $(sel,what); } catch(e) { return $(); } }; /* The following are for events on objects */ /** * Bind an event to an object instead of a DOM Node ``` $.bind(this,'event',function(){}); ``` * @param {Object} object * @param {String} event name * @param {Function} function to execute * @title $.bind(object,event,function); */ $.bind = function (obj, ev, f) { if (!obj.__events) obj.__events = {}; if (!$.isArray(ev)) ev = [ev]; for (var i = 0; i < ev.length; i++) { if (!obj.__events[ev[i]]) obj.__events[ev[i]] = []; obj.__events[ev[i]].push(f); } }; /** * Trigger an event to an object instead of a DOM Node ``` $.trigger(this,'event',arguments); ``` * @param {Object} object * @param {String} event name * @param {Array} arguments * @title $.trigger(object,event,argments); */ $.trigger = function (obj, ev, args) { var ret = true; if (!obj.__events) return ret; if (!$.isArray(ev)) ev = [ev]; if (!$.isArray(args)) args = []; for (var i = 0; i < ev.length; i++) { if (obj.__events[ev[i]]) { var evts = obj.__events[ev[i]]; for (var j = 0; j < evts.length; j++) if ($.isFunction(evts[j]) && evts[j].apply(obj, args) === false) ret = false; } } return ret; }; /** * Unbind an event to an object instead of a DOM Node ``` $.unbind(this,'event',function(){}); ``` * @param {Object} object * @param {String} event name * @param {Function} function to execute * @title $.unbind(object,event,function); */ $.unbind = function (obj, ev, f) { if (!obj.__events) return; if(ev==nundefined) { delete obj.__events; return; } if (!$.isArray(ev)) ev = [ev]; for (var i = 0; i < ev.length; i++) { if (obj.__events[ev[i]]) { var evts = obj.__events[ev[i]]; for (var j = 0; j < evts.length; j++) { if (f ==nundefined) delete evts[j]; if (evts[j] === f) { evts.splice(j, 1); break; } } } } }; $.cleanUpContent = function(){}; $.isObject = function (obj) { return typeof obj === "object"; }; $.asap = function (fn, context, args) { if (!$.isFunction(fn)) throw "$.asap - argument is not a valid function"; setTimeout(function(){ fn.apply(context,args); }); }; /** * this function executes javascript in HTML. ``` $.parseJS(content) ``` * @param {String|DOM} content * @title $.parseJS(content); */ var remoteJSPages = {}; $.parseJS = function (div) { if (!div) return; if (typeof (div) === "string") { var elem = document.createElement("div"); if(isWin8){ MSApp.execUnsafeLocalFunction(function(){ elem.innerHTML = div; }); } else elem.innerHTML = div; div = elem; } var scripts = div.getElementsByTagName("script"); div = null; for (var i = 0; i < scripts.length; i++) { if (scripts[i].src.length > 0 && !remoteJSPages[scripts[i].src]&&!isWin8) { var doc = document.createElement("script"); doc.type = scripts[i].type; doc.src = scripts[i].src; document.getElementsByTagName("head")[0].appendChild(doc); remoteJSPages[scripts[i].src] = 1; doc = null; } else { window["eval"](scripts[i].innerHTML); } } }; $.is$ = function (obj) { return obj instanceof $; }; $.jsonP = function(options) { if (isWin8) { options.type = "get"; options.dataType = null; return $.get(options); } var callbackName = "jsonp_callback" + (++_jsonPID); var abortTimeout = "", context, callback; var script = document.createElement("script"); window[callbackName] = function(data) { clearTimeout(abortTimeout); $(script).remove(); delete window[callbackName]; options.success.call(context, data); }; if (options.url.indexOf("callback=?") !== -1) { script.src = options.url.replace(/=\?/, "=" + callbackName); } else { callback = options.jsonp ? options.jsonp : "callback"; if (options.url.indexOf("?") === -1) { options.url += ("?" + callback + "=" + callbackName); } else { options.url += ("&" + callback + "=" + callbackName); } script.src = options.url; } if (options.error) { script.onerror = function() { clearTimeout(abortTimeout); options.error.call(context, "", "error"); }; } $("head").append(script); if (options.timeout > 0) abortTimeout = setTimeout(function() { options.error.call(context, "", "timeout"); }, options.timeout); return {}; }; //Shim to put touch events on the jQuery special event window.$afm=$; if (!window.numOnly) { window.numOnly = function numOnly(val) { if (val ===undefined || val === "") return 0; if (isNaN(parseFloat(val))) { if (val.replace) { val = val.replace(/[^0-9.-]/g, ""); } else return 0; } return parseFloat(val); }; } })(jQuery,window); window.af=window.jq=jQuery;
/** * angular-permission * Route permission and access control as simple as it can get * @version v2.3.4 - 2016-04-08 * @link https://github.com/Narzerus/angular-permission * @author Rafael Vidaurre <narzerus@gmail.com> (http://www.rafaelvidaurre.com), Blazej Krysiak <blazej.krysiak@gmail.com> * @license MIT License, http://www.opensource.org/licenses/MIT */ (function () { 'use strict'; /** * @namespace permission */ config.$inject = ['$stateProvider']; run.$inject = ['$rootScope', 'TransitionProperties', 'TransitionEvents', 'StateAuthorization', 'StatePermissionMap']; function config($stateProvider) { /** * This decorator is required to access full state object instead of it's configuration * when trying to obtain full toState state object not it's configuration * Can be removed when implemented https://github.com/angular-ui/ui-router/issues/13. */ $stateProvider.decorator('parent', function (state, parentFn) { state.self.$$state = function () { return state; }; state.self.areSetStatePermissions = function () { return angular.isDefined(state.data) && angular.isDefined(state.data.permissions); }; return parentFn(state); }); } function run($rootScope, TransitionProperties, TransitionEvents, StateAuthorization, StatePermissionMap) { /** * State transition interceptor */ $rootScope.$on('$stateChangeStart', function (event, toState, toParams, fromState, fromParams, options) { if (!isAuthorizationFinished()) { event.preventDefault(); setStateAuthorizationStatus(true); setTransitionProperties(); if (!TransitionEvents.areStateEventsDefaultPrevented()) { TransitionEvents.broadcastStateChangePermissionStart(); var statePermissionMap = new StatePermissionMap(); StateAuthorization .authorize(statePermissionMap) .finally(function () { setStateAuthorizationStatus(false); }); } } /** * Updates values of `TransitionProperties` holder object * @method * @private */ function setTransitionProperties() { TransitionProperties.toState = toState; TransitionProperties.toParams = toParams; TransitionProperties.fromState = fromState; TransitionProperties.fromParams = fromParams; TransitionProperties.options = options; } /** * Sets internal state `$$finishedAuthorization` variable to prevent looping * @method * @private * * * @param status {boolean} When true authorization has been already preceded */ function setStateAuthorizationStatus(status) { angular.extend(toState, {'$$isAuthorizationFinished': status}); } /** * Checks if state has been already checked for authorization * @method * @private * * @returns {boolean} */ function isAuthorizationFinished() { return toState.$$isAuthorizationFinished; } }); } angular.module('permission', ['ui.router']) .config(config) .run(run); }()); (function () { 'use strict'; /** * Extends $q implementation by A+ *any* method * @name $q * @extends {angular.$q} * @memberOf permission * * @param $delegate {Object} Angular promise implementation */ $q.$inject = ['$delegate']; function $q($delegate) { $delegate.any = any; /** * Implementation of missing $q `any` method that wits for first resolution of provided promise set * @method * * @param promises {Array|promise} Single or set of promises * * @returns {Promise} Returns a single promise that will be rejected with an array/hash of values, * each value corresponding to the promise at the same index/key in the `promises` array/hash. * If any of the promises is resolved, this resulting promise will be returned * with the same resolution value. */ function any(promises) { var deferred = $delegate.defer(), counter = 0, results = angular.isArray(promises) ? [] : {}; angular.forEach(promises, function (promise, key) { counter++; $delegate .when(promise) .then(function (value) { deferred.resolve(value); }) .catch(function (reason) { results[key] = reason; if (!(--counter)) { deferred.reject(reason); } }); }); if (counter === 0) { deferred.reject(results); } return deferred.promise; } return $delegate; } angular .module('permission') .decorator('$q', $q); })(); (function () { 'use strict'; /** * Pre-defined available configurable behaviours of directive `permission` * @name PermissionStrategies * @memberOf permission * @readonly * * @example * <div permission * permission-except="'MANAGER'" * permission-on-authorized="PermissionStrategies.renderContent" * permission-on-unauthorized="PermissionStrategies.removeContent"> * </div> * * @property enableElement {Function} * @property disableElement {Function} * @property showElement {Function} * @property hideElement {Function} */ var PermissionStrategies = { enableElement: function ($element) { $element.removeAttr('disabled'); }, disableElement: function ($element) { $element.attr('disabled', 'disabled'); }, showElement: function ($element) { $element.removeClass('ng-hide'); }, hideElement: function ($element) { $element.addClass('ng-hide'); } }; angular .module('permission') .constant('PermissionStrategies', PermissionStrategies); }()); (function () { 'use strict'; /** * Helper object used for storing ui-router transition parameters * @name TransitionProperties * @memberOf permission * * @type {Object.<String,Object>} * * @property toState {Object} Target state object * @property toParams {Object} Target state params * @property fromState {Object} Source state object * @property fromParams {Object} Source state params * @property options {Object} Transition options */ var TransitionProperties = { toState: undefined, toParams: undefined, fromState: undefined, fromParams: undefined, options: undefined }; angular .module('permission') .value('TransitionProperties', TransitionProperties); }()); (function () { 'use strict'; /** * Service responsible for managing and emitting events * @name TransitionEvents * @memberOf permission * * @param TransitionProperties {permission.TransitionProperties} Helper storing ui-router transition parameters * @param $rootScope {Object} Top-level angular scope */ TransitionEvents.$inject = ['$rootScope', 'TransitionProperties']; function TransitionEvents($rootScope, TransitionProperties) { this.areStateEventsDefaultPrevented = areStateEventsDefaultPrevented; this.broadcastStateChangePermissionStart = broadcastStateChangePermissionStart; this.broadcastStateChangePermissionAccepted = broadcastStateChangePermissionAccepted; this.broadcastStateChangePermissionDenied = broadcastStateChangePermissionDenied; this.broadcastStateChangeSuccess = broadcastStateChangeSuccess; /** * Checks if state events are not prevented by default * @method * * @returns {boolean} */ function areStateEventsDefaultPrevented() { return isStateChangePermissionStartDefaultPrevented() || isStateChangeStartDefaultPrevented(); } /** * Broadcasts "$stateChangePermissionStart" event from $rootScope * @method */ function broadcastStateChangePermissionStart() { $rootScope.$broadcast('$stateChangePermissionStart', TransitionProperties.toState, TransitionProperties.toParams, TransitionProperties.options); } /** * Broadcasts "$stateChangePermissionAccepted" event from $rootScope * @method */ function broadcastStateChangePermissionAccepted() { $rootScope.$broadcast('$stateChangePermissionAccepted', TransitionProperties.toState, TransitionProperties.toParams, TransitionProperties.options); } /** * Broadcasts "$stateChangeSuccess" event from $rootScope * @method */ function broadcastStateChangeSuccess() { $rootScope.$broadcast('$stateChangeSuccess', TransitionProperties.toState, TransitionProperties.toParams, TransitionProperties.fromState, TransitionProperties.fromParams); } /** * Broadcasts "$tateChangePermissionDenied" event from $rootScope * @method */ function broadcastStateChangePermissionDenied() { $rootScope.$broadcast('$stateChangePermissionDenied', TransitionProperties.toState, TransitionProperties.toParams, TransitionProperties.options); } /** * Checks if event $stateChangeStart hasn't been disabled by default * @method * @private * * @returns {boolean} */ function isStateChangeStartDefaultPrevented() { return $rootScope.$broadcast('$stateChangeStart', TransitionProperties.toState, TransitionProperties.toParams, TransitionProperties.fromState, TransitionProperties.fromParams, TransitionProperties.options).defaultPrevented; } /** * Checks if event $stateChangePermissionStart hasn't been disabled by default * @method * @private * * @returns {boolean} */ function isStateChangePermissionStartDefaultPrevented() { return $rootScope.$broadcast('$stateChangePermissionStart', TransitionProperties.toState, TransitionProperties.toParams, TransitionProperties.options).defaultPrevented; } } angular .module('permission') .service('TransitionEvents', TransitionEvents); }()); (function () { 'use strict'; /** * Access rights map factory * @name PermissionMapFactory * * @param $q {Object} Angular promise implementation * @param TransitionProperties {permission.TransitionProperties} Helper storing ui-router transition parameters * @param RoleStore {permission.RoleStore} Role definition storage * @param PermissionStore {permission.PermissionStore} Permission definition storage * * @return {permission.PermissionMap} */ PermissionMapFactory.$inject = ['$q', 'TransitionProperties', 'RoleStore', 'PermissionStore']; function PermissionMapFactory($q, TransitionProperties, RoleStore, PermissionStore) { /** * Constructs map object instructing authorization service how to handle authorizing * @constructor PermissionMap * @memberOf permission * * @param [permissionMap] {Object} Map of permissions provided to authorization service * @param [permissionMap.only] {Array} List of exclusive access right names allowed for authorization * @param [permissionMap.except] {Array} List of exclusive access right names denied for authorization * @param [permissionMap.redirectTo] {String|Function|Object|promise} Handling redirection when rejected * authorization */ function PermissionMap(permissionMap) { // Suppress not defined object errors permissionMap = permissionMap || {}; this.only = normalizeMapProperty(permissionMap.only); this.except = normalizeMapProperty(permissionMap.except); this.redirectTo = permissionMap.redirectTo; } /** * Redirects to fallback states when permissions fail * @method * @methodOf permission.PermissionMap * * @param rejectedPermissionName {String} Permission name * * @return {Promise} */ PermissionMap.prototype.resolveRedirectState = function (rejectedPermissionName) { if (angular.isFunction(this.redirectTo)) { return resolveFunctionRedirect(this.redirectTo, rejectedPermissionName); } if (angular.isObject(this.redirectTo)) { return resolveObjectRedirect(this.redirectTo, rejectedPermissionName); } if (angular.isString(this.redirectTo)) { return $q.resolve({ state: this.redirectTo }); } // If redirectTo state is not defined stay where you are return $q.reject(null); }; /** * Resolves weather permissions set for "only" or "except" property are valid * @method * * @param property {permissionMap.only|permissionMap.except} "only" or "except" map property * @returns {Array<Promise>} */ PermissionMap.prototype.resolvePropertyValidity = function (property) { return property.map(function (privilegeName) { if (RoleStore.hasRoleDefinition(privilegeName)) { var role = RoleStore.getRoleDefinition(privilegeName); return role.validateRole(); } if (PermissionStore.hasPermissionDefinition(privilegeName)) { var permission = PermissionStore.getPermissionDefinition(privilegeName); return permission.validatePermission(); } return $q.reject(privilegeName); }); }; /** * Handles function based redirection for rejected permissions * @method * @methodOf permission.PermissionMap * @throws {TypeError} * * @param redirectFunction {Function} Redirection function * @param permission {String} Rejected permission * * @return {Promise} */ function resolveFunctionRedirect(redirectFunction, permission) { return $q .when(redirectFunction.call(null, permission)) .then(function (redirectState) { if (angular.isString(redirectState)) { return { state: redirectState }; } if (angular.isObject(redirectState)) { return redirectState; } throw new TypeError('When used "redirectTo" as function, returned value must be string or object'); }); } /** * Handles object based redirection for rejected permissions * @method * @throws {ReferenceError} * * @param redirectObject {Object} Redirection function * @param permission {String} Rejected permission * * @return {Promise} */ function resolveObjectRedirect(redirectObject, permission) { if (!angular.isDefined(redirectObject['default'])) { throw new ReferenceError('When used "redirectTo" as object, property "default" must be defined'); } var redirectState = redirectObject[permission]; if (!angular.isDefined(redirectState)) { redirectState = redirectObject['default']; } if (angular.isFunction(redirectState)) { return resolveFunctionRedirect(redirectState, permission); } if (angular.isObject(redirectState)) { return $q.resolve(redirectState); } if (angular.isString(redirectState)) { return $q.resolve({ state: redirectState }); } } /** * Handles extraction of permission map "only" and "except" properties and converts them into array objects * @method * @private * * @param property {String|Array|Function|Promise} Permission map property "only" or "except" * * @returns {Array<String>} Array of permission "only" or "except" names */ function normalizeMapProperty(property) { if (angular.isString(property)) { return [property]; } if (angular.isArray(property)) { return property; } if (angular.isFunction(property)) { return property.call(null, TransitionProperties); } return []; } return PermissionMap; } angular .module('permission') .factory('PermissionMap', PermissionMapFactory); }()); (function () { 'use strict'; /** * State Access rights map factory * @name StatePermissionMapFactory * * @param TransitionProperties {permission.TransitionProperties} Helper storing ui-router transition parameters * @param PermissionMap {permission.PermissionMap} * * @return {permission.StatePermissionMap} */ StatePermissionMapFactory.$inject = ['TransitionProperties', 'PermissionMap']; function StatePermissionMapFactory(TransitionProperties, PermissionMap) { StatePermissionMap.prototype = new PermissionMap(); StatePermissionMap.constructor = StatePermissionMap; StatePermissionMap.prototype.parent = PermissionMap.prototype; /** * Constructs map object instructing authorization service how to handle authorizing * @constructor StatePermissionMap * @extends PermissionMap * @memberOf permission */ function StatePermissionMap() { this.parent.constructor.call(this); var toStateObject = TransitionProperties.toState.$$state(); var toStatePath = toStateObject.path.slice().reverse(); angular.forEach(toStatePath, function (state) { if (state.areSetStatePermissions()) { var permissionMap = new PermissionMap(state.data.permissions); this.extendPermissionMap(permissionMap); } }, this); } /** * Extends permission map by pushing to it state's permissions * @method * @methodOf permission.StatePermissionMap * * @param permissionMap {permission.PermissionMap} Compensated permission map */ StatePermissionMap.prototype.extendPermissionMap = function (permissionMap) { if (permissionMap.only.length) { this.only = this.only.concat([permissionMap.only]); } if (permissionMap.except.length) { this.except = this.except.concat([permissionMap.except]); } this.redirectTo = permissionMap.redirectTo; }; return StatePermissionMap; } angular .module('permission') .factory('StatePermissionMap', StatePermissionMapFactory); }()); (function () { 'use strict'; /** * Permission definition factory * @name PermissionFactory * * @param $q {Object} Angular promise implementation * @param TransitionProperties {permission.TransitionProperties} Helper storing ui-router transition parameters * * @return {permission.Permission} */ PermissionFactory.$inject = ['$q', 'TransitionProperties']; function PermissionFactory($q, TransitionProperties) { /** * Permission definition object constructor * @class Permission * @memberOf permission * * @param permissionName {String} Name repressing permission * @param validationFunction {Function} Function used to check if permission is valid */ function Permission(permissionName, validationFunction) { validateConstructor(permissionName, validationFunction); this.permissionName = permissionName; this.validationFunction = validationFunction; } /** * Checks if permission is still valid * @method * @methodOf permission.Permission * * @returns {Promise} */ Permission.prototype.validatePermission = function () { var validationResult = this.validationFunction.call(null, this.permissionName, TransitionProperties); if (!angular.isFunction(validationResult.then)) { validationResult = wrapInPromise(validationResult, this.permissionName); } return validationResult; }; /** * Converts a value into a promise, if the value is truthy it resolves it, otherwise it rejects it * @method * @private * * @param result {Boolean} Function to be wrapped into promise * @param permissionName {String} Returned value in promise * @return {Promise} */ function wrapInPromise(result, permissionName) { var dfd = $q.defer(); if (result) { dfd.resolve(permissionName); } else { dfd.reject(permissionName); } return dfd.promise; } /** * Checks if provided permission has accepted parameter types * @method * @private * @throws {TypeError} */ function validateConstructor(permissionName, validationFunction) { if (!angular.isString(permissionName)) { throw new TypeError('Parameter "permissionName" name must be String'); } if (!angular.isFunction(validationFunction)) { throw new TypeError('Parameter "validationFunction" must be Function'); } } return Permission; } angular .module('permission') .factory('Permission', PermissionFactory); }()); (function () { 'use strict'; /** * Role definition factory * @name RoleFactory * * @param $q {Object} Angular promise implementation * @param PermissionStore {permission.PermissionStore} Permission definition storage * @param TransitionProperties {permission.TransitionProperties} Helper storing ui-router transition parameters * * @return {permission.Role} */ RoleFactory.$inject = ['$q', 'PermissionStore', 'TransitionProperties']; function RoleFactory($q, PermissionStore, TransitionProperties) { /** * Role definition constructor * @class Role * @memberOf permission * * @param roleName {String} Name representing role * @param permissionNames {Array} List of permission names representing role * @param [validationFunction] {Function} Optional function used to validate if permissions are still valid */ function Role(roleName, permissionNames, validationFunction) { validateConstructor(roleName, permissionNames, validationFunction); this.roleName = roleName; this.permissionNames = permissionNames || []; this.validationFunction = validationFunction; if (validationFunction) { PermissionStore.defineManyPermissions(permissionNames, validationFunction); } } /** * Checks if role is still valid * @method * @methodOf permission.Role * * @returns {Promise} $q.promise object */ Role.prototype.validateRole = function () { // When permission set is provided check each of them if (this.permissionNames.length) { var promises = this.permissionNames.map(function (permissionName) { if (PermissionStore.hasPermissionDefinition(permissionName)) { var permission = PermissionStore.getPermissionDefinition(permissionName); var validationResult = permission.validationFunction.call(null, permission.permissionName, TransitionProperties); if (!angular.isFunction(validationResult.then)) { validationResult = wrapInPromise(validationResult); } return validationResult; } return $q.reject(); }); return $q.all(promises); } // If not call validation function manually var validationResult = this.validationFunction.call(null, this.roleName, TransitionProperties); if (!angular.isFunction(validationResult.then)) { validationResult = wrapInPromise(validationResult, this.roleName); } return $q.resolve(validationResult); }; /** * Converts a value into a promise, if the value is truthy it resolves it, otherwise it rejects it * @method * @private * * @param result {Boolean} Function to be wrapped into promise * @param [roleName] {String} Returned value in promise * * @return {Promise} */ function wrapInPromise(result, roleName) { var dfd = $q.defer(); if (result) { dfd.resolve(roleName); } else { dfd.reject(roleName); } return dfd.promise; } /** * Checks if provided permission has accepted parameter types * @method * @private * @throws {TypeError} */ function validateConstructor(roleName, permissionNames, validationFunction) { if (!angular.isString(roleName)) { throw new TypeError('Parameter "roleName" name must be String'); } if (!angular.isArray(permissionNames)) { throw new TypeError('Parameter "permissionNames" must be Array'); } if (!permissionNames.length && !angular.isFunction(validationFunction)) { throw new TypeError('Parameter "validationFunction" must be provided for empty "permissionNames" array'); } } return Role; } angular .module('permission') .factory('Role', RoleFactory); }()); (function () { 'use strict'; /** * Permission definition storage * @name PermissionStore * @memberOf permission * * @param Permission {permission.PermissionFactory} Permission definition factory */ PermissionStore.$inject = ['Permission']; function PermissionStore(Permission) { /** * @property permissionStore * * @type {Object} */ var permissionStore = {}; this.definePermission = definePermission; this.defineManyPermissions = defineManyPermissions; this.removePermissionDefinition = removePermissionDefinition; this.hasPermissionDefinition = hasPermissionDefinition; this.getPermissionDefinition = getPermissionDefinition; this.getStore = getStore; this.clearStore = clearStore; /** * Allows to define permission on application configuration * @method * * @param permissionName {String} Name of defined permission * @param validationFunction {Function} Function used to validate if permission is valid */ function definePermission(permissionName, validationFunction) { var permission = new Permission(permissionName, validationFunction); permissionStore[permissionName] = permission; } /** * Allows to define set of permissionNames with shared validation function on application configuration * @method * @throws {TypeError} * * @param permissionNames {Array<String>} Set of permission names * @param validationFunction {Function} Function used to validate if permission is valid */ function defineManyPermissions(permissionNames, validationFunction) { if (!angular.isArray(permissionNames)) { throw new TypeError('Parameter "permissionNames" name must be Array'); } angular.forEach(permissionNames, function (permissionName) { definePermission(permissionName, validationFunction); }); } /** * Deletes permission * @method * * @param permissionName {String} Name of defined permission */ function removePermissionDefinition(permissionName) { delete permissionStore[permissionName]; } /** * Checks if permission exists * @method * * @param permissionName {String} Name of defined permission * @returns {Boolean} */ function hasPermissionDefinition(permissionName) { return angular.isDefined(permissionStore[permissionName]); } /** * Returns permission by it's name * @method * * @returns {permission.Permission} Permissions definition object */ function getPermissionDefinition(permissionName) { return permissionStore[permissionName]; } /** * Returns all permissions * @method * * @returns {Object} Permissions collection */ function getStore() { return permissionStore; } /** * Removes all permissions * @method */ function clearStore() { permissionStore = {}; } } angular .module('permission') .service('PermissionStore', PermissionStore); }()); (function () { 'use strict'; /** * Role definition storage * @name RoleStore * @memberOf permission * * @param Role {permission.Role|Function} Role definition constructor */ RoleStore.$inject = ['Role']; function RoleStore(Role) { var roleStore = {}; this.defineRole = defineRole; this.getRoleDefinition = getRoleDefinition; this.hasRoleDefinition = hasRoleDefinition; this.removeRoleDefinition = removeRoleDefinition; this.getStore = getStore; this.clearStore = clearStore; /** * Allows to define role * @method * * @param roleName {String} Name of defined role * @param permissions {Array<String>} Set of permission names * @param [validationFunction] {Function} Function used to validate if permissions in role are valid */ function defineRole(roleName, permissions, validationFunction) { roleStore[roleName] = new Role(roleName, permissions, validationFunction); } /** * Deletes role from store * @method * * @param roleName {String} Name of defined permission */ function removeRoleDefinition(roleName) { delete roleStore[roleName]; } /** * Checks if role is defined in store * @method * * @param roleName {String} Name of role * @returns {Boolean} */ function hasRoleDefinition(roleName) { return angular.isDefined(roleStore[roleName]); } /** * Returns role definition object by it's name * @method * * @returns {permission.Role} Role definition object */ function getRoleDefinition(roleName) { return roleStore[roleName]; } /** * Returns all role definitions * @method * * @returns {Object} Defined roles collection */ function getStore() { return roleStore; } /** * Removes all role definitions * @method */ function clearStore() { roleStore = {}; } } angular .module('permission') .service('RoleStore', RoleStore); }()); (function () { 'use strict'; /** * Handles authorization based on provided permissions/roles. * @name permissionDirective * @memberOf permission * * Directive accepts single or combined attributes `permission-only` and `permission-except` that checks on * DOM rendering if permissions/roles are met. Attributes can be passed either as String, Array or variable from * parent scope. Directive also will watch for changes if applied and automatically update the view. * * @example * <div permission * permission-only="'USER'"> * </div> * <div permission * permission-only="['USER','ADMIN']" * permission-except="'MANAGER'"> * </div> * * By default directive will show/hide elements if provided permissions matches. * You can override this behaviour by passing `permission-on-authorized` and `permission-on-unauthorized` * attributes that will pass to your function `$element` as argument that you can freely manipulate your DOM * behaviour. * * Important! Function should be as references - `vm.disableElement` not `vm.disableElement()` to be able to * accept passed $element reference from inside of permissionDirective * * @example * <div permission * permission-only="['USER','ADMIN']" * permission-on-authorized="PermissionStrategies.disableElement" * permission-on-unauthorized="PermissionStrategies.enableElement"> * </div> * * @param $log {Object} Logging service * @param Authorization {permission.Authorization} Authorization service * @param PermissionMap {permission.PermissionMap} Map of state access rights * @param PermissionStrategies {permission.PermissionStrategies} Set of pre-defined directive behaviours * * @returns {Object} Directive instance */ permissionDirective.$inject = ['$log', 'Authorization', 'PermissionMap', 'PermissionStrategies']; function permissionDirective($log, Authorization, PermissionMap, PermissionStrategies) { return { restrict: 'A', scope: false, bindToController: { only: '=?permissionOnly', except: '=?permissionExcept', onAuthorized: '&?permissionOnAuthorized', onUnauthorized: '&?permissionOnUnauthorized', // Observing attribute `only` and `except` will be removed with version 2.3.0+ deprecatedOnly: '=only', deprecatedExcept: '=except' }, controllerAs: 'permission', controller: ['$scope', '$element', function ($scope, $element) { var permission = this; if (angular.isDefined(permission.deprecatedOnly) || angular.isDefined(permission.deprecatedExcept)) { $log.warn('Attributes "only" and "except" are deprecated since 2.2.0+ and their support ' + 'will be removed from 2.4.0. Use scoped "permission-only" and "permission-except" instead.'); } /** * Observing attribute `only` and `except` will be removed with version 2.4.0+ */ $scope.$watchGroup(['permission.only', 'permission.except', 'permission.deprecatedOnly', 'permission.deprecatedExcept'], function () { try { var permissionMap = new PermissionMap({ only: permission.only || permission.deprecatedOnly, except: permission.except || permission.deprecatedExcept }); Authorization .authorize(permissionMap) .then(function () { onAuthorizedAccess(); }) .catch(function () { onUnauthorizedAccess(); }); } catch (e) { onUnauthorizedAccess(); $log.error(e.message); } }); /** * Calls `onAuthorized` function if provided or show element * @private */ function onAuthorizedAccess() { if (angular.isFunction(permission.onAuthorized)) { permission.onAuthorized()($element); } else { PermissionStrategies.showElement($element); } } /** * Calls `onUnauthorized` function if provided or hide element * @private */ function onUnauthorizedAccess() { if (angular.isFunction(permission.onUnauthorized)) { permission.onUnauthorized()($element); } else { PermissionStrategies.hideElement($element); } } }] }; } angular .module('permission') .directive('permission', permissionDirective); }()); (function () { 'use strict'; /** * Service responsible for handling view based authorization * @name Authorization * @memberOf permission * * @param $q {Object} Angular promise implementation */ Authorization.$inject = ['$q']; function Authorization($q) { /** * @type {permission.PermissionMap} * @private */ var map; this.authorize = authorize; /** * Handles authorization based on provided permissions map * @method * * @param permissionsMap {permission.PermissionMap} Map of permission names * * @returns {promise} $q.promise object */ function authorize(permissionsMap) { map = permissionsMap; return authorizePermissionMap(); } /** * Checks authorization for simple view based access * @method * @private * * @returns {promise} $q.promise object */ function authorizePermissionMap() { var deferred = $q.defer(); resolveExceptPrivilegeMap(deferred); return deferred.promise; } /** * Resolves flat set of "except" privileges * @method * @private * * @param deferred {Object} Promise defer * * @returns {Promise} $q.promise object */ function resolveExceptPrivilegeMap(deferred) { var exceptPromises = map.resolvePropertyValidity(map.except); $q.any(exceptPromises) .then(function (rejectedPermissions) { deferred.reject(rejectedPermissions); }) .catch(function () { resolveOnlyPermissionMap(deferred); }); } /** * Resolves flat set of "only" privileges * @method * @private * * @param deferred {Object} Promise defer */ function resolveOnlyPermissionMap(deferred) { if (!map.only.length) { deferred.resolve(); return; } var onlyPromises = map.resolvePropertyValidity(map.only); $q.any(onlyPromises) .then(function (resolvedPermissions) { deferred.resolve(resolvedPermissions); }) .catch(function (rejectedPermission) { deferred.reject(rejectedPermission); }); } } angular .module('permission') .service('Authorization', Authorization); })(); (function () { 'use strict'; /** * Service responsible for handling state based authorization * @name StateAuthorization * @memberOf permission * * @param $q {Object} Angular promise implementation * @param $location {Object} Angular location helper service * @param $state {Object} Current state provider * @param TransitionEvents {permission.TransitionEvents} Event management service * @param TransitionProperties {permission.TransitionProperties} Transition properties holder */ StateAuthorization.$inject = ['$q', '$location', '$state', 'TransitionEvents', 'TransitionProperties']; function StateAuthorization($q, $location, $state, TransitionEvents, TransitionProperties) { /** * @type {permission.StatePermissionMap} * @private */ var map; this.authorize = authorize; /** * Handles state authorization * @method {permission.StatePermissionMap} * @param statePermissionMap * * @return {promise} */ function authorize(statePermissionMap) { map = statePermissionMap; return authorizeStatePermissionMap() .then(function () { handleAuthorizedState(); }) .catch(function (rejectedPermission) { handleUnauthorizedState(rejectedPermission); }); } /** * Checks authorization for complex state inheritance * @method * @private * * @returns {promise} $q.promise object */ function authorizeStatePermissionMap() { var deferred = $q.defer(); resolveExceptStatePermissionMap(deferred); return deferred.promise; } /** * Resolves compensated set of "except" privileges * @method * @private * * @param deferred {Object} Promise defer */ function resolveExceptStatePermissionMap(deferred) { var exceptPromises = resolveStatePermissionMap(map.except); $q.all(exceptPromises) .then(function (rejectedPermissions) { deferred.reject(rejectedPermissions); }) .catch(function () { resolveOnlyStatePermissionMap(deferred); }); } /** * Resolves compensated set of "only" privileges * @method * @private * * @param deferred {Object} Promise defer */ function resolveOnlyStatePermissionMap(deferred) { if (!map.only.length) { deferred.resolve(); return; } var onlyPromises = resolveStatePermissionMap(map.only); $q.all(onlyPromises) .then(function (resolvedPermissions) { deferred.resolve(resolvedPermissions); }) .catch(function (rejectedPermission) { deferred.reject(rejectedPermission); }); } /** * Performs iteration over list of privileges looking for matches * @method * @private * * @param privilegesNames {Array} Array of sets of access rights * * @returns {Array<Promise>} Promise collection */ function resolveStatePermissionMap(privilegesNames) { if (!privilegesNames.length) { return [$q.reject()]; } return privilegesNames.map(function (statePrivileges) { var resolvedStatePrivileges = map.resolvePropertyValidity(statePrivileges); return $q.any(resolvedStatePrivileges); }); } /** * Handles redirection for authorized access * @method * @private */ function handleAuthorizedState() { TransitionEvents.broadcastStateChangePermissionAccepted(); $location.replace(); // Overwrite notify option to broadcast it later TransitionProperties.options = angular.extend({}, TransitionProperties.options, {notify: false}); $state .go(TransitionProperties.toState.name, TransitionProperties.toParams, TransitionProperties.options) .then(function () { TransitionEvents.broadcastStateChangeSuccess(); }); } /** * Handles redirection for unauthorized access * @method * @private * * @param rejectedPermission {String} Rejected access right */ function handleUnauthorizedState(rejectedPermission) { TransitionEvents.broadcastStateChangePermissionDenied(); map .resolveRedirectState(rejectedPermission) .then(function (redirect) { $state.go(redirect.state, redirect.params, redirect.options); }); } } angular .module('permission') .service('StateAuthorization', StateAuthorization); })();
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.Cycle = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){ // shim for using process in browser var process = module.exports = {}; var queue = []; var draining = false; var currentQueue; var queueIndex = -1; function cleanUpNextTick() { 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) { 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'); }; // TODO(shtylman) process.cwd = function () { return '/' }; process.chdir = function (dir) { throw new Error('process.chdir is not supported'); }; process.umask = function() { return 0; }; },{}],2:[function(require,module,exports){ (function (process,global){ // Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. ;(function (undefined) { var objectTypes = { 'boolean': false, 'function': true, 'object': true, 'number': false, 'string': false, 'undefined': false }; var root = (objectTypes[typeof window] && window) || this, freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports, freeModule = objectTypes[typeof module] && module && !module.nodeType && module, moduleExports = freeModule && freeModule.exports === freeExports && freeExports, freeGlobal = objectTypes[typeof global] && global; if (freeGlobal && (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal)) { root = freeGlobal; } var Rx = { internals: {}, config: { Promise: root.Promise }, helpers: { } }; // Defaults var noop = Rx.helpers.noop = function () { }, notDefined = Rx.helpers.notDefined = function (x) { return typeof x === 'undefined'; }, identity = Rx.helpers.identity = function (x) { return x; }, pluck = Rx.helpers.pluck = function (property) { return function (x) { return x[property]; }; }, just = Rx.helpers.just = function (value) { return function () { return value; }; }, defaultNow = Rx.helpers.defaultNow = Date.now, defaultComparer = Rx.helpers.defaultComparer = function (x, y) { return isEqual(x, y); }, defaultSubComparer = Rx.helpers.defaultSubComparer = function (x, y) { return x > y ? 1 : (x < y ? -1 : 0); }, defaultKeySerializer = Rx.helpers.defaultKeySerializer = function (x) { return x.toString(); }, defaultError = Rx.helpers.defaultError = function (err) { throw err; }, isPromise = Rx.helpers.isPromise = function (p) { return !!p && typeof p.subscribe !== 'function' && typeof p.then === 'function'; }, asArray = Rx.helpers.asArray = function () { return Array.prototype.slice.call(arguments); }, not = Rx.helpers.not = function (a) { return !a; }, isFunction = Rx.helpers.isFunction = (function () { var isFn = function (value) { return typeof value == 'function' || false; } // fallback for older versions of Chrome and Safari if (isFn(/x/)) { isFn = function(value) { return typeof value == 'function' && toString.call(value) == '[object Function]'; }; } return isFn; }()); function cloneArray(arr) { for(var a = [], i = 0, len = arr.length; i < len; i++) { a.push(arr[i]); } return a;} Rx.config.longStackSupport = false; var hasStacks = false; try { throw new Error(); } catch (e) { hasStacks = !!e.stack; } // All code after this point will be filtered from stack traces reported by RxJS var rStartingLine = captureLine(), rFileName; var STACK_JUMP_SEPARATOR = "From previous event:"; function makeStackTraceLong(error, observable) { // If possible, transform the error stack trace by removing Node and RxJS // cruft, then concatenating with the stack trace of `observable`. if (hasStacks && observable.stack && typeof error === "object" && error !== null && error.stack && error.stack.indexOf(STACK_JUMP_SEPARATOR) === -1 ) { var stacks = []; for (var o = observable; !!o; o = o.source) { if (o.stack) { stacks.unshift(o.stack); } } stacks.unshift(error.stack); var concatedStacks = stacks.join("\n" + STACK_JUMP_SEPARATOR + "\n"); error.stack = filterStackString(concatedStacks); } } function filterStackString(stackString) { var lines = stackString.split("\n"), desiredLines = []; for (var i = 0, len = lines.length; i < len; i++) { var line = lines[i]; if (!isInternalFrame(line) && !isNodeFrame(line) && line) { desiredLines.push(line); } } return desiredLines.join("\n"); } function isInternalFrame(stackLine) { var fileNameAndLineNumber = getFileNameAndLineNumber(stackLine); if (!fileNameAndLineNumber) { return false; } var fileName = fileNameAndLineNumber[0], lineNumber = fileNameAndLineNumber[1]; return fileName === rFileName && lineNumber >= rStartingLine && lineNumber <= rEndingLine; } function isNodeFrame(stackLine) { return stackLine.indexOf("(module.js:") !== -1 || stackLine.indexOf("(node.js:") !== -1; } function captureLine() { if (!hasStacks) { return; } try { throw new Error(); } catch (e) { var lines = e.stack.split("\n"); var firstLine = lines[0].indexOf("@") > 0 ? lines[1] : lines[2]; var fileNameAndLineNumber = getFileNameAndLineNumber(firstLine); if (!fileNameAndLineNumber) { return; } rFileName = fileNameAndLineNumber[0]; return fileNameAndLineNumber[1]; } } function getFileNameAndLineNumber(stackLine) { // Named functions: "at functionName (filename:lineNumber:columnNumber)" var attempt1 = /at .+ \((.+):(\d+):(?:\d+)\)$/.exec(stackLine); if (attempt1) { return [attempt1[1], Number(attempt1[2])]; } // Anonymous functions: "at filename:lineNumber:columnNumber" var attempt2 = /at ([^ ]+):(\d+):(?:\d+)$/.exec(stackLine); if (attempt2) { return [attempt2[1], Number(attempt2[2])]; } // Firefox style: "function@filename:lineNumber or @filename:lineNumber" var attempt3 = /.*@(.+):(\d+)$/.exec(stackLine); if (attempt3) { return [attempt3[1], Number(attempt3[2])]; } } var EmptyError = Rx.EmptyError = function() { this.message = 'Sequence contains no elements.'; Error.call(this); }; EmptyError.prototype = Error.prototype; var ObjectDisposedError = Rx.ObjectDisposedError = function() { this.message = 'Object has been disposed'; Error.call(this); }; ObjectDisposedError.prototype = Error.prototype; var ArgumentOutOfRangeError = Rx.ArgumentOutOfRangeError = function () { this.message = 'Argument out of range'; Error.call(this); }; ArgumentOutOfRangeError.prototype = Error.prototype; var NotSupportedError = Rx.NotSupportedError = function (message) { this.message = message || 'This operation is not supported'; Error.call(this); }; NotSupportedError.prototype = Error.prototype; var NotImplementedError = Rx.NotImplementedError = function (message) { this.message = message || 'This operation is not implemented'; Error.call(this); }; NotImplementedError.prototype = Error.prototype; var notImplemented = Rx.helpers.notImplemented = function () { throw new NotImplementedError(); }; var notSupported = Rx.helpers.notSupported = function () { throw new NotSupportedError(); }; // Shim in iterator support var $iterator$ = (typeof Symbol === 'function' && Symbol.iterator) || '_es6shim_iterator_'; // Bug for mozilla version if (root.Set && typeof new root.Set()['@@iterator'] === 'function') { $iterator$ = '@@iterator'; } var doneEnumerator = Rx.doneEnumerator = { done: true, value: undefined }; var isIterable = Rx.helpers.isIterable = function (o) { return o[$iterator$] !== undefined; } var isArrayLike = Rx.helpers.isArrayLike = function (o) { return o && o.length !== undefined; } Rx.helpers.iterator = $iterator$; var bindCallback = Rx.internals.bindCallback = function (func, thisArg, argCount) { if (typeof thisArg === 'undefined') { return func; } switch(argCount) { case 0: return function() { return func.call(thisArg) }; case 1: return function(arg) { return func.call(thisArg, arg); } case 2: return function(value, index) { return func.call(thisArg, value, index); }; case 3: return function(value, index, collection) { return func.call(thisArg, value, index, collection); }; } return function() { return func.apply(thisArg, arguments); }; }; /** Used to determine if values are of the language type Object */ var dontEnums = ['toString', 'toLocaleString', 'valueOf', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'constructor'], dontEnumsLength = dontEnums.length; /** `Object#toString` result shortcuts */ var argsClass = '[object Arguments]', arrayClass = '[object Array]', boolClass = '[object Boolean]', dateClass = '[object Date]', errorClass = '[object Error]', funcClass = '[object Function]', numberClass = '[object Number]', objectClass = '[object Object]', regexpClass = '[object RegExp]', stringClass = '[object String]'; var toString = Object.prototype.toString, hasOwnProperty = Object.prototype.hasOwnProperty, supportsArgsClass = toString.call(arguments) == argsClass, // For less <IE9 && FF<4 supportNodeClass, errorProto = Error.prototype, objectProto = Object.prototype, stringProto = String.prototype, propertyIsEnumerable = objectProto.propertyIsEnumerable; try { supportNodeClass = !(toString.call(document) == objectClass && !({ 'toString': 0 } + '')); } catch (e) { supportNodeClass = true; } var nonEnumProps = {}; nonEnumProps[arrayClass] = nonEnumProps[dateClass] = nonEnumProps[numberClass] = { 'constructor': true, 'toLocaleString': true, 'toString': true, 'valueOf': true }; nonEnumProps[boolClass] = nonEnumProps[stringClass] = { 'constructor': true, 'toString': true, 'valueOf': true }; nonEnumProps[errorClass] = nonEnumProps[funcClass] = nonEnumProps[regexpClass] = { 'constructor': true, 'toString': true }; nonEnumProps[objectClass] = { 'constructor': true }; var support = {}; (function () { var ctor = function() { this.x = 1; }, props = []; ctor.prototype = { 'valueOf': 1, 'y': 1 }; for (var key in new ctor) { props.push(key); } for (key in arguments) { } // Detect if `name` or `message` properties of `Error.prototype` are enumerable by default. support.enumErrorProps = propertyIsEnumerable.call(errorProto, 'message') || propertyIsEnumerable.call(errorProto, 'name'); // Detect if `prototype` properties are enumerable by default. support.enumPrototypes = propertyIsEnumerable.call(ctor, 'prototype'); // Detect if `arguments` object indexes are non-enumerable support.nonEnumArgs = key != 0; // Detect if properties shadowing those on `Object.prototype` are non-enumerable. support.nonEnumShadows = !/valueOf/.test(props); }(1)); var isObject = Rx.internals.isObject = function(value) { var type = typeof value; return value && (type == 'function' || type == 'object') || false; }; function keysIn(object) { var result = []; if (!isObject(object)) { return result; } if (support.nonEnumArgs && object.length && isArguments(object)) { object = slice.call(object); } var skipProto = support.enumPrototypes && typeof object == 'function', skipErrorProps = support.enumErrorProps && (object === errorProto || object instanceof Error); for (var key in object) { if (!(skipProto && key == 'prototype') && !(skipErrorProps && (key == 'message' || key == 'name'))) { result.push(key); } } if (support.nonEnumShadows && object !== objectProto) { var ctor = object.constructor, index = -1, length = dontEnumsLength; if (object === (ctor && ctor.prototype)) { var className = object === stringProto ? stringClass : object === errorProto ? errorClass : toString.call(object), nonEnum = nonEnumProps[className]; } while (++index < length) { key = dontEnums[index]; if (!(nonEnum && nonEnum[key]) && hasOwnProperty.call(object, key)) { result.push(key); } } } return result; } function internalFor(object, callback, keysFunc) { var index = -1, props = keysFunc(object), length = props.length; while (++index < length) { var key = props[index]; if (callback(object[key], key, object) === false) { break; } } return object; } function internalForIn(object, callback) { return internalFor(object, callback, keysIn); } function isNode(value) { // IE < 9 presents DOM nodes as `Object` objects except they have `toString` // methods that are `typeof` "string" and still can coerce nodes to strings return typeof value.toString != 'function' && typeof (value + '') == 'string'; } var isArguments = function(value) { return (value && typeof value == 'object') ? toString.call(value) == argsClass : false; } // fallback for browsers that can't detect `arguments` objects by [[Class]] if (!supportsArgsClass) { isArguments = function(value) { return (value && typeof value == 'object') ? hasOwnProperty.call(value, 'callee') : false; }; } var isEqual = Rx.internals.isEqual = function (x, y) { return deepEquals(x, y, [], []); }; /** @private * Used for deep comparison **/ function deepEquals(a, b, stackA, stackB) { // exit early for identical values if (a === b) { // treat `+0` vs. `-0` as not equal return a !== 0 || (1 / a == 1 / b); } var type = typeof a, otherType = typeof b; // exit early for unlike primitive values if (a === a && (a == null || b == null || (type != 'function' && type != 'object' && otherType != 'function' && otherType != 'object'))) { return false; } // compare [[Class]] names var className = toString.call(a), otherClass = toString.call(b); if (className == argsClass) { className = objectClass; } if (otherClass == argsClass) { otherClass = objectClass; } if (className != otherClass) { return false; } switch (className) { case boolClass: case dateClass: // coerce dates and booleans to numbers, dates to milliseconds and booleans // to `1` or `0` treating invalid dates coerced to `NaN` as not equal return +a == +b; case numberClass: // treat `NaN` vs. `NaN` as equal return (a != +a) ? b != +b : // but treat `-0` vs. `+0` as not equal (a == 0 ? (1 / a == 1 / b) : a == +b); case regexpClass: case stringClass: // coerce regexes to strings (http://es5.github.io/#x15.10.6.4) // treat string primitives and their corresponding object instances as equal return a == String(b); } var isArr = className == arrayClass; if (!isArr) { // exit for functions and DOM nodes if (className != objectClass || (!support.nodeClass && (isNode(a) || isNode(b)))) { return false; } // in older versions of Opera, `arguments` objects have `Array` constructors var ctorA = !support.argsObject && isArguments(a) ? Object : a.constructor, ctorB = !support.argsObject && isArguments(b) ? Object : b.constructor; // non `Object` object instances with different constructors are not equal if (ctorA != ctorB && !(hasOwnProperty.call(a, 'constructor') && hasOwnProperty.call(b, 'constructor')) && !(isFunction(ctorA) && ctorA instanceof ctorA && isFunction(ctorB) && ctorB instanceof ctorB) && ('constructor' in a && 'constructor' in b) ) { return false; } } // assume cyclic structures are equal // the algorithm for detecting cyclic structures is adapted from ES 5.1 // section 15.12.3, abstract operation `JO` (http://es5.github.io/#x15.12.3) var initedStack = !stackA; stackA || (stackA = []); stackB || (stackB = []); var length = stackA.length; while (length--) { if (stackA[length] == a) { return stackB[length] == b; } } var size = 0; var result = true; // add `a` and `b` to the stack of traversed objects stackA.push(a); stackB.push(b); // recursively compare objects and arrays (susceptible to call stack limits) if (isArr) { // compare lengths to determine if a deep comparison is necessary length = a.length; size = b.length; result = size == length; if (result) { // deep compare the contents, ignoring non-numeric properties while (size--) { var index = length, value = b[size]; if (!(result = deepEquals(a[size], value, stackA, stackB))) { break; } } } } else { // deep compare objects using `forIn`, instead of `forOwn`, to avoid `Object.keys` // which, in this case, is more costly internalForIn(b, function(value, key, b) { if (hasOwnProperty.call(b, key)) { // count the number of properties. size++; // deep compare each property value. return (result = hasOwnProperty.call(a, key) && deepEquals(a[key], value, stackA, stackB)); } }); if (result) { // ensure both objects have the same number of properties internalForIn(a, function(value, key, a) { if (hasOwnProperty.call(a, key)) { // `size` will be `-1` if `a` has more properties than `b` return (result = --size > -1); } }); } } stackA.pop(); stackB.pop(); return result; } var hasProp = {}.hasOwnProperty, slice = Array.prototype.slice; var inherits = this.inherits = Rx.internals.inherits = function (child, parent) { function __() { this.constructor = child; } __.prototype = parent.prototype; child.prototype = new __(); }; var addProperties = Rx.internals.addProperties = function (obj) { for(var sources = [], i = 1, len = arguments.length; i < len; i++) { sources.push(arguments[i]); } for (var idx = 0, ln = sources.length; idx < ln; idx++) { var source = sources[idx]; for (var prop in source) { obj[prop] = source[prop]; } } }; // Rx Utils var addRef = Rx.internals.addRef = function (xs, r) { return new AnonymousObservable(function (observer) { return new CompositeDisposable(r.getDisposable(), xs.subscribe(observer)); }); }; function arrayInitialize(count, factory) { var a = new Array(count); for (var i = 0; i < count; i++) { a[i] = factory(); } return a; } var errorObj = {e: {}}; var tryCatchTarget; function tryCatcher() { try { return tryCatchTarget.apply(this, arguments); } catch (e) { errorObj.e = e; return errorObj; } } function tryCatch(fn) { if (!isFunction(fn)) { throw new TypeError('fn must be a function'); } tryCatchTarget = fn; return tryCatcher; } function thrower(e) { throw e; } // Collections function IndexedItem(id, value) { this.id = id; this.value = value; } IndexedItem.prototype.compareTo = function (other) { var c = this.value.compareTo(other.value); c === 0 && (c = this.id - other.id); return c; }; // Priority Queue for Scheduling var PriorityQueue = Rx.internals.PriorityQueue = function (capacity) { this.items = new Array(capacity); this.length = 0; }; var priorityProto = PriorityQueue.prototype; priorityProto.isHigherPriority = function (left, right) { return this.items[left].compareTo(this.items[right]) < 0; }; priorityProto.percolate = function (index) { if (index >= this.length || index < 0) { return; } var parent = index - 1 >> 1; if (parent < 0 || parent === index) { return; } if (this.isHigherPriority(index, parent)) { var temp = this.items[index]; this.items[index] = this.items[parent]; this.items[parent] = temp; this.percolate(parent); } }; priorityProto.heapify = function (index) { +index || (index = 0); if (index >= this.length || index < 0) { return; } var left = 2 * index + 1, right = 2 * index + 2, first = index; if (left < this.length && this.isHigherPriority(left, first)) { first = left; } if (right < this.length && this.isHigherPriority(right, first)) { first = right; } if (first !== index) { var temp = this.items[index]; this.items[index] = this.items[first]; this.items[first] = temp; this.heapify(first); } }; priorityProto.peek = function () { return this.items[0].value; }; priorityProto.removeAt = function (index) { this.items[index] = this.items[--this.length]; this.items[this.length] = undefined; this.heapify(); }; priorityProto.dequeue = function () { var result = this.peek(); this.removeAt(0); return result; }; priorityProto.enqueue = function (item) { var index = this.length++; this.items[index] = new IndexedItem(PriorityQueue.count++, item); this.percolate(index); }; priorityProto.remove = function (item) { for (var i = 0; i < this.length; i++) { if (this.items[i].value === item) { this.removeAt(i); return true; } } return false; }; PriorityQueue.count = 0; /** * Represents a group of disposable resources that are disposed together. * @constructor */ var CompositeDisposable = Rx.CompositeDisposable = function () { var args = [], i, len; if (Array.isArray(arguments[0])) { args = arguments[0]; len = args.length; } else { len = arguments.length; args = new Array(len); for(i = 0; i < len; i++) { args[i] = arguments[i]; } } for(i = 0; i < len; i++) { if (!isDisposable(args[i])) { throw new TypeError('Not a disposable'); } } this.disposables = args; this.isDisposed = false; this.length = args.length; }; var CompositeDisposablePrototype = CompositeDisposable.prototype; /** * Adds a disposable to the CompositeDisposable or disposes the disposable if the CompositeDisposable is disposed. * @param {Mixed} item Disposable to add. */ CompositeDisposablePrototype.add = function (item) { if (this.isDisposed) { item.dispose(); } else { this.disposables.push(item); this.length++; } }; /** * Removes and disposes the first occurrence of a disposable from the CompositeDisposable. * @param {Mixed} item Disposable to remove. * @returns {Boolean} true if found; false otherwise. */ CompositeDisposablePrototype.remove = function (item) { var shouldDispose = false; if (!this.isDisposed) { var idx = this.disposables.indexOf(item); if (idx !== -1) { shouldDispose = true; this.disposables.splice(idx, 1); this.length--; item.dispose(); } } return shouldDispose; }; /** * Disposes all disposables in the group and removes them from the group. */ CompositeDisposablePrototype.dispose = function () { if (!this.isDisposed) { this.isDisposed = true; var len = this.disposables.length, currentDisposables = new Array(len); for(var i = 0; i < len; i++) { currentDisposables[i] = this.disposables[i]; } this.disposables = []; this.length = 0; for (i = 0; i < len; i++) { currentDisposables[i].dispose(); } } }; /** * Provides a set of static methods for creating Disposables. * @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once. */ var Disposable = Rx.Disposable = function (action) { this.isDisposed = false; this.action = action || noop; }; /** Performs the task of cleaning up resources. */ Disposable.prototype.dispose = function () { if (!this.isDisposed) { this.action(); this.isDisposed = true; } }; /** * Creates a disposable object that invokes the specified action when disposed. * @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once. * @return {Disposable} The disposable object that runs the given action upon disposal. */ var disposableCreate = Disposable.create = function (action) { return new Disposable(action); }; /** * Gets the disposable that does nothing when disposed. */ var disposableEmpty = Disposable.empty = { dispose: noop }; /** * Validates whether the given object is a disposable * @param {Object} Object to test whether it has a dispose method * @returns {Boolean} true if a disposable object, else false. */ var isDisposable = Disposable.isDisposable = function (d) { return d && isFunction(d.dispose); }; var checkDisposed = Disposable.checkDisposed = function (disposable) { if (disposable.isDisposed) { throw new ObjectDisposedError(); } }; // Single assignment var SingleAssignmentDisposable = Rx.SingleAssignmentDisposable = function () { this.isDisposed = false; this.current = null; }; SingleAssignmentDisposable.prototype.getDisposable = function () { return this.current; }; SingleAssignmentDisposable.prototype.setDisposable = function (value) { if (this.current) { throw new Error('Disposable has already been assigned'); } var shouldDispose = this.isDisposed; !shouldDispose && (this.current = value); shouldDispose && value && value.dispose(); }; SingleAssignmentDisposable.prototype.dispose = function () { if (!this.isDisposed) { this.isDisposed = true; var old = this.current; this.current = null; } old && old.dispose(); }; // Multiple assignment disposable var SerialDisposable = Rx.SerialDisposable = function () { this.isDisposed = false; this.current = null; }; SerialDisposable.prototype.getDisposable = function () { return this.current; }; SerialDisposable.prototype.setDisposable = function (value) { var shouldDispose = this.isDisposed; if (!shouldDispose) { var old = this.current; this.current = value; } old && old.dispose(); shouldDispose && value && value.dispose(); }; SerialDisposable.prototype.dispose = function () { if (!this.isDisposed) { this.isDisposed = true; var old = this.current; this.current = null; } old && old.dispose(); }; /** * Represents a disposable resource that only disposes its underlying disposable resource when all dependent disposable objects have been disposed. */ var RefCountDisposable = Rx.RefCountDisposable = (function () { function InnerDisposable(disposable) { this.disposable = disposable; this.disposable.count++; this.isInnerDisposed = false; } InnerDisposable.prototype.dispose = function () { if (!this.disposable.isDisposed && !this.isInnerDisposed) { this.isInnerDisposed = true; this.disposable.count--; if (this.disposable.count === 0 && this.disposable.isPrimaryDisposed) { this.disposable.isDisposed = true; this.disposable.underlyingDisposable.dispose(); } } }; /** * Initializes a new instance of the RefCountDisposable with the specified disposable. * @constructor * @param {Disposable} disposable Underlying disposable. */ function RefCountDisposable(disposable) { this.underlyingDisposable = disposable; this.isDisposed = false; this.isPrimaryDisposed = false; this.count = 0; } /** * Disposes the underlying disposable only when all dependent disposables have been disposed */ RefCountDisposable.prototype.dispose = function () { if (!this.isDisposed && !this.isPrimaryDisposed) { this.isPrimaryDisposed = true; if (this.count === 0) { this.isDisposed = true; this.underlyingDisposable.dispose(); } } }; /** * Returns a dependent disposable that when disposed decreases the refcount on the underlying disposable. * @returns {Disposable} A dependent disposable contributing to the reference count that manages the underlying disposable's lifetime. */ RefCountDisposable.prototype.getDisposable = function () { return this.isDisposed ? disposableEmpty : new InnerDisposable(this); }; return RefCountDisposable; })(); function ScheduledDisposable(scheduler, disposable) { this.scheduler = scheduler; this.disposable = disposable; this.isDisposed = false; } function scheduleItem(s, self) { if (!self.isDisposed) { self.isDisposed = true; self.disposable.dispose(); } } ScheduledDisposable.prototype.dispose = function () { this.scheduler.scheduleWithState(this, scheduleItem); }; var ScheduledItem = Rx.internals.ScheduledItem = function (scheduler, state, action, dueTime, comparer) { this.scheduler = scheduler; this.state = state; this.action = action; this.dueTime = dueTime; this.comparer = comparer || defaultSubComparer; this.disposable = new SingleAssignmentDisposable(); } ScheduledItem.prototype.invoke = function () { this.disposable.setDisposable(this.invokeCore()); }; ScheduledItem.prototype.compareTo = function (other) { return this.comparer(this.dueTime, other.dueTime); }; ScheduledItem.prototype.isCancelled = function () { return this.disposable.isDisposed; }; ScheduledItem.prototype.invokeCore = function () { return this.action(this.scheduler, this.state); }; /** Provides a set of static properties to access commonly used schedulers. */ var Scheduler = Rx.Scheduler = (function () { function Scheduler(now, schedule, scheduleRelative, scheduleAbsolute) { this.now = now; this._schedule = schedule; this._scheduleRelative = scheduleRelative; this._scheduleAbsolute = scheduleAbsolute; } /** Determines whether the given object is a scheduler */ Scheduler.isScheduler = function (s) { return s instanceof Scheduler; } function invokeAction(scheduler, action) { action(); return disposableEmpty; } var schedulerProto = Scheduler.prototype; /** * Schedules an action to be executed. * @param {Function} action Action to execute. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.schedule = function (action) { return this._schedule(action, invokeAction); }; /** * Schedules an action to be executed. * @param state State passed to the action to be executed. * @param {Function} action Action to be executed. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleWithState = function (state, action) { return this._schedule(state, action); }; /** * Schedules an action to be executed after the specified relative due time. * @param {Function} action Action to execute. * @param {Number} dueTime Relative time after which to execute the action. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleWithRelative = function (dueTime, action) { return this._scheduleRelative(action, dueTime, invokeAction); }; /** * Schedules an action to be executed after dueTime. * @param state State passed to the action to be executed. * @param {Function} action Action to be executed. * @param {Number} dueTime Relative time after which to execute the action. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleWithRelativeAndState = function (state, dueTime, action) { return this._scheduleRelative(state, dueTime, action); }; /** * Schedules an action to be executed at the specified absolute due time. * @param {Function} action Action to execute. * @param {Number} dueTime Absolute time at which to execute the action. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleWithAbsolute = function (dueTime, action) { return this._scheduleAbsolute(action, dueTime, invokeAction); }; /** * Schedules an action to be executed at dueTime. * @param {Mixed} state State passed to the action to be executed. * @param {Function} action Action to be executed. * @param {Number}dueTime Absolute time at which to execute the action. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleWithAbsoluteAndState = function (state, dueTime, action) { return this._scheduleAbsolute(state, dueTime, action); }; /** Gets the current time according to the local machine's system clock. */ Scheduler.now = defaultNow; /** * Normalizes the specified TimeSpan value to a positive value. * @param {Number} timeSpan The time span value to normalize. * @returns {Number} The specified TimeSpan value if it is zero or positive; otherwise, 0 */ Scheduler.normalize = function (timeSpan) { timeSpan < 0 && (timeSpan = 0); return timeSpan; }; return Scheduler; }()); var normalizeTime = Scheduler.normalize, isScheduler = Scheduler.isScheduler; (function (schedulerProto) { function invokeRecImmediate(scheduler, pair) { var state = pair[0], action = pair[1], group = new CompositeDisposable(); function recursiveAction(state1) { action(state1, function (state2) { var isAdded = false, isDone = false, d = scheduler.scheduleWithState(state2, function (scheduler1, state3) { if (isAdded) { group.remove(d); } else { isDone = true; } recursiveAction(state3); return disposableEmpty; }); if (!isDone) { group.add(d); isAdded = true; } }); } recursiveAction(state); return group; } function invokeRecDate(scheduler, pair, method) { var state = pair[0], action = pair[1], group = new CompositeDisposable(); function recursiveAction(state1) { action(state1, function (state2, dueTime1) { var isAdded = false, isDone = false, d = scheduler[method](state2, dueTime1, function (scheduler1, state3) { if (isAdded) { group.remove(d); } else { isDone = true; } recursiveAction(state3); return disposableEmpty; }); if (!isDone) { group.add(d); isAdded = true; } }); }; recursiveAction(state); return group; } function scheduleInnerRecursive(action, self) { action(function(dt) { self(action, dt); }); } /** * Schedules an action to be executed recursively. * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursive = function (action) { return this.scheduleRecursiveWithState(action, scheduleInnerRecursive); }; /** * Schedules an action to be executed recursively. * @param {Mixed} state State passed to the action to be executed. * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in recursive invocation state. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursiveWithState = function (state, action) { return this.scheduleWithState([state, action], invokeRecImmediate); }; /** * Schedules an action to be executed recursively after a specified relative due time. * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action at the specified relative time. * @param {Number}dueTime Relative time after which to execute the action for the first time. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursiveWithRelative = function (dueTime, action) { return this.scheduleRecursiveWithRelativeAndState(action, dueTime, scheduleInnerRecursive); }; /** * Schedules an action to be executed recursively after a specified relative due time. * @param {Mixed} state State passed to the action to be executed. * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in the recursive due time and invocation state. * @param {Number}dueTime Relative time after which to execute the action for the first time. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursiveWithRelativeAndState = function (state, dueTime, action) { return this._scheduleRelative([state, action], dueTime, function (s, p) { return invokeRecDate(s, p, 'scheduleWithRelativeAndState'); }); }; /** * Schedules an action to be executed recursively at a specified absolute due time. * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action at the specified absolute time. * @param {Number}dueTime Absolute time at which to execute the action for the first time. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursiveWithAbsolute = function (dueTime, action) { return this.scheduleRecursiveWithAbsoluteAndState(action, dueTime, scheduleInnerRecursive); }; /** * Schedules an action to be executed recursively at a specified absolute due time. * @param {Mixed} state State passed to the action to be executed. * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in the recursive due time and invocation state. * @param {Number}dueTime Absolute time at which to execute the action for the first time. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursiveWithAbsoluteAndState = function (state, dueTime, action) { return this._scheduleAbsolute([state, action], dueTime, function (s, p) { return invokeRecDate(s, p, 'scheduleWithAbsoluteAndState'); }); }; }(Scheduler.prototype)); (function (schedulerProto) { /** * Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be scheduled using window.setInterval for the base implementation. * @param {Number} period Period for running the work periodically. * @param {Function} action Action to be executed. * @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort). */ Scheduler.prototype.schedulePeriodic = function (period, action) { return this.schedulePeriodicWithState(null, period, action); }; /** * Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be scheduled using window.setInterval for the base implementation. * @param {Mixed} state Initial state passed to the action upon the first iteration. * @param {Number} period Period for running the work periodically. * @param {Function} action Action to be executed, potentially updating the state. * @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort). */ Scheduler.prototype.schedulePeriodicWithState = function(state, period, action) { if (typeof root.setInterval === 'undefined') { throw new NotSupportedError(); } period = normalizeTime(period); var s = state, id = root.setInterval(function () { s = action(s); }, period); return disposableCreate(function () { root.clearInterval(id); }); }; }(Scheduler.prototype)); (function (schedulerProto) { /** * Returns a scheduler that wraps the original scheduler, adding exception handling for scheduled actions. * @param {Function} handler Handler that's run if an exception is caught. The exception will be rethrown if the handler returns false. * @returns {Scheduler} Wrapper around the original scheduler, enforcing exception handling. */ schedulerProto.catchError = schedulerProto['catch'] = function (handler) { return new CatchScheduler(this, handler); }; }(Scheduler.prototype)); var SchedulePeriodicRecursive = Rx.internals.SchedulePeriodicRecursive = (function () { function tick(command, recurse) { recurse(0, this._period); try { this._state = this._action(this._state); } catch (e) { this._cancel.dispose(); throw e; } } function SchedulePeriodicRecursive(scheduler, state, period, action) { this._scheduler = scheduler; this._state = state; this._period = period; this._action = action; } SchedulePeriodicRecursive.prototype.start = function () { var d = new SingleAssignmentDisposable(); this._cancel = d; d.setDisposable(this._scheduler.scheduleRecursiveWithRelativeAndState(0, this._period, tick.bind(this))); return d; }; return SchedulePeriodicRecursive; }()); /** Gets a scheduler that schedules work immediately on the current thread. */ var immediateScheduler = Scheduler.immediate = (function () { function scheduleNow(state, action) { return action(this, state); } return new Scheduler(defaultNow, scheduleNow, notSupported, notSupported); }()); /** * Gets a scheduler that schedules work as soon as possible on the current thread. */ var currentThreadScheduler = Scheduler.currentThread = (function () { var queue; function runTrampoline () { while (queue.length > 0) { var item = queue.dequeue(); !item.isCancelled() && item.invoke(); } } function scheduleNow(state, action) { var si = new ScheduledItem(this, state, action, this.now()); if (!queue) { queue = new PriorityQueue(4); queue.enqueue(si); var result = tryCatch(runTrampoline)(); queue = null; if (result === errorObj) { return thrower(result.e); } } else { queue.enqueue(si); } return si.disposable; } var currentScheduler = new Scheduler(defaultNow, scheduleNow, notSupported, notSupported); currentScheduler.scheduleRequired = function () { return !queue; }; return currentScheduler; }()); var scheduleMethod, clearMethod; var localTimer = (function () { var localSetTimeout, localClearTimeout = noop; if (!!root.setTimeout) { localSetTimeout = root.setTimeout; localClearTimeout = root.clearTimeout; } else if (!!root.WScript) { localSetTimeout = function (fn, time) { root.WScript.Sleep(time); fn(); }; } else { throw new NotSupportedError(); } return { setTimeout: localSetTimeout, clearTimeout: localClearTimeout }; }()); var localSetTimeout = localTimer.setTimeout, localClearTimeout = localTimer.clearTimeout; (function () { var nextHandle = 1, tasksByHandle = {}, currentlyRunning = false; clearMethod = function (handle) { delete tasksByHandle[handle]; }; function runTask(handle) { if (currentlyRunning) { localSetTimeout(function () { runTask(handle) }, 0); } else { var task = tasksByHandle[handle]; if (task) { currentlyRunning = true; var result = tryCatch(task)(); clearMethod(handle); currentlyRunning = false; if (result === errorObj) { return thrower(result.e); } } } } var reNative = RegExp('^' + String(toString) .replace(/[.*+?^${}()|[\]\\]/g, '\\$&') .replace(/toString| for [^\]]+/g, '.*?') + '$' ); var setImmediate = typeof (setImmediate = freeGlobal && moduleExports && freeGlobal.setImmediate) == 'function' && !reNative.test(setImmediate) && setImmediate; function postMessageSupported () { // Ensure not in a worker if (!root.postMessage || root.importScripts) { return false; } var isAsync = false, oldHandler = root.onmessage; // Test for async root.onmessage = function () { isAsync = true; }; root.postMessage('', '*'); root.onmessage = oldHandler; return isAsync; } // Use in order, setImmediate, nextTick, postMessage, MessageChannel, script readystatechanged, setTimeout if (isFunction(setImmediate)) { scheduleMethod = function (action) { var id = nextHandle++; tasksByHandle[id] = action; setImmediate(function () { runTask(id); }); return id; }; } else if (typeof process !== 'undefined' && {}.toString.call(process) === '[object process]') { scheduleMethod = function (action) { var id = nextHandle++; tasksByHandle[id] = action; process.nextTick(function () { runTask(id); }); return id; }; } else if (postMessageSupported()) { var MSG_PREFIX = 'ms.rx.schedule' + Math.random(); function onGlobalPostMessage(event) { // Only if we're a match to avoid any other global events if (typeof event.data === 'string' && event.data.substring(0, MSG_PREFIX.length) === MSG_PREFIX) { runTask(event.data.substring(MSG_PREFIX.length)); } } if (root.addEventListener) { root.addEventListener('message', onGlobalPostMessage, false); } else if (root.attachEvent) { root.attachEvent('onmessage', onGlobalPostMessage); } else { root.onmessage = onGlobalPostMessage; } scheduleMethod = function (action) { var id = nextHandle++; tasksByHandle[id] = action; root.postMessage(MSG_PREFIX + currentId, '*'); return id; }; } else if (!!root.MessageChannel) { var channel = new root.MessageChannel(); channel.port1.onmessage = function (e) { runTask(e.data); }; scheduleMethod = function (action) { var id = nextHandle++; tasksByHandle[id] = action; channel.port2.postMessage(id); return id; }; } else if ('document' in root && 'onreadystatechange' in root.document.createElement('script')) { scheduleMethod = function (action) { var scriptElement = root.document.createElement('script'); var id = nextHandle++; tasksByHandle[id] = action; scriptElement.onreadystatechange = function () { runTask(id); scriptElement.onreadystatechange = null; scriptElement.parentNode.removeChild(scriptElement); scriptElement = null; }; root.document.documentElement.appendChild(scriptElement); return id; }; } else { scheduleMethod = function (action) { var id = nextHandle++; tasksByHandle[id] = action; localSetTimeout(function () { runTask(id); }, 0); return id; }; } }()); /** * Gets a scheduler that schedules work via a timed callback based upon platform. */ var timeoutScheduler = Scheduler.timeout = Scheduler['default'] = (function () { function scheduleNow(state, action) { var scheduler = this, disposable = new SingleAssignmentDisposable(); var id = scheduleMethod(function () { !disposable.isDisposed && disposable.setDisposable(action(scheduler, state)); }); return new CompositeDisposable(disposable, disposableCreate(function () { clearMethod(id); })); } function scheduleRelative(state, dueTime, action) { var scheduler = this, dt = Scheduler.normalize(dueTime), disposable = new SingleAssignmentDisposable(); if (dt === 0) { return scheduler.scheduleWithState(state, action); } var id = localSetTimeout(function () { !disposable.isDisposed && disposable.setDisposable(action(scheduler, state)); }, dt); return new CompositeDisposable(disposable, disposableCreate(function () { localClearTimeout(id); })); } function scheduleAbsolute(state, dueTime, action) { return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action); } return new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute); })(); var CatchScheduler = (function (__super__) { function scheduleNow(state, action) { return this._scheduler.scheduleWithState(state, this._wrap(action)); } function scheduleRelative(state, dueTime, action) { return this._scheduler.scheduleWithRelativeAndState(state, dueTime, this._wrap(action)); } function scheduleAbsolute(state, dueTime, action) { return this._scheduler.scheduleWithAbsoluteAndState(state, dueTime, this._wrap(action)); } inherits(CatchScheduler, __super__); function CatchScheduler(scheduler, handler) { this._scheduler = scheduler; this._handler = handler; this._recursiveOriginal = null; this._recursiveWrapper = null; __super__.call(this, this._scheduler.now.bind(this._scheduler), scheduleNow, scheduleRelative, scheduleAbsolute); } CatchScheduler.prototype._clone = function (scheduler) { return new CatchScheduler(scheduler, this._handler); }; CatchScheduler.prototype._wrap = function (action) { var parent = this; return function (self, state) { try { return action(parent._getRecursiveWrapper(self), state); } catch (e) { if (!parent._handler(e)) { throw e; } return disposableEmpty; } }; }; CatchScheduler.prototype._getRecursiveWrapper = function (scheduler) { if (this._recursiveOriginal !== scheduler) { this._recursiveOriginal = scheduler; var wrapper = this._clone(scheduler); wrapper._recursiveOriginal = scheduler; wrapper._recursiveWrapper = wrapper; this._recursiveWrapper = wrapper; } return this._recursiveWrapper; }; CatchScheduler.prototype.schedulePeriodicWithState = function (state, period, action) { var self = this, failed = false, d = new SingleAssignmentDisposable(); d.setDisposable(this._scheduler.schedulePeriodicWithState(state, period, function (state1) { if (failed) { return null; } try { return action(state1); } catch (e) { failed = true; if (!self._handler(e)) { throw e; } d.dispose(); return null; } })); return d; }; return CatchScheduler; }(Scheduler)); /** * Represents a notification to an observer. */ var Notification = Rx.Notification = (function () { function Notification(kind, value, exception, accept, acceptObservable, toString) { this.kind = kind; this.value = value; this.exception = exception; this._accept = accept; this._acceptObservable = acceptObservable; this.toString = toString; } /** * Invokes the delegate corresponding to the notification or the observer's method corresponding to the notification and returns the produced result. * * @memberOf Notification * @param {Any} observerOrOnNext Delegate to invoke for an OnNext notification or Observer to invoke the notification on.. * @param {Function} onError Delegate to invoke for an OnError notification. * @param {Function} onCompleted Delegate to invoke for an OnCompleted notification. * @returns {Any} Result produced by the observation. */ Notification.prototype.accept = function (observerOrOnNext, onError, onCompleted) { return observerOrOnNext && typeof observerOrOnNext === 'object' ? this._acceptObservable(observerOrOnNext) : this._accept(observerOrOnNext, onError, onCompleted); }; /** * Returns an observable sequence with a single notification. * * @memberOf Notifications * @param {Scheduler} [scheduler] Scheduler to send out the notification calls on. * @returns {Observable} The observable sequence that surfaces the behavior of the notification upon subscription. */ Notification.prototype.toObservable = function (scheduler) { var self = this; isScheduler(scheduler) || (scheduler = immediateScheduler); return new AnonymousObservable(function (observer) { return scheduler.scheduleWithState(self, function (_, notification) { notification._acceptObservable(observer); notification.kind === 'N' && observer.onCompleted(); }); }); }; return Notification; })(); /** * Creates an object that represents an OnNext notification to an observer. * @param {Any} value The value contained in the notification. * @returns {Notification} The OnNext notification containing the value. */ var notificationCreateOnNext = Notification.createOnNext = (function () { function _accept(onNext) { return onNext(this.value); } function _acceptObservable(observer) { return observer.onNext(this.value); } function toString() { return 'OnNext(' + this.value + ')'; } return function (value) { return new Notification('N', value, null, _accept, _acceptObservable, toString); }; }()); /** * Creates an object that represents an OnError notification to an observer. * @param {Any} error The exception contained in the notification. * @returns {Notification} The OnError notification containing the exception. */ var notificationCreateOnError = Notification.createOnError = (function () { function _accept (onNext, onError) { return onError(this.exception); } function _acceptObservable(observer) { return observer.onError(this.exception); } function toString () { return 'OnError(' + this.exception + ')'; } return function (e) { return new Notification('E', null, e, _accept, _acceptObservable, toString); }; }()); /** * Creates an object that represents an OnCompleted notification to an observer. * @returns {Notification} The OnCompleted notification. */ var notificationCreateOnCompleted = Notification.createOnCompleted = (function () { function _accept (onNext, onError, onCompleted) { return onCompleted(); } function _acceptObservable(observer) { return observer.onCompleted(); } function toString () { return 'OnCompleted()'; } return function () { return new Notification('C', null, null, _accept, _acceptObservable, toString); }; }()); /** * Supports push-style iteration over an observable sequence. */ var Observer = Rx.Observer = function () { }; /** * Creates a notification callback from an observer. * @returns The action that forwards its input notification to the underlying observer. */ Observer.prototype.toNotifier = function () { var observer = this; return function (n) { return n.accept(observer); }; }; /** * Hides the identity of an observer. * @returns An observer that hides the identity of the specified observer. */ Observer.prototype.asObserver = function () { return new AnonymousObserver(this.onNext.bind(this), this.onError.bind(this), this.onCompleted.bind(this)); }; /** * Checks access to the observer for grammar violations. This includes checking for multiple OnError or OnCompleted calls, as well as reentrancy in any of the observer methods. * If a violation is detected, an Error is thrown from the offending observer method call. * @returns An observer that checks callbacks invocations against the observer grammar and, if the checks pass, forwards those to the specified observer. */ Observer.prototype.checked = function () { return new CheckedObserver(this); }; /** * Creates an observer from the specified OnNext, along with optional OnError, and OnCompleted actions. * @param {Function} [onNext] Observer's OnNext action implementation. * @param {Function} [onError] Observer's OnError action implementation. * @param {Function} [onCompleted] Observer's OnCompleted action implementation. * @returns {Observer} The observer object implemented using the given actions. */ var observerCreate = Observer.create = function (onNext, onError, onCompleted) { onNext || (onNext = noop); onError || (onError = defaultError); onCompleted || (onCompleted = noop); return new AnonymousObserver(onNext, onError, onCompleted); }; /** * Creates an observer from a notification callback. * * @static * @memberOf Observer * @param {Function} handler Action that handles a notification. * @returns The observer object that invokes the specified handler using a notification corresponding to each message it receives. */ Observer.fromNotifier = function (handler, thisArg) { return new AnonymousObserver(function (x) { return handler.call(thisArg, notificationCreateOnNext(x)); }, function (e) { return handler.call(thisArg, notificationCreateOnError(e)); }, function () { return handler.call(thisArg, notificationCreateOnCompleted()); }); }; /** * Schedules the invocation of observer methods on the given scheduler. * @param {Scheduler} scheduler Scheduler to schedule observer messages on. * @returns {Observer} Observer whose messages are scheduled on the given scheduler. */ Observer.prototype.notifyOn = function (scheduler) { return new ObserveOnObserver(scheduler, this); }; Observer.prototype.makeSafe = function(disposable) { return new AnonymousSafeObserver(this._onNext, this._onError, this._onCompleted, disposable); }; /** * Abstract base class for implementations of the Observer class. * This base class enforces the grammar of observers where OnError and OnCompleted are terminal messages. */ var AbstractObserver = Rx.internals.AbstractObserver = (function (__super__) { inherits(AbstractObserver, __super__); /** * Creates a new observer in a non-stopped state. */ function AbstractObserver() { this.isStopped = false; __super__.call(this); } // Must be implemented by other observers AbstractObserver.prototype.next = notImplemented; AbstractObserver.prototype.error = notImplemented; AbstractObserver.prototype.completed = notImplemented; /** * Notifies the observer of a new element in the sequence. * @param {Any} value Next element in the sequence. */ AbstractObserver.prototype.onNext = function (value) { if (!this.isStopped) { this.next(value); } }; /** * Notifies the observer that an exception has occurred. * @param {Any} error The error that has occurred. */ AbstractObserver.prototype.onError = function (error) { if (!this.isStopped) { this.isStopped = true; this.error(error); } }; /** * Notifies the observer of the end of the sequence. */ AbstractObserver.prototype.onCompleted = function () { if (!this.isStopped) { this.isStopped = true; this.completed(); } }; /** * Disposes the observer, causing it to transition to the stopped state. */ AbstractObserver.prototype.dispose = function () { this.isStopped = true; }; AbstractObserver.prototype.fail = function (e) { if (!this.isStopped) { this.isStopped = true; this.error(e); return true; } return false; }; return AbstractObserver; }(Observer)); /** * Class to create an Observer instance from delegate-based implementations of the on* methods. */ var AnonymousObserver = Rx.AnonymousObserver = (function (__super__) { inherits(AnonymousObserver, __super__); /** * Creates an observer from the specified OnNext, OnError, and OnCompleted actions. * @param {Any} onNext Observer's OnNext action implementation. * @param {Any} onError Observer's OnError action implementation. * @param {Any} onCompleted Observer's OnCompleted action implementation. */ function AnonymousObserver(onNext, onError, onCompleted) { __super__.call(this); this._onNext = onNext; this._onError = onError; this._onCompleted = onCompleted; } /** * Calls the onNext action. * @param {Any} value Next element in the sequence. */ AnonymousObserver.prototype.next = function (value) { this._onNext(value); }; /** * Calls the onError action. * @param {Any} error The error that has occurred. */ AnonymousObserver.prototype.error = function (error) { this._onError(error); }; /** * Calls the onCompleted action. */ AnonymousObserver.prototype.completed = function () { this._onCompleted(); }; return AnonymousObserver; }(AbstractObserver)); var CheckedObserver = (function (__super__) { inherits(CheckedObserver, __super__); function CheckedObserver(observer) { __super__.call(this); this._observer = observer; this._state = 0; // 0 - idle, 1 - busy, 2 - done } var CheckedObserverPrototype = CheckedObserver.prototype; CheckedObserverPrototype.onNext = function (value) { this.checkAccess(); var res = tryCatch(this._observer.onNext).call(this._observer, value); this._state = 0; res === errorObj && thrower(res.e); }; CheckedObserverPrototype.onError = function (err) { this.checkAccess(); var res = tryCatch(this._observer.onError).call(this._observer, err); this._state = 2; res === errorObj && thrower(res.e); }; CheckedObserverPrototype.onCompleted = function () { this.checkAccess(); var res = tryCatch(this._observer.onCompleted).call(this._observer); this._state = 2; res === errorObj && thrower(res.e); }; CheckedObserverPrototype.checkAccess = function () { if (this._state === 1) { throw new Error('Re-entrancy detected'); } if (this._state === 2) { throw new Error('Observer completed'); } if (this._state === 0) { this._state = 1; } }; return CheckedObserver; }(Observer)); var ScheduledObserver = Rx.internals.ScheduledObserver = (function (__super__) { inherits(ScheduledObserver, __super__); function ScheduledObserver(scheduler, observer) { __super__.call(this); this.scheduler = scheduler; this.observer = observer; this.isAcquired = false; this.hasFaulted = false; this.queue = []; this.disposable = new SerialDisposable(); } ScheduledObserver.prototype.next = function (value) { var self = this; this.queue.push(function () { self.observer.onNext(value); }); }; ScheduledObserver.prototype.error = function (e) { var self = this; this.queue.push(function () { self.observer.onError(e); }); }; ScheduledObserver.prototype.completed = function () { var self = this; this.queue.push(function () { self.observer.onCompleted(); }); }; ScheduledObserver.prototype.ensureActive = function () { var isOwner = false, parent = this; if (!this.hasFaulted && this.queue.length > 0) { isOwner = !this.isAcquired; this.isAcquired = true; } if (isOwner) { this.disposable.setDisposable(this.scheduler.scheduleRecursive(function (self) { var work; if (parent.queue.length > 0) { work = parent.queue.shift(); } else { parent.isAcquired = false; return; } try { work(); } catch (ex) { parent.queue = []; parent.hasFaulted = true; throw ex; } self(); })); } }; ScheduledObserver.prototype.dispose = function () { __super__.prototype.dispose.call(this); this.disposable.dispose(); }; return ScheduledObserver; }(AbstractObserver)); var ObserveOnObserver = (function (__super__) { inherits(ObserveOnObserver, __super__); function ObserveOnObserver(scheduler, observer, cancel) { __super__.call(this, scheduler, observer); this._cancel = cancel; } ObserveOnObserver.prototype.next = function (value) { __super__.prototype.next.call(this, value); this.ensureActive(); }; ObserveOnObserver.prototype.error = function (e) { __super__.prototype.error.call(this, e); this.ensureActive(); }; ObserveOnObserver.prototype.completed = function () { __super__.prototype.completed.call(this); this.ensureActive(); }; ObserveOnObserver.prototype.dispose = function () { __super__.prototype.dispose.call(this); this._cancel && this._cancel.dispose(); this._cancel = null; }; return ObserveOnObserver; })(ScheduledObserver); var observableProto; /** * Represents a push-style collection. */ var Observable = Rx.Observable = (function () { function Observable(subscribe) { if (Rx.config.longStackSupport && hasStacks) { try { throw new Error(); } catch (e) { this.stack = e.stack.substring(e.stack.indexOf("\n") + 1); } var self = this; this._subscribe = function (observer) { var oldOnError = observer.onError.bind(observer); observer.onError = function (err) { makeStackTraceLong(err, self); oldOnError(err); }; return subscribe.call(self, observer); }; } else { this._subscribe = subscribe; } } observableProto = Observable.prototype; /** * Subscribes an observer to the observable sequence. * @param {Mixed} [observerOrOnNext] The object that is to receive notifications or an action to invoke for each element in the observable sequence. * @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence. * @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence. * @returns {Diposable} A disposable handling the subscriptions and unsubscriptions. */ observableProto.subscribe = observableProto.forEach = function (observerOrOnNext, onError, onCompleted) { return this._subscribe(typeof observerOrOnNext === 'object' ? observerOrOnNext : observerCreate(observerOrOnNext, onError, onCompleted)); }; /** * Subscribes to the next value in the sequence with an optional "this" argument. * @param {Function} onNext The function to invoke on each element in the observable sequence. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Disposable} A disposable handling the subscriptions and unsubscriptions. */ observableProto.subscribeOnNext = function (onNext, thisArg) { return this._subscribe(observerCreate(typeof thisArg !== 'undefined' ? function(x) { onNext.call(thisArg, x); } : onNext)); }; /** * Subscribes to an exceptional condition in the sequence with an optional "this" argument. * @param {Function} onError The function to invoke upon exceptional termination of the observable sequence. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Disposable} A disposable handling the subscriptions and unsubscriptions. */ observableProto.subscribeOnError = function (onError, thisArg) { return this._subscribe(observerCreate(null, typeof thisArg !== 'undefined' ? function(e) { onError.call(thisArg, e); } : onError)); }; /** * Subscribes to the next value in the sequence with an optional "this" argument. * @param {Function} onCompleted The function to invoke upon graceful termination of the observable sequence. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Disposable} A disposable handling the subscriptions and unsubscriptions. */ observableProto.subscribeOnCompleted = function (onCompleted, thisArg) { return this._subscribe(observerCreate(null, null, typeof thisArg !== 'undefined' ? function() { onCompleted.call(thisArg); } : onCompleted)); }; return Observable; })(); var ObservableBase = Rx.ObservableBase = (function (__super__) { inherits(ObservableBase, __super__); function fixSubscriber(subscriber) { return subscriber && isFunction(subscriber.dispose) ? subscriber : isFunction(subscriber) ? disposableCreate(subscriber) : disposableEmpty; } function setDisposable(s, state) { var ado = state[0], self = state[1]; var sub = tryCatch(self.subscribeCore).call(self, ado); if (sub === errorObj) { if(!ado.fail(errorObj.e)) { return thrower(errorObj.e); } } ado.setDisposable(fixSubscriber(sub)); } function subscribe(observer) { var ado = new AutoDetachObserver(observer), state = [ado, this]; if (currentThreadScheduler.scheduleRequired()) { currentThreadScheduler.scheduleWithState(state, setDisposable); } else { setDisposable(null, state); } return ado; } function ObservableBase() { __super__.call(this, subscribe); } ObservableBase.prototype.subscribeCore = notImplemented; return ObservableBase; }(Observable)); var Enumerable = Rx.internals.Enumerable = function () { }; var ConcatEnumerableObservable = (function(__super__) { inherits(ConcatEnumerableObservable, __super__); function ConcatEnumerableObservable(sources) { this.sources = sources; __super__.call(this); } ConcatEnumerableObservable.prototype.subscribeCore = function (o) { var isDisposed, subscription = new SerialDisposable(); var cancelable = immediateScheduler.scheduleRecursiveWithState(this.sources[$iterator$](), function (e, self) { if (isDisposed) { return; } var currentItem = tryCatch(e.next).call(e); if (currentItem === errorObj) { return o.onError(currentItem.e); } if (currentItem.done) { return o.onCompleted(); } // Check if promise var currentValue = currentItem.value; isPromise(currentValue) && (currentValue = observableFromPromise(currentValue)); var d = new SingleAssignmentDisposable(); subscription.setDisposable(d); d.setDisposable(currentValue.subscribe(new InnerObserver(o, self, e))); }); return new CompositeDisposable(subscription, cancelable, disposableCreate(function () { isDisposed = true; })); }; function InnerObserver(o, s, e) { this.o = o; this.s = s; this.e = e; this.isStopped = false; } InnerObserver.prototype.onNext = function (x) { if(!this.isStopped) { this.o.onNext(x); } }; InnerObserver.prototype.onError = function (err) { if (!this.isStopped) { this.isStopped = true; this.o.onError(err); } }; InnerObserver.prototype.onCompleted = function () { if (!this.isStopped) { this.isStopped = true; this.s(this.e); } }; InnerObserver.prototype.dispose = function () { this.isStopped = true; }; InnerObserver.prototype.fail = function (err) { if (!this.isStopped) { this.isStopped = true; this.o.onError(err); return true; } return false; }; return ConcatEnumerableObservable; }(ObservableBase)); Enumerable.prototype.concat = function () { return new ConcatEnumerableObservable(this); }; var CatchErrorObservable = (function(__super__) { inherits(CatchErrorObservable, __super__); function CatchErrorObservable(sources) { this.sources = sources; __super__.call(this); } CatchErrorObservable.prototype.subscribeCore = function (o) { var e = this.sources[$iterator$](); var isDisposed, subscription = new SerialDisposable(); var cancelable = immediateScheduler.scheduleRecursiveWithState(null, function (lastException, self) { if (isDisposed) { return; } var currentItem = tryCatch(e.next).call(e); if (currentItem === errorObj) { return o.onError(currentItem.e); } if (currentItem.done) { return lastException !== null ? o.onError(lastException) : o.onCompleted(); } // Check if promise var currentValue = currentItem.value; isPromise(currentValue) && (currentValue = observableFromPromise(currentValue)); var d = new SingleAssignmentDisposable(); subscription.setDisposable(d); d.setDisposable(currentValue.subscribe( function(x) { o.onNext(x); }, self, function() { o.onCompleted(); })); }); return new CompositeDisposable(subscription, cancelable, disposableCreate(function () { isDisposed = true; })); }; return CatchErrorObservable; }(ObservableBase)); Enumerable.prototype.catchError = function () { return new CatchErrorObservable(this); }; Enumerable.prototype.catchErrorWhen = function (notificationHandler) { var sources = this; return new AnonymousObservable(function (o) { var exceptions = new Subject(), notifier = new Subject(), handled = notificationHandler(exceptions), notificationDisposable = handled.subscribe(notifier); var e = sources[$iterator$](); var isDisposed, lastException, subscription = new SerialDisposable(); var cancelable = immediateScheduler.scheduleRecursive(function (self) { if (isDisposed) { return; } var currentItem = tryCatch(e.next).call(e); if (currentItem === errorObj) { return o.onError(currentItem.e); } if (currentItem.done) { if (lastException) { o.onError(lastException); } else { o.onCompleted(); } return; } // Check if promise var currentValue = currentItem.value; isPromise(currentValue) && (currentValue = observableFromPromise(currentValue)); var outer = new SingleAssignmentDisposable(); var inner = new SingleAssignmentDisposable(); subscription.setDisposable(new CompositeDisposable(inner, outer)); outer.setDisposable(currentValue.subscribe( function(x) { o.onNext(x); }, function (exn) { inner.setDisposable(notifier.subscribe(self, function(ex) { o.onError(ex); }, function() { o.onCompleted(); })); exceptions.onNext(exn); }, function() { o.onCompleted(); })); }); return new CompositeDisposable(notificationDisposable, subscription, cancelable, disposableCreate(function () { isDisposed = true; })); }); }; var RepeatEnumerable = (function (__super__) { inherits(RepeatEnumerable, __super__); function RepeatEnumerable(v, c) { this.v = v; this.c = c == null ? -1 : c; } RepeatEnumerable.prototype[$iterator$] = function () { return new RepeatEnumerator(this); }; function RepeatEnumerator(p) { this.v = p.v; this.l = p.c; } RepeatEnumerator.prototype.next = function () { if (this.l === 0) { return doneEnumerator; } if (this.l > 0) { this.l--; } return { done: false, value: this.v }; }; return RepeatEnumerable; }(Enumerable)); var enumerableRepeat = Enumerable.repeat = function (value, repeatCount) { return new RepeatEnumerable(value, repeatCount); }; var OfEnumerable = (function(__super__) { inherits(OfEnumerable, __super__); function OfEnumerable(s, fn, thisArg) { this.s = s; this.fn = fn ? bindCallback(fn, thisArg, 3) : null; } OfEnumerable.prototype[$iterator$] = function () { return new OfEnumerator(this); }; function OfEnumerator(p) { this.i = -1; this.s = p.s; this.l = this.s.length; this.fn = p.fn; } OfEnumerator.prototype.next = function () { return ++this.i < this.l ? { done: false, value: !this.fn ? this.s[this.i] : this.fn(this.s[this.i], this.i, this.s) } : doneEnumerator; }; return OfEnumerable; }(Enumerable)); var enumerableOf = Enumerable.of = function (source, selector, thisArg) { return new OfEnumerable(source, selector, thisArg); }; /** * Wraps the source sequence in order to run its observer callbacks on the specified scheduler. * * This only invokes observer callbacks on a scheduler. In case the subscription and/or unsubscription actions have side-effects * that require to be run on a scheduler, use subscribeOn. * * @param {Scheduler} scheduler Scheduler to notify observers on. * @returns {Observable} The source sequence whose observations happen on the specified scheduler. */ observableProto.observeOn = function (scheduler) { var source = this; return new AnonymousObservable(function (observer) { return source.subscribe(new ObserveOnObserver(scheduler, observer)); }, source); }; /** * Wraps the source sequence in order to run its subscription and unsubscription logic on the specified scheduler. This operation is not commonly used; * see the remarks section for more information on the distinction between subscribeOn and observeOn. * This only performs the side-effects of subscription and unsubscription on the specified scheduler. In order to invoke observer * callbacks on a scheduler, use observeOn. * @param {Scheduler} scheduler Scheduler to perform subscription and unsubscription actions on. * @returns {Observable} The source sequence whose subscriptions and unsubscriptions happen on the specified scheduler. */ observableProto.subscribeOn = function (scheduler) { var source = this; return new AnonymousObservable(function (observer) { var m = new SingleAssignmentDisposable(), d = new SerialDisposable(); d.setDisposable(m); m.setDisposable(scheduler.schedule(function () { d.setDisposable(new ScheduledDisposable(scheduler, source.subscribe(observer))); })); return d; }, source); }; var FromPromiseObservable = (function(__super__) { inherits(FromPromiseObservable, __super__); function FromPromiseObservable(p) { this.p = p; __super__.call(this); } FromPromiseObservable.prototype.subscribeCore = function(o) { this.p.then(function (data) { o.onNext(data); o.onCompleted(); }, function (err) { o.onError(err); }); return disposableEmpty; }; return FromPromiseObservable; }(ObservableBase)); /** * Converts a Promise to an Observable sequence * @param {Promise} An ES6 Compliant promise. * @returns {Observable} An Observable sequence which wraps the existing promise success and failure. */ var observableFromPromise = Observable.fromPromise = function (promise) { return new FromPromiseObservable(promise); }; /* * Converts an existing observable sequence to an ES6 Compatible Promise * @example * var promise = Rx.Observable.return(42).toPromise(RSVP.Promise); * * // With config * Rx.config.Promise = RSVP.Promise; * var promise = Rx.Observable.return(42).toPromise(); * @param {Function} [promiseCtor] The constructor of the promise. If not provided, it looks for it in Rx.config.Promise. * @returns {Promise} An ES6 compatible promise with the last value from the observable sequence. */ observableProto.toPromise = function (promiseCtor) { promiseCtor || (promiseCtor = Rx.config.Promise); if (!promiseCtor) { throw new NotSupportedError('Promise type not provided nor in Rx.config.Promise'); } var source = this; return new promiseCtor(function (resolve, reject) { // No cancellation can be done var value, hasValue = false; source.subscribe(function (v) { value = v; hasValue = true; }, reject, function () { hasValue && resolve(value); }); }); }; var ToArrayObservable = (function(__super__) { inherits(ToArrayObservable, __super__); function ToArrayObservable(source) { this.source = source; __super__.call(this); } ToArrayObservable.prototype.subscribeCore = function(o) { return this.source.subscribe(new InnerObserver(o)); }; function InnerObserver(o) { this.o = o; this.a = []; this.isStopped = false; } InnerObserver.prototype.onNext = function (x) { if(!this.isStopped) { this.a.push(x); } }; InnerObserver.prototype.onError = function (e) { if (!this.isStopped) { this.isStopped = true; this.o.onError(e); } }; InnerObserver.prototype.onCompleted = function () { if (!this.isStopped) { this.isStopped = true; this.o.onNext(this.a); this.o.onCompleted(); } }; InnerObserver.prototype.dispose = function () { this.isStopped = true; } InnerObserver.prototype.fail = function (e) { if (!this.isStopped) { this.isStopped = true; this.o.onError(e); return true; } return false; }; return ToArrayObservable; }(ObservableBase)); /** * Creates an array from an observable sequence. * @returns {Observable} An observable sequence containing a single element with a list containing all the elements of the source sequence. */ observableProto.toArray = function () { return new ToArrayObservable(this); }; /** * Creates an observable sequence from a specified subscribe method implementation. * @example * var res = Rx.Observable.create(function (observer) { return function () { } ); * var res = Rx.Observable.create(function (observer) { return Rx.Disposable.empty; } ); * var res = Rx.Observable.create(function (observer) { } ); * @param {Function} subscribe Implementation of the resulting observable sequence's subscribe method, returning a function that will be wrapped in a Disposable. * @returns {Observable} The observable sequence with the specified implementation for the Subscribe method. */ Observable.create = Observable.createWithDisposable = function (subscribe, parent) { return new AnonymousObservable(subscribe, parent); }; /** * Returns an observable sequence that invokes the specified factory function whenever a new observer subscribes. * * @example * var res = Rx.Observable.defer(function () { return Rx.Observable.fromArray([1,2,3]); }); * @param {Function} observableFactory Observable factory function to invoke for each observer that subscribes to the resulting sequence or Promise. * @returns {Observable} An observable sequence whose observers trigger an invocation of the given observable factory function. */ var observableDefer = Observable.defer = function (observableFactory) { return new AnonymousObservable(function (observer) { var result; try { result = observableFactory(); } catch (e) { return observableThrow(e).subscribe(observer); } isPromise(result) && (result = observableFromPromise(result)); return result.subscribe(observer); }); }; var EmptyObservable = (function(__super__) { inherits(EmptyObservable, __super__); function EmptyObservable(scheduler) { this.scheduler = scheduler; __super__.call(this); } EmptyObservable.prototype.subscribeCore = function (observer) { var sink = new EmptySink(observer, this); return sink.run(); }; function EmptySink(observer, parent) { this.observer = observer; this.parent = parent; } function scheduleItem(s, state) { state.onCompleted(); } EmptySink.prototype.run = function () { return this.parent.scheduler.scheduleWithState(this.observer, scheduleItem); }; return EmptyObservable; }(ObservableBase)); /** * Returns an empty observable sequence, using the specified scheduler to send out the single OnCompleted message. * * @example * var res = Rx.Observable.empty(); * var res = Rx.Observable.empty(Rx.Scheduler.timeout); * @param {Scheduler} [scheduler] Scheduler to send the termination call on. * @returns {Observable} An observable sequence with no elements. */ var observableEmpty = Observable.empty = function (scheduler) { isScheduler(scheduler) || (scheduler = immediateScheduler); return new EmptyObservable(scheduler); }; var FromObservable = (function(__super__) { inherits(FromObservable, __super__); function FromObservable(iterable, mapper, scheduler) { this.iterable = iterable; this.mapper = mapper; this.scheduler = scheduler; __super__.call(this); } FromObservable.prototype.subscribeCore = function (observer) { var sink = new FromSink(observer, this); return sink.run(); }; return FromObservable; }(ObservableBase)); var FromSink = (function () { function FromSink(observer, parent) { this.observer = observer; this.parent = parent; } FromSink.prototype.run = function () { var list = Object(this.parent.iterable), it = getIterable(list), observer = this.observer, mapper = this.parent.mapper; function loopRecursive(i, recurse) { try { var next = it.next(); } catch (e) { return observer.onError(e); } if (next.done) { return observer.onCompleted(); } var result = next.value; if (mapper) { try { result = mapper(result, i); } catch (e) { return observer.onError(e); } } observer.onNext(result); recurse(i + 1); } return this.parent.scheduler.scheduleRecursiveWithState(0, loopRecursive); }; return FromSink; }()); var maxSafeInteger = Math.pow(2, 53) - 1; function StringIterable(str) { this._s = s; } StringIterable.prototype[$iterator$] = function () { return new StringIterator(this._s); }; function StringIterator(str) { this._s = s; this._l = s.length; this._i = 0; } StringIterator.prototype[$iterator$] = function () { return this; }; StringIterator.prototype.next = function () { return this._i < this._l ? { done: false, value: this._s.charAt(this._i++) } : doneEnumerator; }; function ArrayIterable(a) { this._a = a; } ArrayIterable.prototype[$iterator$] = function () { return new ArrayIterator(this._a); }; function ArrayIterator(a) { this._a = a; this._l = toLength(a); this._i = 0; } ArrayIterator.prototype[$iterator$] = function () { return this; }; ArrayIterator.prototype.next = function () { return this._i < this._l ? { done: false, value: this._a[this._i++] } : doneEnumerator; }; function numberIsFinite(value) { return typeof value === 'number' && root.isFinite(value); } function isNan(n) { return n !== n; } function getIterable(o) { var i = o[$iterator$], it; if (!i && typeof o === 'string') { it = new StringIterable(o); return it[$iterator$](); } if (!i && o.length !== undefined) { it = new ArrayIterable(o); return it[$iterator$](); } if (!i) { throw new TypeError('Object is not iterable'); } return o[$iterator$](); } function sign(value) { var number = +value; if (number === 0) { return number; } if (isNaN(number)) { return number; } return number < 0 ? -1 : 1; } function toLength(o) { var len = +o.length; if (isNaN(len)) { return 0; } if (len === 0 || !numberIsFinite(len)) { return len; } len = sign(len) * Math.floor(Math.abs(len)); if (len <= 0) { return 0; } if (len > maxSafeInteger) { return maxSafeInteger; } return len; } /** * This method creates a new Observable sequence from an array-like or iterable object. * @param {Any} arrayLike An array-like or iterable object to convert to an Observable sequence. * @param {Function} [mapFn] Map function to call on every element of the array. * @param {Any} [thisArg] The context to use calling the mapFn if provided. * @param {Scheduler} [scheduler] Optional scheduler to use for scheduling. If not provided, defaults to Scheduler.currentThread. */ var observableFrom = Observable.from = function (iterable, mapFn, thisArg, scheduler) { if (iterable == null) { throw new Error('iterable cannot be null.') } if (mapFn && !isFunction(mapFn)) { throw new Error('mapFn when provided must be a function'); } if (mapFn) { var mapper = bindCallback(mapFn, thisArg, 2); } isScheduler(scheduler) || (scheduler = currentThreadScheduler); return new FromObservable(iterable, mapper, scheduler); } var FromArrayObservable = (function(__super__) { inherits(FromArrayObservable, __super__); function FromArrayObservable(args, scheduler) { this.args = args; this.scheduler = scheduler; __super__.call(this); } FromArrayObservable.prototype.subscribeCore = function (observer) { var sink = new FromArraySink(observer, this); return sink.run(); }; return FromArrayObservable; }(ObservableBase)); function FromArraySink(observer, parent) { this.observer = observer; this.parent = parent; } FromArraySink.prototype.run = function () { var observer = this.observer, args = this.parent.args, len = args.length; function loopRecursive(i, recurse) { if (i < len) { observer.onNext(args[i]); recurse(i + 1); } else { observer.onCompleted(); } } return this.parent.scheduler.scheduleRecursiveWithState(0, loopRecursive); }; /** * Converts an array to an observable sequence, using an optional scheduler to enumerate the array. * @deprecated use Observable.from or Observable.of * @param {Scheduler} [scheduler] Scheduler to run the enumeration of the input sequence on. * @returns {Observable} The observable sequence whose elements are pulled from the given enumerable sequence. */ var observableFromArray = Observable.fromArray = function (array, scheduler) { isScheduler(scheduler) || (scheduler = currentThreadScheduler); return new FromArrayObservable(array, scheduler) }; /** * Generates an observable sequence by running a state-driven loop producing the sequence's elements, using the specified scheduler to send out observer messages. * * @example * var res = Rx.Observable.generate(0, function (x) { return x < 10; }, function (x) { return x + 1; }, function (x) { return x; }); * var res = Rx.Observable.generate(0, function (x) { return x < 10; }, function (x) { return x + 1; }, function (x) { return x; }, Rx.Scheduler.timeout); * @param {Mixed} initialState Initial state. * @param {Function} condition Condition to terminate generation (upon returning false). * @param {Function} iterate Iteration step function. * @param {Function} resultSelector Selector function for results produced in the sequence. * @param {Scheduler} [scheduler] Scheduler on which to run the generator loop. If not provided, defaults to Scheduler.currentThread. * @returns {Observable} The generated sequence. */ Observable.generate = function (initialState, condition, iterate, resultSelector, scheduler) { isScheduler(scheduler) || (scheduler = currentThreadScheduler); return new AnonymousObservable(function (o) { var first = true; return scheduler.scheduleRecursiveWithState(initialState, function (state, self) { var hasResult, result; try { if (first) { first = false; } else { state = iterate(state); } hasResult = condition(state); hasResult && (result = resultSelector(state)); } catch (e) { return o.onError(e); } if (hasResult) { o.onNext(result); self(state); } else { o.onCompleted(); } }); }); }; function observableOf (scheduler, array) { isScheduler(scheduler) || (scheduler = currentThreadScheduler); return new FromArrayObservable(array, scheduler); } /** * This method creates a new Observable instance with a variable number of arguments, regardless of number or type of the arguments. * @returns {Observable} The observable sequence whose elements are pulled from the given arguments. */ Observable.of = function () { var len = arguments.length, args = new Array(len); for(var i = 0; i < len; i++) { args[i] = arguments[i]; } return new FromArrayObservable(args, currentThreadScheduler); }; /** * This method creates a new Observable instance with a variable number of arguments, regardless of number or type of the arguments. * @param {Scheduler} scheduler A scheduler to use for scheduling the arguments. * @returns {Observable} The observable sequence whose elements are pulled from the given arguments. */ Observable.ofWithScheduler = function (scheduler) { var len = arguments.length, args = new Array(len - 1); for(var i = 1; i < len; i++) { args[i - 1] = arguments[i]; } return new FromArrayObservable(args, scheduler); }; /** * Creates an Observable sequence from changes to an array using Array.observe. * @param {Array} array An array to observe changes. * @returns {Observable} An observable sequence containing changes to an array from Array.observe. */ Observable.ofArrayChanges = function(array) { if (!Array.isArray(array)) { throw new TypeError('Array.observe only accepts arrays.'); } if (typeof Array.observe !== 'function' && typeof Array.unobserve !== 'function') { throw new TypeError('Array.observe is not supported on your platform') } return new AnonymousObservable(function(observer) { function observerFn(changes) { for(var i = 0, len = changes.length; i < len; i++) { observer.onNext(changes[i]); } } Array.observe(array, observerFn); return function () { Array.unobserve(array, observerFn); }; }); }; /** * Creates an Observable sequence from changes to an object using Object.observe. * @param {Object} obj An object to observe changes. * @returns {Observable} An observable sequence containing changes to an object from Object.observe. */ Observable.ofObjectChanges = function(obj) { if (obj == null) { throw new TypeError('object must not be null or undefined.'); } if (typeof Object.observe !== 'function' && typeof Object.unobserve !== 'function') { throw new TypeError('Object.observe is not supported on your platform') } return new AnonymousObservable(function(observer) { function observerFn(changes) { for(var i = 0, len = changes.length; i < len; i++) { observer.onNext(changes[i]); } } Object.observe(obj, observerFn); return function () { Object.unobserve(obj, observerFn); }; }); }; var NeverObservable = (function(__super__) { inherits(NeverObservable, __super__); function NeverObservable() { __super__.call(this); } NeverObservable.prototype.subscribeCore = function (observer) { return disposableEmpty; }; return NeverObservable; }(ObservableBase)); /** * Returns a non-terminating observable sequence, which can be used to denote an infinite duration (e.g. when using reactive joins). * @returns {Observable} An observable sequence whose observers will never get called. */ var observableNever = Observable.never = function () { return new NeverObservable(); }; var PairsObservable = (function(__super__) { inherits(PairsObservable, __super__); function PairsObservable(obj, scheduler) { this.obj = obj; this.keys = Object.keys(obj); this.scheduler = scheduler; __super__.call(this); } PairsObservable.prototype.subscribeCore = function (observer) { var sink = new PairsSink(observer, this); return sink.run(); }; return PairsObservable; }(ObservableBase)); function PairsSink(observer, parent) { this.observer = observer; this.parent = parent; } PairsSink.prototype.run = function () { var observer = this.observer, obj = this.parent.obj, keys = this.parent.keys, len = keys.length; function loopRecursive(i, recurse) { if (i < len) { var key = keys[i]; observer.onNext([key, obj[key]]); recurse(i + 1); } else { observer.onCompleted(); } } return this.parent.scheduler.scheduleRecursiveWithState(0, loopRecursive); }; /** * Convert an object into an observable sequence of [key, value] pairs. * @param {Object} obj The object to inspect. * @param {Scheduler} [scheduler] Scheduler to run the enumeration of the input sequence on. * @returns {Observable} An observable sequence of [key, value] pairs from the object. */ Observable.pairs = function (obj, scheduler) { scheduler || (scheduler = currentThreadScheduler); return new PairsObservable(obj, scheduler); }; var RangeObservable = (function(__super__) { inherits(RangeObservable, __super__); function RangeObservable(start, count, scheduler) { this.start = start; this.rangeCount = count; this.scheduler = scheduler; __super__.call(this); } RangeObservable.prototype.subscribeCore = function (observer) { var sink = new RangeSink(observer, this); return sink.run(); }; return RangeObservable; }(ObservableBase)); var RangeSink = (function () { function RangeSink(observer, parent) { this.observer = observer; this.parent = parent; } RangeSink.prototype.run = function () { var start = this.parent.start, count = this.parent.rangeCount, observer = this.observer; function loopRecursive(i, recurse) { if (i < count) { observer.onNext(start + i); recurse(i + 1); } else { observer.onCompleted(); } } return this.parent.scheduler.scheduleRecursiveWithState(0, loopRecursive); }; return RangeSink; }()); /** * Generates an observable sequence of integral numbers within a specified range, using the specified scheduler to send out observer messages. * @param {Number} start The value of the first integer in the sequence. * @param {Number} count The number of sequential integers to generate. * @param {Scheduler} [scheduler] Scheduler to run the generator loop on. If not specified, defaults to Scheduler.currentThread. * @returns {Observable} An observable sequence that contains a range of sequential integral numbers. */ Observable.range = function (start, count, scheduler) { isScheduler(scheduler) || (scheduler = currentThreadScheduler); return new RangeObservable(start, count, scheduler); }; var RepeatObservable = (function(__super__) { inherits(RepeatObservable, __super__); function RepeatObservable(value, repeatCount, scheduler) { this.value = value; this.repeatCount = repeatCount == null ? -1 : repeatCount; this.scheduler = scheduler; __super__.call(this); } RepeatObservable.prototype.subscribeCore = function (observer) { var sink = new RepeatSink(observer, this); return sink.run(); }; return RepeatObservable; }(ObservableBase)); function RepeatSink(observer, parent) { this.observer = observer; this.parent = parent; } RepeatSink.prototype.run = function () { var observer = this.observer, value = this.parent.value; function loopRecursive(i, recurse) { if (i === -1 || i > 0) { observer.onNext(value); i > 0 && i--; } if (i === 0) { return observer.onCompleted(); } recurse(i); } return this.parent.scheduler.scheduleRecursiveWithState(this.parent.repeatCount, loopRecursive); }; /** * Generates an observable sequence that repeats the given element the specified number of times, using the specified scheduler to send out observer messages. * @param {Mixed} value Element to repeat. * @param {Number} repeatCount [Optiona] Number of times to repeat the element. If not specified, repeats indefinitely. * @param {Scheduler} scheduler Scheduler to run the producer loop on. If not specified, defaults to Scheduler.immediate. * @returns {Observable} An observable sequence that repeats the given element the specified number of times. */ Observable.repeat = function (value, repeatCount, scheduler) { isScheduler(scheduler) || (scheduler = currentThreadScheduler); return new RepeatObservable(value, repeatCount, scheduler); }; var JustObservable = (function(__super__) { inherits(JustObservable, __super__); function JustObservable(value, scheduler) { this.value = value; this.scheduler = scheduler; __super__.call(this); } JustObservable.prototype.subscribeCore = function (observer) { var sink = new JustSink(observer, this); return sink.run(); }; function JustSink(observer, parent) { this.observer = observer; this.parent = parent; } function scheduleItem(s, state) { var value = state[0], observer = state[1]; observer.onNext(value); observer.onCompleted(); } JustSink.prototype.run = function () { return this.parent.scheduler.scheduleWithState([this.parent.value, this.observer], scheduleItem); }; return JustObservable; }(ObservableBase)); /** * Returns an observable sequence that contains a single element, using the specified scheduler to send out observer messages. * There is an alias called 'just' or browsers <IE9. * @param {Mixed} value Single element in the resulting observable sequence. * @param {Scheduler} scheduler Scheduler to send the single element on. If not specified, defaults to Scheduler.immediate. * @returns {Observable} An observable sequence containing the single specified element. */ var observableReturn = Observable['return'] = Observable.just = Observable.returnValue = function (value, scheduler) { isScheduler(scheduler) || (scheduler = immediateScheduler); return new JustObservable(value, scheduler); }; var ThrowObservable = (function(__super__) { inherits(ThrowObservable, __super__); function ThrowObservable(error, scheduler) { this.error = error; this.scheduler = scheduler; __super__.call(this); } ThrowObservable.prototype.subscribeCore = function (o) { var sink = new ThrowSink(o, this); return sink.run(); }; function ThrowSink(o, p) { this.o = o; this.p = p; } function scheduleItem(s, state) { var e = state[0], o = state[1]; o.onError(e); } ThrowSink.prototype.run = function () { return this.p.scheduler.scheduleWithState([this.p.error, this.o], scheduleItem); }; return ThrowObservable; }(ObservableBase)); /** * Returns an observable sequence that terminates with an exception, using the specified scheduler to send out the single onError message. * There is an alias to this method called 'throwError' for browsers <IE9. * @param {Mixed} error An object used for the sequence's termination. * @param {Scheduler} scheduler Scheduler to send the exceptional termination call on. If not specified, defaults to Scheduler.immediate. * @returns {Observable} The observable sequence that terminates exceptionally with the specified exception object. */ var observableThrow = Observable['throw'] = Observable.throwError = Observable.throwException = function (error, scheduler) { isScheduler(scheduler) || (scheduler = immediateScheduler); return new ThrowObservable(error, scheduler); }; /** * Constructs an observable sequence that depends on a resource object, whose lifetime is tied to the resulting observable sequence's lifetime. * @param {Function} resourceFactory Factory function to obtain a resource object. * @param {Function} observableFactory Factory function to obtain an observable sequence that depends on the obtained resource. * @returns {Observable} An observable sequence whose lifetime controls the lifetime of the dependent resource object. */ Observable.using = function (resourceFactory, observableFactory) { return new AnonymousObservable(function (observer) { var disposable = disposableEmpty, resource, source; try { resource = resourceFactory(); resource && (disposable = resource); source = observableFactory(resource); } catch (exception) { return new CompositeDisposable(observableThrow(exception).subscribe(observer), disposable); } return new CompositeDisposable(source.subscribe(observer), disposable); }); }; /** * Propagates the observable sequence or Promise that reacts first. * @param {Observable} rightSource Second observable sequence or Promise. * @returns {Observable} {Observable} An observable sequence that surfaces either of the given sequences, whichever reacted first. */ observableProto.amb = function (rightSource) { var leftSource = this; return new AnonymousObservable(function (observer) { var choice, leftChoice = 'L', rightChoice = 'R', leftSubscription = new SingleAssignmentDisposable(), rightSubscription = new SingleAssignmentDisposable(); isPromise(rightSource) && (rightSource = observableFromPromise(rightSource)); function choiceL() { if (!choice) { choice = leftChoice; rightSubscription.dispose(); } } function choiceR() { if (!choice) { choice = rightChoice; leftSubscription.dispose(); } } leftSubscription.setDisposable(leftSource.subscribe(function (left) { choiceL(); choice === leftChoice && observer.onNext(left); }, function (err) { choiceL(); choice === leftChoice && observer.onError(err); }, function () { choiceL(); choice === leftChoice && observer.onCompleted(); })); rightSubscription.setDisposable(rightSource.subscribe(function (right) { choiceR(); choice === rightChoice && observer.onNext(right); }, function (err) { choiceR(); choice === rightChoice && observer.onError(err); }, function () { choiceR(); choice === rightChoice && observer.onCompleted(); })); return new CompositeDisposable(leftSubscription, rightSubscription); }); }; /** * Propagates the observable sequence or Promise that reacts first. * * @example * var = Rx.Observable.amb(xs, ys, zs); * @returns {Observable} An observable sequence that surfaces any of the given sequences, whichever reacted first. */ Observable.amb = function () { var acc = observableNever(), items = []; if (Array.isArray(arguments[0])) { items = arguments[0]; } else { for(var i = 0, len = arguments.length; i < len; i++) { items.push(arguments[i]); } } function func(previous, current) { return previous.amb(current); } for (var i = 0, len = items.length; i < len; i++) { acc = func(acc, items[i]); } return acc; }; function observableCatchHandler(source, handler) { return new AnonymousObservable(function (o) { var d1 = new SingleAssignmentDisposable(), subscription = new SerialDisposable(); subscription.setDisposable(d1); d1.setDisposable(source.subscribe(function (x) { o.onNext(x); }, function (e) { try { var result = handler(e); } catch (ex) { return o.onError(ex); } isPromise(result) && (result = observableFromPromise(result)); var d = new SingleAssignmentDisposable(); subscription.setDisposable(d); d.setDisposable(result.subscribe(o)); }, function (x) { o.onCompleted(x); })); return subscription; }, source); } /** * Continues an observable sequence that is terminated by an exception with the next observable sequence. * @example * 1 - xs.catchException(ys) * 2 - xs.catchException(function (ex) { return ys(ex); }) * @param {Mixed} handlerOrSecond Exception handler function that returns an observable sequence given the error that occurred in the first sequence, or a second observable sequence used to produce results when an error occurred in the first sequence. * @returns {Observable} An observable sequence containing the first sequence's elements, followed by the elements of the handler sequence in case an exception occurred. */ observableProto['catch'] = observableProto.catchError = observableProto.catchException = function (handlerOrSecond) { return typeof handlerOrSecond === 'function' ? observableCatchHandler(this, handlerOrSecond) : observableCatch([this, handlerOrSecond]); }; /** * Continues an observable sequence that is terminated by an exception with the next observable sequence. * @param {Array | Arguments} args Arguments or an array to use as the next sequence if an error occurs. * @returns {Observable} An observable sequence containing elements from consecutive source sequences until a source sequence terminates successfully. */ var observableCatch = Observable.catchError = Observable['catch'] = Observable.catchException = function () { var items = []; if (Array.isArray(arguments[0])) { items = arguments[0]; } else { for(var i = 0, len = arguments.length; i < len; i++) { items.push(arguments[i]); } } return enumerableOf(items).catchError(); }; /** * Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences or Promises produces an element. * This can be in the form of an argument list of observables or an array. * * @example * 1 - obs = observable.combineLatest(obs1, obs2, obs3, function (o1, o2, o3) { return o1 + o2 + o3; }); * 2 - obs = observable.combineLatest([obs1, obs2, obs3], function (o1, o2, o3) { return o1 + o2 + o3; }); * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. */ observableProto.combineLatest = function () { var len = arguments.length, args = new Array(len); for(var i = 0; i < len; i++) { args[i] = arguments[i]; } if (Array.isArray(args[0])) { args[0].unshift(this); } else { args.unshift(this); } return combineLatest.apply(this, args); }; /** * Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences or Promises produces an element. * * @example * 1 - obs = Rx.Observable.combineLatest(obs1, obs2, obs3, function (o1, o2, o3) { return o1 + o2 + o3; }); * 2 - obs = Rx.Observable.combineLatest([obs1, obs2, obs3], function (o1, o2, o3) { return o1 + o2 + o3; }); * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. */ var combineLatest = Observable.combineLatest = function () { var len = arguments.length, args = new Array(len); for(var i = 0; i < len; i++) { args[i] = arguments[i]; } var resultSelector = args.pop(); Array.isArray(args[0]) && (args = args[0]); return new AnonymousObservable(function (o) { var n = args.length, falseFactory = function () { return false; }, hasValue = arrayInitialize(n, falseFactory), hasValueAll = false, isDone = arrayInitialize(n, falseFactory), values = new Array(n); function next(i) { hasValue[i] = true; if (hasValueAll || (hasValueAll = hasValue.every(identity))) { try { var res = resultSelector.apply(null, values); } catch (e) { return o.onError(e); } o.onNext(res); } else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) { o.onCompleted(); } } function done (i) { isDone[i] = true; isDone.every(identity) && o.onCompleted(); } var subscriptions = new Array(n); for (var idx = 0; idx < n; idx++) { (function (i) { var source = args[i], sad = new SingleAssignmentDisposable(); isPromise(source) && (source = observableFromPromise(source)); sad.setDisposable(source.subscribe(function (x) { values[i] = x; next(i); }, function(e) { o.onError(e); }, function () { done(i); } )); subscriptions[i] = sad; }(idx)); } return new CompositeDisposable(subscriptions); }, this); }; /** * Concatenates all the observable sequences. This takes in either an array or variable arguments to concatenate. * @returns {Observable} An observable sequence that contains the elements of each given sequence, in sequential order. */ observableProto.concat = function () { for(var args = [], i = 0, len = arguments.length; i < len; i++) { args.push(arguments[i]); } args.unshift(this); return observableConcat.apply(null, args); }; var ConcatObservable = (function(__super__) { inherits(ConcatObservable, __super__); function ConcatObservable(sources) { this.sources = sources; __super__.call(this); } ConcatObservable.prototype.subscribeCore = function(o) { var sink = new ConcatSink(this.sources, o); return sink.run(); }; function ConcatSink(sources, o) { this.sources = sources; this.o = o; } ConcatSink.prototype.run = function () { var isDisposed, subscription = new SerialDisposable(), sources = this.sources, length = sources.length, o = this.o; var cancelable = immediateScheduler.scheduleRecursiveWithState(0, function (i, self) { if (isDisposed) { return; } if (i === length) { return o.onCompleted(); } // Check if promise var currentValue = sources[i]; isPromise(currentValue) && (currentValue = observableFromPromise(currentValue)); var d = new SingleAssignmentDisposable(); subscription.setDisposable(d); d.setDisposable(currentValue.subscribe( function (x) { o.onNext(x); }, function (e) { o.onError(e); }, function () { self(i + 1); } )); }); return new CompositeDisposable(subscription, cancelable, disposableCreate(function () { isDisposed = true; })); }; return ConcatObservable; }(ObservableBase)); /** * Concatenates all the observable sequences. * @param {Array | Arguments} args Arguments or an array to concat to the observable sequence. * @returns {Observable} An observable sequence that contains the elements of each given sequence, in sequential order. */ var observableConcat = Observable.concat = function () { var args; if (Array.isArray(arguments[0])) { args = arguments[0]; } else { args = new Array(arguments.length); for(var i = 0, len = arguments.length; i < len; i++) { args[i] = arguments[i]; } } return new ConcatObservable(args); }; /** * Concatenates an observable sequence of observable sequences. * @returns {Observable} An observable sequence that contains the elements of each observed inner sequence, in sequential order. */ observableProto.concatAll = observableProto.concatObservable = function () { return this.merge(1); }; var MergeObservable = (function (__super__) { inherits(MergeObservable, __super__); function MergeObservable(source, maxConcurrent) { this.source = source; this.maxConcurrent = maxConcurrent; __super__.call(this); } MergeObservable.prototype.subscribeCore = function(observer) { var g = new CompositeDisposable(); g.add(this.source.subscribe(new MergeObserver(observer, this.maxConcurrent, g))); return g; }; return MergeObservable; }(ObservableBase)); var MergeObserver = (function () { function MergeObserver(o, max, g) { this.o = o; this.max = max; this.g = g; this.done = false; this.q = []; this.activeCount = 0; this.isStopped = false; } MergeObserver.prototype.handleSubscribe = function (xs) { var sad = new SingleAssignmentDisposable(); this.g.add(sad); isPromise(xs) && (xs = observableFromPromise(xs)); sad.setDisposable(xs.subscribe(new InnerObserver(this, sad))); }; MergeObserver.prototype.onNext = function (innerSource) { if (this.isStopped) { return; } if(this.activeCount < this.max) { this.activeCount++; this.handleSubscribe(innerSource); } else { this.q.push(innerSource); } }; MergeObserver.prototype.onError = function (e) { if (!this.isStopped) { this.isStopped = true; this.o.onError(e); } }; MergeObserver.prototype.onCompleted = function () { if (!this.isStopped) { this.isStopped = true; this.done = true; this.activeCount === 0 && this.o.onCompleted(); } }; MergeObserver.prototype.dispose = function() { this.isStopped = true; }; MergeObserver.prototype.fail = function (e) { if (!this.isStopped) { this.isStopped = true; this.o.onError(e); return true; } return false; }; function InnerObserver(parent, sad) { this.parent = parent; this.sad = sad; this.isStopped = false; } InnerObserver.prototype.onNext = function (x) { if(!this.isStopped) { this.parent.o.onNext(x); } }; InnerObserver.prototype.onError = function (e) { if (!this.isStopped) { this.isStopped = true; this.parent.o.onError(e); } }; InnerObserver.prototype.onCompleted = function () { if(!this.isStopped) { this.isStopped = true; var parent = this.parent; parent.g.remove(this.sad); if (parent.q.length > 0) { parent.handleSubscribe(parent.q.shift()); } else { parent.activeCount--; parent.done && parent.activeCount === 0 && parent.o.onCompleted(); } } }; InnerObserver.prototype.dispose = function() { this.isStopped = true; }; InnerObserver.prototype.fail = function (e) { if (!this.isStopped) { this.isStopped = true; this.parent.o.onError(e); return true; } return false; }; return MergeObserver; }()); /** * Merges an observable sequence of observable sequences into an observable sequence, limiting the number of concurrent subscriptions to inner sequences. * Or merges two observable sequences into a single observable sequence. * * @example * 1 - merged = sources.merge(1); * 2 - merged = source.merge(otherSource); * @param {Mixed} [maxConcurrentOrOther] Maximum number of inner observable sequences being subscribed to concurrently or the second observable sequence. * @returns {Observable} The observable sequence that merges the elements of the inner sequences. */ observableProto.merge = function (maxConcurrentOrOther) { return typeof maxConcurrentOrOther !== 'number' ? observableMerge(this, maxConcurrentOrOther) : new MergeObservable(this, maxConcurrentOrOther); }; /** * Merges all the observable sequences into a single observable sequence. * The scheduler is optional and if not specified, the immediate scheduler is used. * @returns {Observable} The observable sequence that merges the elements of the observable sequences. */ var observableMerge = Observable.merge = function () { var scheduler, sources = [], i, len = arguments.length; if (!arguments[0]) { scheduler = immediateScheduler; for(i = 1; i < len; i++) { sources.push(arguments[i]); } } else if (isScheduler(arguments[0])) { scheduler = arguments[0]; for(i = 1; i < len; i++) { sources.push(arguments[i]); } } else { scheduler = immediateScheduler; for(i = 0; i < len; i++) { sources.push(arguments[i]); } } if (Array.isArray(sources[0])) { sources = sources[0]; } return observableOf(scheduler, sources).mergeAll(); }; var MergeAllObservable = (function (__super__) { inherits(MergeAllObservable, __super__); function MergeAllObservable(source) { this.source = source; __super__.call(this); } MergeAllObservable.prototype.subscribeCore = function (observer) { var g = new CompositeDisposable(), m = new SingleAssignmentDisposable(); g.add(m); m.setDisposable(this.source.subscribe(new MergeAllObserver(observer, g))); return g; }; function MergeAllObserver(o, g) { this.o = o; this.g = g; this.isStopped = false; this.done = false; } MergeAllObserver.prototype.onNext = function(innerSource) { if(this.isStopped) { return; } var sad = new SingleAssignmentDisposable(); this.g.add(sad); isPromise(innerSource) && (innerSource = observableFromPromise(innerSource)); sad.setDisposable(innerSource.subscribe(new InnerObserver(this, this.g, sad))); }; MergeAllObserver.prototype.onError = function (e) { if(!this.isStopped) { this.isStopped = true; this.o.onError(e); } }; MergeAllObserver.prototype.onCompleted = function () { if(!this.isStopped) { this.isStopped = true; this.done = true; this.g.length === 1 && this.o.onCompleted(); } }; MergeAllObserver.prototype.dispose = function() { this.isStopped = true; }; MergeAllObserver.prototype.fail = function (e) { if (!this.isStopped) { this.isStopped = true; this.o.onError(e); return true; } return false; }; function InnerObserver(parent, g, sad) { this.parent = parent; this.g = g; this.sad = sad; this.isStopped = false; } InnerObserver.prototype.onNext = function (x) { if (!this.isStopped) { this.parent.o.onNext(x); } }; InnerObserver.prototype.onError = function (e) { if(!this.isStopped) { this.isStopped = true; this.parent.o.onError(e); } }; InnerObserver.prototype.onCompleted = function () { if(!this.isStopped) { var parent = this.parent; this.isStopped = true; parent.g.remove(this.sad); parent.done && parent.g.length === 1 && parent.o.onCompleted(); } }; InnerObserver.prototype.dispose = function() { this.isStopped = true; }; InnerObserver.prototype.fail = function (e) { if (!this.isStopped) { this.isStopped = true; this.parent.o.onError(e); return true; } return false; }; return MergeAllObservable; }(ObservableBase)); /** * Merges an observable sequence of observable sequences into an observable sequence. * @returns {Observable} The observable sequence that merges the elements of the inner sequences. */ observableProto.mergeAll = observableProto.mergeObservable = function () { return new MergeAllObservable(this); }; var CompositeError = Rx.CompositeError = function(errors) { this.name = "NotImplementedError"; this.innerErrors = errors; this.message = 'This contains multiple errors. Check the innerErrors'; Error.call(this); } CompositeError.prototype = Error.prototype; /** * Flattens an Observable that emits Observables into one Observable, in a way that allows an Observer to * receive all successfully emitted items from all of the source Observables without being interrupted by * an error notification from one of them. * * This behaves like Observable.prototype.mergeAll except that if any of the merged Observables notify of an * error via the Observer's onError, mergeDelayError will refrain from propagating that * error notification until all of the merged Observables have finished emitting items. * @param {Array | Arguments} args Arguments or an array to merge. * @returns {Observable} an Observable that emits all of the items emitted by the Observables emitted by the Observable */ Observable.mergeDelayError = function() { var args; if (Array.isArray(arguments[0])) { args = arguments[0]; } else { var len = arguments.length; args = new Array(len); for(var i = 0; i < len; i++) { args[i] = arguments[i]; } } var source = observableOf(null, args); return new AnonymousObservable(function (o) { var group = new CompositeDisposable(), m = new SingleAssignmentDisposable(), isStopped = false, errors = []; function setCompletion() { if (errors.length === 0) { o.onCompleted(); } else if (errors.length === 1) { o.onError(errors[0]); } else { o.onError(new CompositeError(errors)); } } group.add(m); m.setDisposable(source.subscribe( function (innerSource) { var innerSubscription = new SingleAssignmentDisposable(); group.add(innerSubscription); // Check for promises support isPromise(innerSource) && (innerSource = observableFromPromise(innerSource)); innerSubscription.setDisposable(innerSource.subscribe( function (x) { o.onNext(x); }, function (e) { errors.push(e); group.remove(innerSubscription); isStopped && group.length === 1 && setCompletion(); }, function () { group.remove(innerSubscription); isStopped && group.length === 1 && setCompletion(); })); }, function (e) { errors.push(e); isStopped = true; group.length === 1 && setCompletion(); }, function () { isStopped = true; group.length === 1 && setCompletion(); })); return group; }); }; /** * Continues an observable sequence that is terminated normally or by an exception with the next observable sequence. * @param {Observable} second Second observable sequence used to produce results after the first sequence terminates. * @returns {Observable} An observable sequence that concatenates the first and second sequence, even if the first sequence terminates exceptionally. */ observableProto.onErrorResumeNext = function (second) { if (!second) { throw new Error('Second observable is required'); } return onErrorResumeNext([this, second]); }; /** * Continues an observable sequence that is terminated normally or by an exception with the next observable sequence. * * @example * 1 - res = Rx.Observable.onErrorResumeNext(xs, ys, zs); * 1 - res = Rx.Observable.onErrorResumeNext([xs, ys, zs]); * @returns {Observable} An observable sequence that concatenates the source sequences, even if a sequence terminates exceptionally. */ var onErrorResumeNext = Observable.onErrorResumeNext = function () { var sources = []; if (Array.isArray(arguments[0])) { sources = arguments[0]; } else { for(var i = 0, len = arguments.length; i < len; i++) { sources.push(arguments[i]); } } return new AnonymousObservable(function (observer) { var pos = 0, subscription = new SerialDisposable(), cancelable = immediateScheduler.scheduleRecursive(function (self) { var current, d; if (pos < sources.length) { current = sources[pos++]; isPromise(current) && (current = observableFromPromise(current)); d = new SingleAssignmentDisposable(); subscription.setDisposable(d); d.setDisposable(current.subscribe(observer.onNext.bind(observer), self, self)); } else { observer.onCompleted(); } }); return new CompositeDisposable(subscription, cancelable); }); }; /** * Returns the values from the source observable sequence only after the other observable sequence produces a value. * @param {Observable | Promise} other The observable sequence or Promise that triggers propagation of elements of the source sequence. * @returns {Observable} An observable sequence containing the elements of the source sequence starting from the point the other sequence triggered propagation. */ observableProto.skipUntil = function (other) { var source = this; return new AnonymousObservable(function (o) { var isOpen = false; var disposables = new CompositeDisposable(source.subscribe(function (left) { isOpen && o.onNext(left); }, function (e) { o.onError(e); }, function () { isOpen && o.onCompleted(); })); isPromise(other) && (other = observableFromPromise(other)); var rightSubscription = new SingleAssignmentDisposable(); disposables.add(rightSubscription); rightSubscription.setDisposable(other.subscribe(function () { isOpen = true; rightSubscription.dispose(); }, function (e) { o.onError(e); }, function () { rightSubscription.dispose(); })); return disposables; }, source); }; var SwitchObservable = (function(__super__) { inherits(SwitchObservable, __super__); function SwitchObservable(source) { this.source = source; __super__.call(this); } SwitchObservable.prototype.subscribeCore = function (o) { var inner = new SerialDisposable(), s = this.source.subscribe(new SwitchObserver(o, inner)); return new CompositeDisposable(s, inner); }; function SwitchObserver(o, inner) { this.o = o; this.inner = inner; this.stopped = false; this.latest = 0; this.hasLatest = false; this.isStopped = false; } SwitchObserver.prototype.onNext = function (innerSource) { if (this.isStopped) { return; } var d = new SingleAssignmentDisposable(), id = ++this.latest; this.hasLatest = true; this.inner.setDisposable(d); isPromise(innerSource) && (innerSource = observableFromPromise(innerSource)); d.setDisposable(innerSource.subscribe(new InnerObserver(this, id))); }; SwitchObserver.prototype.onError = function (e) { if (!this.isStopped) { this.isStopped = true; this.o.onError(e); } }; SwitchObserver.prototype.onCompleted = function () { if (!this.isStopped) { this.isStopped = true; this.stopped = true; !this.hasLatest && this.o.onCompleted(); } }; SwitchObserver.prototype.dispose = function () { this.isStopped = true; }; SwitchObserver.prototype.fail = function (e) { if(!this.isStopped) { this.isStopped = true; this.o.onError(e); return true; } return false; }; function InnerObserver(parent, id) { this.parent = parent; this.id = id; this.isStopped = false; } InnerObserver.prototype.onNext = function (x) { if (this.isStopped) { return; } this.parent.latest === this.id && this.parent.o.onNext(x); }; InnerObserver.prototype.onError = function (e) { if (!this.isStopped) { this.isStopped = true; this.parent.latest === this.id && this.parent.o.onError(e); } }; InnerObserver.prototype.onCompleted = function () { if (!this.isStopped) { this.isStopped = true; if (this.parent.latest === this.id) { this.parent.hasLatest = false; this.parent.isStopped && this.parent.o.onCompleted(); } } }; InnerObserver.prototype.dispose = function () { this.isStopped = true; } InnerObserver.prototype.fail = function (e) { if(!this.isStopped) { this.isStopped = true; this.parent.o.onError(e); return true; } return false; }; return SwitchObservable; }(ObservableBase)); /** * Transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence. * @returns {Observable} The observable sequence that at any point in time produces the elements of the most recent inner observable sequence that has been received. */ observableProto['switch'] = observableProto.switchLatest = function () { return new SwitchObservable(this); }; var TakeUntilObservable = (function(__super__) { inherits(TakeUntilObservable, __super__); function TakeUntilObservable(source, other) { this.source = source; this.other = isPromise(other) ? observableFromPromise(other) : other; __super__.call(this); } TakeUntilObservable.prototype.subscribeCore = function(o) { return new CompositeDisposable( this.source.subscribe(o), this.other.subscribe(new InnerObserver(o)) ); }; function InnerObserver(o) { this.o = o; this.isStopped = false; } InnerObserver.prototype.onNext = function (x) { if (this.isStopped) { return; } this.o.onCompleted(); }; InnerObserver.prototype.onError = function (err) { if (!this.isStopped) { this.isStopped = true; this.o.onError(err); } }; InnerObserver.prototype.onCompleted = function () { !this.isStopped && (this.isStopped = true); }; InnerObserver.prototype.dispose = function() { this.isStopped = true; }; InnerObserver.prototype.fail = function (e) { if (!this.isStopped) { this.isStopped = true; this.o.onError(e); return true; } return false; }; return TakeUntilObservable; }(ObservableBase)); /** * Returns the values from the source observable sequence until the other observable sequence produces a value. * @param {Observable | Promise} other Observable sequence or Promise that terminates propagation of elements of the source sequence. * @returns {Observable} An observable sequence containing the elements of the source sequence up to the point the other sequence interrupted further propagation. */ observableProto.takeUntil = function (other) { return new TakeUntilObservable(this, other); }; function falseFactory() { return false; } /** * Merges the specified observable sequences into one observable sequence by using the selector function only when the (first) source observable sequence produces an element. * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. */ observableProto.withLatestFrom = function () { var len = arguments.length, args = new Array(len) for(var i = 0; i < len; i++) { args[i] = arguments[i]; } var resultSelector = args.pop(), source = this; Array.isArray(args[0]) && (args = args[0]); return new AnonymousObservable(function (observer) { var n = args.length, hasValue = arrayInitialize(n, falseFactory), hasValueAll = false, values = new Array(n); var subscriptions = new Array(n + 1); for (var idx = 0; idx < n; idx++) { (function (i) { var other = args[i], sad = new SingleAssignmentDisposable(); isPromise(other) && (other = observableFromPromise(other)); sad.setDisposable(other.subscribe(function (x) { values[i] = x; hasValue[i] = true; hasValueAll = hasValue.every(identity); }, function (e) { observer.onError(e); }, noop)); subscriptions[i] = sad; }(idx)); } var sad = new SingleAssignmentDisposable(); sad.setDisposable(source.subscribe(function (x) { var allValues = [x].concat(values); if (!hasValueAll) { return; } var res = tryCatch(resultSelector).apply(null, allValues); if (res === errorObj) { return observer.onError(res.e); } observer.onNext(res); }, function (e) { observer.onError(e); }, function () { observer.onCompleted(); })); subscriptions[n] = sad; return new CompositeDisposable(subscriptions); }, this); }; function zipArray(second, resultSelector) { var first = this; return new AnonymousObservable(function (o) { var index = 0, len = second.length; return first.subscribe(function (left) { if (index < len) { var right = second[index++], res = tryCatch(resultSelector)(left, right); if (res === errorObj) { return o.onError(res.e); } o.onNext(res); } else { o.onCompleted(); } }, function (e) { o.onError(e); }, function () { o.onCompleted(); }); }, first); } function falseFactory() { return false; } function emptyArrayFactory() { return []; } /** * Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences or an array have produced an element at a corresponding index. * The last element in the arguments must be a function to invoke for each series of elements at corresponding indexes in the args. * @returns {Observable} An observable sequence containing the result of combining elements of the args using the specified result selector function. */ observableProto.zip = function () { if (Array.isArray(arguments[0])) { return zipArray.apply(this, arguments); } var len = arguments.length, args = new Array(len); for(var i = 0; i < len; i++) { args[i] = arguments[i]; } var parent = this, resultSelector = args.pop(); args.unshift(parent); return new AnonymousObservable(function (o) { var n = args.length, queues = arrayInitialize(n, emptyArrayFactory), isDone = arrayInitialize(n, falseFactory); var subscriptions = new Array(n); for (var idx = 0; idx < n; idx++) { (function (i) { var source = args[i], sad = new SingleAssignmentDisposable(); isPromise(source) && (source = observableFromPromise(source)); sad.setDisposable(source.subscribe(function (x) { queues[i].push(x); if (queues.every(function (x) { return x.length > 0; })) { var queuedValues = queues.map(function (x) { return x.shift(); }), res = tryCatch(resultSelector).apply(parent, queuedValues); if (res === errorObj) { return o.onError(res.e); } o.onNext(res); } else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) { o.onCompleted(); } }, function (e) { o.onError(e); }, function () { isDone[i] = true; isDone.every(identity) && o.onCompleted(); })); subscriptions[i] = sad; })(idx); } return new CompositeDisposable(subscriptions); }, parent); }; /** * Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index. * @param arguments Observable sources. * @param {Function} resultSelector Function to invoke for each series of elements at corresponding indexes in the sources. * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. */ Observable.zip = function () { var len = arguments.length, args = new Array(len); for(var i = 0; i < len; i++) { args[i] = arguments[i]; } var first = args.shift(); return first.zip.apply(first, args); }; function falseFactory() { return false; } function arrayFactory() { return []; } /** * Merges the specified observable sequences into one observable sequence by emitting a list with the elements of the observable sequences at corresponding indexes. * @param arguments Observable sources. * @returns {Observable} An observable sequence containing lists of elements at corresponding indexes. */ Observable.zipArray = function () { var sources; if (Array.isArray(arguments[0])) { sources = arguments[0]; } else { var len = arguments.length; sources = new Array(len); for(var i = 0; i < len; i++) { sources[i] = arguments[i]; } } return new AnonymousObservable(function (o) { var n = sources.length, queues = arrayInitialize(n, arrayFactory), isDone = arrayInitialize(n, falseFactory); var subscriptions = new Array(n); for (var idx = 0; idx < n; idx++) { (function (i) { subscriptions[i] = new SingleAssignmentDisposable(); subscriptions[i].setDisposable(sources[i].subscribe(function (x) { queues[i].push(x); if (queues.every(function (x) { return x.length > 0; })) { var res = queues.map(function (x) { return x.shift(); }); o.onNext(res); } else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) { return o.onCompleted(); } }, function (e) { o.onError(e); }, function () { isDone[i] = true; isDone.every(identity) && o.onCompleted(); })); })(idx); } return new CompositeDisposable(subscriptions); }); }; /** * Hides the identity of an observable sequence. * @returns {Observable} An observable sequence that hides the identity of the source sequence. */ observableProto.asObservable = function () { var source = this; return new AnonymousObservable(function (o) { return source.subscribe(o); }, source); }; /** * Projects each element of an observable sequence into zero or more buffers which are produced based on element count information. * * @example * var res = xs.bufferWithCount(10); * var res = xs.bufferWithCount(10, 1); * @param {Number} count Length of each buffer. * @param {Number} [skip] Number of elements to skip between creation of consecutive buffers. If not provided, defaults to the count. * @returns {Observable} An observable sequence of buffers. */ observableProto.bufferWithCount = function (count, skip) { if (typeof skip !== 'number') { skip = count; } return this.windowWithCount(count, skip).selectMany(function (x) { return x.toArray(); }).where(function (x) { return x.length > 0; }); }; /** * Dematerializes the explicit notification values of an observable sequence as implicit notifications. * @returns {Observable} An observable sequence exhibiting the behavior corresponding to the source sequence's notification values. */ observableProto.dematerialize = function () { var source = this; return new AnonymousObservable(function (o) { return source.subscribe(function (x) { return x.accept(o); }, function(e) { o.onError(e); }, function () { o.onCompleted(); }); }, this); }; /** * Returns an observable sequence that contains only distinct contiguous elements according to the keySelector and the comparer. * * var obs = observable.distinctUntilChanged(); * var obs = observable.distinctUntilChanged(function (x) { return x.id; }); * var obs = observable.distinctUntilChanged(function (x) { return x.id; }, function (x, y) { return x === y; }); * * @param {Function} [keySelector] A function to compute the comparison key for each element. If not provided, it projects the value. * @param {Function} [comparer] Equality comparer for computed key values. If not provided, defaults to an equality comparer function. * @returns {Observable} An observable sequence only containing the distinct contiguous elements, based on a computed key value, from the source sequence. */ observableProto.distinctUntilChanged = function (keySelector, comparer) { var source = this; comparer || (comparer = defaultComparer); return new AnonymousObservable(function (o) { var hasCurrentKey = false, currentKey; return source.subscribe(function (value) { var key = value; if (keySelector) { key = tryCatch(keySelector)(value); if (key === errorObj) { return o.onError(key.e); } } if (hasCurrentKey) { var comparerEquals = tryCatch(comparer)(currentKey, key); if (comparerEquals === errorObj) { return o.onError(comparerEquals.e); } } if (!hasCurrentKey || !comparerEquals) { hasCurrentKey = true; currentKey = key; o.onNext(value); } }, function (e) { o.onError(e); }, function () { o.onCompleted(); }); }, this); }; var TapObservable = (function(__super__) { inherits(TapObservable,__super__); function TapObservable(source, observerOrOnNext, onError, onCompleted) { this.source = source; this.t = !observerOrOnNext || isFunction(observerOrOnNext) ? observerCreate(observerOrOnNext || noop, onError || noop, onCompleted || noop) : observerOrOnNext; __super__.call(this); } TapObservable.prototype.subscribeCore = function(o) { return this.source.subscribe(new InnerObserver(o, this.t)); }; function InnerObserver(o, t) { this.o = o; this.t = t; this.isStopped = false; } InnerObserver.prototype.onNext = function(x) { if (this.isStopped) { return; } var res = tryCatch(this.t.onNext).call(this.t, x); if (res === errorObj) { this.o.onError(res.e); } this.o.onNext(x); }; InnerObserver.prototype.onError = function(err) { if (!this.isStopped) { this.isStopped = true; var res = tryCatch(this.t.onError).call(this.t, err); if (res === errorObj) { return this.o.onError(res.e); } this.o.onError(err); } }; InnerObserver.prototype.onCompleted = function() { if (!this.isStopped) { this.isStopped = true; var res = tryCatch(this.t.onCompleted).call(this.t); if (res === errorObj) { return this.o.onError(res.e); } this.o.onCompleted(); } }; InnerObserver.prototype.dispose = function() { this.isStopped = true; }; InnerObserver.prototype.fail = function (e) { if (!this.isStopped) { this.isStopped = true; this.o.onError(e); return true; } return false; }; return TapObservable; }(ObservableBase)); /** * Invokes an action for each element in the observable sequence and invokes an action upon graceful or exceptional termination of the observable sequence. * This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline. * @param {Function | Observer} observerOrOnNext Action to invoke for each element in the observable sequence or an o. * @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function. * @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function. * @returns {Observable} The source sequence with the side-effecting behavior applied. */ observableProto['do'] = observableProto.tap = observableProto.doAction = function (observerOrOnNext, onError, onCompleted) { return new TapObservable(this, observerOrOnNext, onError, onCompleted); }; /** * Invokes an action for each element in the observable sequence. * This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline. * @param {Function} onNext Action to invoke for each element in the observable sequence. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} The source sequence with the side-effecting behavior applied. */ observableProto.doOnNext = observableProto.tapOnNext = function (onNext, thisArg) { return this.tap(typeof thisArg !== 'undefined' ? function (x) { onNext.call(thisArg, x); } : onNext); }; /** * Invokes an action upon exceptional termination of the observable sequence. * This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline. * @param {Function} onError Action to invoke upon exceptional termination of the observable sequence. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} The source sequence with the side-effecting behavior applied. */ observableProto.doOnError = observableProto.tapOnError = function (onError, thisArg) { return this.tap(noop, typeof thisArg !== 'undefined' ? function (e) { onError.call(thisArg, e); } : onError); }; /** * Invokes an action upon graceful termination of the observable sequence. * This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline. * @param {Function} onCompleted Action to invoke upon graceful termination of the observable sequence. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} The source sequence with the side-effecting behavior applied. */ observableProto.doOnCompleted = observableProto.tapOnCompleted = function (onCompleted, thisArg) { return this.tap(noop, null, typeof thisArg !== 'undefined' ? function () { onCompleted.call(thisArg); } : onCompleted); }; /** * Invokes a specified action after the source observable sequence terminates gracefully or exceptionally. * @param {Function} finallyAction Action to invoke after the source observable sequence terminates. * @returns {Observable} Source sequence with the action-invoking termination behavior applied. */ observableProto['finally'] = observableProto.ensure = function (action) { var source = this; return new AnonymousObservable(function (observer) { var subscription; try { subscription = source.subscribe(observer); } catch (e) { action(); throw e; } return disposableCreate(function () { try { subscription.dispose(); } catch (e) { throw e; } finally { action(); } }); }, this); }; /** * @deprecated use #finally or #ensure instead. */ observableProto.finallyAction = function (action) { //deprecate('finallyAction', 'finally or ensure'); return this.ensure(action); }; var IgnoreElementsObservable = (function(__super__) { inherits(IgnoreElementsObservable, __super__); function IgnoreElementsObservable(source) { this.source = source; __super__.call(this); } IgnoreElementsObservable.prototype.subscribeCore = function (o) { return this.source.subscribe(new InnerObserver(o)); }; function InnerObserver(o) { this.o = o; this.isStopped = false; } InnerObserver.prototype.onNext = noop; InnerObserver.prototype.onError = function (err) { if(!this.isStopped) { this.isStopped = true; this.o.onError(err); } }; InnerObserver.prototype.onCompleted = function () { if(!this.isStopped) { this.isStopped = true; this.o.onCompleted(); } }; InnerObserver.prototype.dispose = function() { this.isStopped = true; }; InnerObserver.prototype.fail = function (e) { if (!this.isStopped) { this.isStopped = true; this.observer.onError(e); return true; } return false; }; return IgnoreElementsObservable; }(ObservableBase)); /** * Ignores all elements in an observable sequence leaving only the termination messages. * @returns {Observable} An empty observable sequence that signals termination, successful or exceptional, of the source sequence. */ observableProto.ignoreElements = function () { return new IgnoreElementsObservable(this); }; /** * Materializes the implicit notifications of an observable sequence as explicit notification values. * @returns {Observable} An observable sequence containing the materialized notification values from the source sequence. */ observableProto.materialize = function () { var source = this; return new AnonymousObservable(function (observer) { return source.subscribe(function (value) { observer.onNext(notificationCreateOnNext(value)); }, function (e) { observer.onNext(notificationCreateOnError(e)); observer.onCompleted(); }, function () { observer.onNext(notificationCreateOnCompleted()); observer.onCompleted(); }); }, source); }; /** * Repeats the observable sequence a specified number of times. If the repeat count is not specified, the sequence repeats indefinitely. * @param {Number} [repeatCount] Number of times to repeat the sequence. If not provided, repeats the sequence indefinitely. * @returns {Observable} The observable sequence producing the elements of the given sequence repeatedly. */ observableProto.repeat = function (repeatCount) { return enumerableRepeat(this, repeatCount).concat(); }; /** * Repeats the source observable sequence the specified number of times or until it successfully terminates. If the retry count is not specified, it retries indefinitely. * Note if you encounter an error and want it to retry once, then you must use .retry(2); * * @example * var res = retried = retry.repeat(); * var res = retried = retry.repeat(2); * @param {Number} [retryCount] Number of times to retry the sequence. If not provided, retry the sequence indefinitely. * @returns {Observable} An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully. */ observableProto.retry = function (retryCount) { return enumerableRepeat(this, retryCount).catchError(); }; /** * Repeats the source observable sequence upon error each time the notifier emits or until it successfully terminates. * if the notifier completes, the observable sequence completes. * * @example * var timer = Observable.timer(500); * var source = observable.retryWhen(timer); * @param {Observable} [notifier] An observable that triggers the retries or completes the observable with onNext or onCompleted respectively. * @returns {Observable} An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully. */ observableProto.retryWhen = function (notifier) { return enumerableRepeat(this).catchErrorWhen(notifier); }; var ScanObservable = (function(__super__) { inherits(ScanObservable, __super__); function ScanObservable(source, accumulator, hasSeed, seed) { this.source = source; this.accumulator = accumulator; this.hasSeed = hasSeed; this.seed = seed; __super__.call(this); } ScanObservable.prototype.subscribeCore = function(observer) { return this.source.subscribe(new ScanObserver(observer,this)); }; return ScanObservable; }(ObservableBase)); function ScanObserver(observer, parent) { this.observer = observer; this.accumulator = parent.accumulator; this.hasSeed = parent.hasSeed; this.seed = parent.seed; this.hasAccumulation = false; this.accumulation = null; this.hasValue = false; this.isStopped = false; } ScanObserver.prototype.onNext = function (x) { if (this.isStopped) { return; } !this.hasValue && (this.hasValue = true); try { if (this.hasAccumulation) { this.accumulation = this.accumulator(this.accumulation, x); } else { this.accumulation = this.hasSeed ? this.accumulator(this.seed, x) : x; this.hasAccumulation = true; } } catch (e) { return this.observer.onError(e); } this.observer.onNext(this.accumulation); }; ScanObserver.prototype.onError = function (e) { if (!this.isStopped) { this.isStopped = true; this.observer.onError(e); } }; ScanObserver.prototype.onCompleted = function () { if (!this.isStopped) { this.isStopped = true; !this.hasValue && this.hasSeed && this.observer.onNext(this.seed); this.observer.onCompleted(); } }; ScanObserver.prototype.dispose = function() { this.isStopped = true; }; ScanObserver.prototype.fail = function (e) { if (!this.isStopped) { this.isStopped = true; this.observer.onError(e); return true; } return false; }; /** * Applies an accumulator function over an observable sequence and returns each intermediate result. The optional seed value is used as the initial accumulator value. * For aggregation behavior with no intermediate results, see Observable.aggregate. * @param {Mixed} [seed] The initial accumulator value. * @param {Function} accumulator An accumulator function to be invoked on each element. * @returns {Observable} An observable sequence containing the accumulated values. */ observableProto.scan = function () { var hasSeed = false, seed, accumulator, source = this; if (arguments.length === 2) { hasSeed = true; seed = arguments[0]; accumulator = arguments[1]; } else { accumulator = arguments[0]; } return new ScanObservable(this, accumulator, hasSeed, seed); }; /** * Bypasses a specified number of elements at the end of an observable sequence. * @description * This operator accumulates a queue with a length enough to store the first `count` elements. As more elements are * received, elements are taken from the front of the queue and produced on the result sequence. This causes elements to be delayed. * @param count Number of elements to bypass at the end of the source sequence. * @returns {Observable} An observable sequence containing the source sequence elements except for the bypassed ones at the end. */ observableProto.skipLast = function (count) { if (count < 0) { throw new ArgumentOutOfRangeError(); } var source = this; return new AnonymousObservable(function (o) { var q = []; return source.subscribe(function (x) { q.push(x); q.length > count && o.onNext(q.shift()); }, function (e) { o.onError(e); }, function () { o.onCompleted(); }); }, source); }; /** * Prepends a sequence of values to an observable sequence with an optional scheduler and an argument list of values to prepend. * @example * var res = source.startWith(1, 2, 3); * var res = source.startWith(Rx.Scheduler.timeout, 1, 2, 3); * @param {Arguments} args The specified values to prepend to the observable sequence * @returns {Observable} The source sequence prepended with the specified values. */ observableProto.startWith = function () { var values, scheduler, start = 0; if (!!arguments.length && isScheduler(arguments[0])) { scheduler = arguments[0]; start = 1; } else { scheduler = immediateScheduler; } for(var args = [], i = start, len = arguments.length; i < len; i++) { args.push(arguments[i]); } return enumerableOf([observableFromArray(args, scheduler), this]).concat(); }; /** * Returns a specified number of contiguous elements from the end of an observable sequence. * @description * This operator accumulates a buffer with a length enough to store elements count elements. Upon completion of * the source sequence, this buffer is drained on the result sequence. This causes the elements to be delayed. * @param {Number} count Number of elements to take from the end of the source sequence. * @returns {Observable} An observable sequence containing the specified number of elements from the end of the source sequence. */ observableProto.takeLast = function (count) { if (count < 0) { throw new ArgumentOutOfRangeError(); } var source = this; return new AnonymousObservable(function (o) { var q = []; return source.subscribe(function (x) { q.push(x); q.length > count && q.shift(); }, function (e) { o.onError(e); }, function () { while (q.length > 0) { o.onNext(q.shift()); } o.onCompleted(); }); }, source); }; /** * Returns an array with the specified number of contiguous elements from the end of an observable sequence. * * @description * This operator accumulates a buffer with a length enough to store count elements. Upon completion of the * source sequence, this buffer is produced on the result sequence. * @param {Number} count Number of elements to take from the end of the source sequence. * @returns {Observable} An observable sequence containing a single array with the specified number of elements from the end of the source sequence. */ observableProto.takeLastBuffer = function (count) { var source = this; return new AnonymousObservable(function (o) { var q = []; return source.subscribe(function (x) { q.push(x); q.length > count && q.shift(); }, function (e) { o.onError(e); }, function () { o.onNext(q); o.onCompleted(); }); }, source); }; /** * Projects each element of an observable sequence into zero or more windows which are produced based on element count information. * * var res = xs.windowWithCount(10); * var res = xs.windowWithCount(10, 1); * @param {Number} count Length of each window. * @param {Number} [skip] Number of elements to skip between creation of consecutive windows. If not specified, defaults to the count. * @returns {Observable} An observable sequence of windows. */ observableProto.windowWithCount = function (count, skip) { var source = this; +count || (count = 0); Math.abs(count) === Infinity && (count = 0); if (count <= 0) { throw new ArgumentOutOfRangeError(); } skip == null && (skip = count); +skip || (skip = 0); Math.abs(skip) === Infinity && (skip = 0); if (skip <= 0) { throw new ArgumentOutOfRangeError(); } return new AnonymousObservable(function (observer) { var m = new SingleAssignmentDisposable(), refCountDisposable = new RefCountDisposable(m), n = 0, q = []; function createWindow () { var s = new Subject(); q.push(s); observer.onNext(addRef(s, refCountDisposable)); } createWindow(); m.setDisposable(source.subscribe( function (x) { for (var i = 0, len = q.length; i < len; i++) { q[i].onNext(x); } var c = n - count + 1; c >= 0 && c % skip === 0 && q.shift().onCompleted(); ++n % skip === 0 && createWindow(); }, function (e) { while (q.length > 0) { q.shift().onError(e); } observer.onError(e); }, function () { while (q.length > 0) { q.shift().onCompleted(); } observer.onCompleted(); } )); return refCountDisposable; }, source); }; function concatMap(source, selector, thisArg) { var selectorFunc = bindCallback(selector, thisArg, 3); return source.map(function (x, i) { var result = selectorFunc(x, i, source); isPromise(result) && (result = observableFromPromise(result)); (isArrayLike(result) || isIterable(result)) && (result = observableFrom(result)); return result; }).concatAll(); } /** * One of the Following: * Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence. * * @example * var res = source.concatMap(function (x) { return Rx.Observable.range(0, x); }); * Or: * Projects each element of an observable sequence to an observable sequence, invokes the result selector for the source element and each of the corresponding inner sequence's elements, and merges the results into one observable sequence. * * var res = source.concatMap(function (x) { return Rx.Observable.range(0, x); }, function (x, y) { return x + y; }); * Or: * Projects each element of the source observable sequence to the other observable sequence and merges the resulting observable sequences into one observable sequence. * * var res = source.concatMap(Rx.Observable.fromArray([1,2,3])); * @param {Function} selector A transform function to apply to each element or an observable sequence to project each element from the * source sequence onto which could be either an observable or Promise. * @param {Function} [resultSelector] A transform function to apply to each element of the intermediate sequence. * @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function collectionSelector on each element of the input sequence and then mapping each of those sequence elements and their corresponding source element to a result element. */ observableProto.selectConcat = observableProto.concatMap = function (selector, resultSelector, thisArg) { if (isFunction(selector) && isFunction(resultSelector)) { return this.concatMap(function (x, i) { var selectorResult = selector(x, i); isPromise(selectorResult) && (selectorResult = observableFromPromise(selectorResult)); (isArrayLike(selectorResult) || isIterable(selectorResult)) && (selectorResult = observableFrom(selectorResult)); return selectorResult.map(function (y, i2) { return resultSelector(x, y, i, i2); }); }); } return isFunction(selector) ? concatMap(this, selector, thisArg) : concatMap(this, function () { return selector; }); }; /** * Projects each notification of an observable sequence to an observable sequence and concats the resulting observable sequences into one observable sequence. * @param {Function} onNext A transform function to apply to each element; the second parameter of the function represents the index of the source element. * @param {Function} onError A transform function to apply when an error occurs in the source sequence. * @param {Function} onCompleted A transform function to apply when the end of the source sequence is reached. * @param {Any} [thisArg] An optional "this" to use to invoke each transform. * @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function corresponding to each notification in the input sequence. */ observableProto.concatMapObserver = observableProto.selectConcatObserver = function(onNext, onError, onCompleted, thisArg) { var source = this, onNextFunc = bindCallback(onNext, thisArg, 2), onErrorFunc = bindCallback(onError, thisArg, 1), onCompletedFunc = bindCallback(onCompleted, thisArg, 0); return new AnonymousObservable(function (observer) { var index = 0; return source.subscribe( function (x) { var result; try { result = onNextFunc(x, index++); } catch (e) { observer.onError(e); return; } isPromise(result) && (result = observableFromPromise(result)); observer.onNext(result); }, function (err) { var result; try { result = onErrorFunc(err); } catch (e) { observer.onError(e); return; } isPromise(result) && (result = observableFromPromise(result)); observer.onNext(result); observer.onCompleted(); }, function () { var result; try { result = onCompletedFunc(); } catch (e) { observer.onError(e); return; } isPromise(result) && (result = observableFromPromise(result)); observer.onNext(result); observer.onCompleted(); }); }, this).concatAll(); }; /** * Returns the elements of the specified sequence or the specified value in a singleton sequence if the sequence is empty. * * var res = obs = xs.defaultIfEmpty(); * 2 - obs = xs.defaultIfEmpty(false); * * @memberOf Observable# * @param defaultValue The value to return if the sequence is empty. If not provided, this defaults to null. * @returns {Observable} An observable sequence that contains the specified default value if the source is empty; otherwise, the elements of the source itself. */ observableProto.defaultIfEmpty = function (defaultValue) { var source = this; defaultValue === undefined && (defaultValue = null); return new AnonymousObservable(function (observer) { var found = false; return source.subscribe(function (x) { found = true; observer.onNext(x); }, function (e) { observer.onError(e); }, function () { !found && observer.onNext(defaultValue); observer.onCompleted(); }); }, source); }; // Swap out for Array.findIndex function arrayIndexOfComparer(array, item, comparer) { for (var i = 0, len = array.length; i < len; i++) { if (comparer(array[i], item)) { return i; } } return -1; } function HashSet(comparer) { this.comparer = comparer; this.set = []; } HashSet.prototype.push = function(value) { var retValue = arrayIndexOfComparer(this.set, value, this.comparer) === -1; retValue && this.set.push(value); return retValue; }; /** * Returns an observable sequence that contains only distinct elements according to the keySelector and the comparer. * Usage of this operator should be considered carefully due to the maintenance of an internal lookup structure which can grow large. * * @example * var res = obs = xs.distinct(); * 2 - obs = xs.distinct(function (x) { return x.id; }); * 2 - obs = xs.distinct(function (x) { return x.id; }, function (a,b) { return a === b; }); * @param {Function} [keySelector] A function to compute the comparison key for each element. * @param {Function} [comparer] Used to compare items in the collection. * @returns {Observable} An observable sequence only containing the distinct elements, based on a computed key value, from the source sequence. */ observableProto.distinct = function (keySelector, comparer) { var source = this; comparer || (comparer = defaultComparer); return new AnonymousObservable(function (o) { var hashSet = new HashSet(comparer); return source.subscribe(function (x) { var key = x; if (keySelector) { try { key = keySelector(x); } catch (e) { o.onError(e); return; } } hashSet.push(key) && o.onNext(x); }, function (e) { o.onError(e); }, function () { o.onCompleted(); }); }, this); }; /** * Groups the elements of an observable sequence according to a specified key selector function and comparer and selects the resulting elements by using a specified function. * * @example * var res = observable.groupBy(function (x) { return x.id; }); * 2 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }); * 3 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }, function (x) { return x.toString(); }); * @param {Function} keySelector A function to extract the key for each element. * @param {Function} [elementSelector] A function to map each source element to an element in an observable group. * @param {Function} [comparer] Used to determine whether the objects are equal. * @returns {Observable} A sequence of observable groups, each of which corresponds to a unique key value, containing all elements that share that same key value. */ observableProto.groupBy = function (keySelector, elementSelector, comparer) { return this.groupByUntil(keySelector, elementSelector, observableNever, comparer); }; /** * Groups the elements of an observable sequence according to a specified key selector function. * A duration selector function is used to control the lifetime of groups. When a group expires, it receives an OnCompleted notification. When a new element with the same * key value as a reclaimed group occurs, the group will be reborn with a new lifetime request. * * @example * var res = observable.groupByUntil(function (x) { return x.id; }, null, function () { return Rx.Observable.never(); }); * 2 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }, function () { return Rx.Observable.never(); }); * 3 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }, function () { return Rx.Observable.never(); }, function (x) { return x.toString(); }); * @param {Function} keySelector A function to extract the key for each element. * @param {Function} durationSelector A function to signal the expiration of a group. * @param {Function} [comparer] Used to compare objects. When not specified, the default comparer is used. * @returns {Observable} * A sequence of observable groups, each of which corresponds to a unique key value, containing all elements that share that same key value. * If a group's lifetime expires, a new group with the same key value can be created once an element with such a key value is encoutered. * */ observableProto.groupByUntil = function (keySelector, elementSelector, durationSelector, comparer) { var source = this; elementSelector || (elementSelector = identity); comparer || (comparer = defaultComparer); return new AnonymousObservable(function (observer) { function handleError(e) { return function (item) { item.onError(e); }; } var map = new Dictionary(0, comparer), groupDisposable = new CompositeDisposable(), refCountDisposable = new RefCountDisposable(groupDisposable); groupDisposable.add(source.subscribe(function (x) { var key; try { key = keySelector(x); } catch (e) { map.getValues().forEach(handleError(e)); observer.onError(e); return; } var fireNewMapEntry = false, writer = map.tryGetValue(key); if (!writer) { writer = new Subject(); map.set(key, writer); fireNewMapEntry = true; } if (fireNewMapEntry) { var group = new GroupedObservable(key, writer, refCountDisposable), durationGroup = new GroupedObservable(key, writer); try { duration = durationSelector(durationGroup); } catch (e) { map.getValues().forEach(handleError(e)); observer.onError(e); return; } observer.onNext(group); var md = new SingleAssignmentDisposable(); groupDisposable.add(md); var expire = function () { map.remove(key) && writer.onCompleted(); groupDisposable.remove(md); }; md.setDisposable(duration.take(1).subscribe( noop, function (exn) { map.getValues().forEach(handleError(exn)); observer.onError(exn); }, expire) ); } var element; try { element = elementSelector(x); } catch (e) { map.getValues().forEach(handleError(e)); observer.onError(e); return; } writer.onNext(element); }, function (ex) { map.getValues().forEach(handleError(ex)); observer.onError(ex); }, function () { map.getValues().forEach(function (item) { item.onCompleted(); }); observer.onCompleted(); })); return refCountDisposable; }, source); }; var MapObservable = (function (__super__) { inherits(MapObservable, __super__); function MapObservable(source, selector, thisArg) { this.source = source; this.selector = bindCallback(selector, thisArg, 3); __super__.call(this); } function innerMap(selector, self) { return function (x, i, o) { return selector.call(this, self.selector(x, i, o), i, o); } } MapObservable.prototype.internalMap = function (selector, thisArg) { return new MapObservable(this.source, innerMap(selector, this), thisArg); }; MapObservable.prototype.subscribeCore = function (o) { return this.source.subscribe(new InnerObserver(o, this.selector, this)); }; function InnerObserver(o, selector, source) { this.o = o; this.selector = selector; this.source = source; this.i = 0; this.isStopped = false; } InnerObserver.prototype.onNext = function(x) { if (this.isStopped) { return; } var result = tryCatch(this.selector)(x, this.i++, this.source); if (result === errorObj) { return this.o.onError(result.e); } this.o.onNext(result); }; InnerObserver.prototype.onError = function (e) { if(!this.isStopped) { this.isStopped = true; this.o.onError(e); } }; InnerObserver.prototype.onCompleted = function () { if(!this.isStopped) { this.isStopped = true; this.o.onCompleted(); } }; InnerObserver.prototype.dispose = function() { this.isStopped = true; }; InnerObserver.prototype.fail = function (e) { if (!this.isStopped) { this.isStopped = true; this.o.onError(e); return true; } return false; }; return MapObservable; }(ObservableBase)); /** * Projects each element of an observable sequence into a new form by incorporating the element's index. * @param {Function} selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source. */ observableProto.map = observableProto.select = function (selector, thisArg) { var selectorFn = typeof selector === 'function' ? selector : function () { return selector; }; return this instanceof MapObservable ? this.internalMap(selectorFn, thisArg) : new MapObservable(this, selectorFn, thisArg); }; /** * Retrieves the value of a specified nested property from all elements in * the Observable sequence. * @param {Arguments} arguments The nested properties to pluck. * @returns {Observable} Returns a new Observable sequence of property values. */ observableProto.pluck = function () { var args = arguments, len = arguments.length; if (len === 0) { throw new Error('List of properties cannot be empty.'); } return this.map(function (x) { var currentProp = x; for (var i = 0; i < len; i++) { var p = currentProp[args[i]]; if (typeof p !== 'undefined') { currentProp = p; } else { return undefined; } } return currentProp; }); }; function flatMap(source, selector, thisArg) { var selectorFunc = bindCallback(selector, thisArg, 3); return source.map(function (x, i) { var result = selectorFunc(x, i, source); isPromise(result) && (result = observableFromPromise(result)); (isArrayLike(result) || isIterable(result)) && (result = observableFrom(result)); return result; }).mergeAll(); } /** * One of the Following: * Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence. * * @example * var res = source.selectMany(function (x) { return Rx.Observable.range(0, x); }); * Or: * Projects each element of an observable sequence to an observable sequence, invokes the result selector for the source element and each of the corresponding inner sequence's elements, and merges the results into one observable sequence. * * var res = source.selectMany(function (x) { return Rx.Observable.range(0, x); }, function (x, y) { return x + y; }); * Or: * Projects each element of the source observable sequence to the other observable sequence and merges the resulting observable sequences into one observable sequence. * * var res = source.selectMany(Rx.Observable.fromArray([1,2,3])); * @param {Function} selector A transform function to apply to each element or an observable sequence to project each element from the source sequence onto which could be either an observable or Promise. * @param {Function} [resultSelector] A transform function to apply to each element of the intermediate sequence. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function collectionSelector on each element of the input sequence and then mapping each of those sequence elements and their corresponding source element to a result element. */ observableProto.selectMany = observableProto.flatMap = function (selector, resultSelector, thisArg) { if (isFunction(selector) && isFunction(resultSelector)) { return this.flatMap(function (x, i) { var selectorResult = selector(x, i); isPromise(selectorResult) && (selectorResult = observableFromPromise(selectorResult)); (isArrayLike(selectorResult) || isIterable(selectorResult)) && (selectorResult = observableFrom(selectorResult)); return selectorResult.map(function (y, i2) { return resultSelector(x, y, i, i2); }); }, thisArg); } return isFunction(selector) ? flatMap(this, selector, thisArg) : flatMap(this, function () { return selector; }); }; /** * Projects each notification of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence. * @param {Function} onNext A transform function to apply to each element; the second parameter of the function represents the index of the source element. * @param {Function} onError A transform function to apply when an error occurs in the source sequence. * @param {Function} onCompleted A transform function to apply when the end of the source sequence is reached. * @param {Any} [thisArg] An optional "this" to use to invoke each transform. * @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function corresponding to each notification in the input sequence. */ observableProto.flatMapObserver = observableProto.selectManyObserver = function (onNext, onError, onCompleted, thisArg) { var source = this; return new AnonymousObservable(function (observer) { var index = 0; return source.subscribe( function (x) { var result; try { result = onNext.call(thisArg, x, index++); } catch (e) { observer.onError(e); return; } isPromise(result) && (result = observableFromPromise(result)); observer.onNext(result); }, function (err) { var result; try { result = onError.call(thisArg, err); } catch (e) { observer.onError(e); return; } isPromise(result) && (result = observableFromPromise(result)); observer.onNext(result); observer.onCompleted(); }, function () { var result; try { result = onCompleted.call(thisArg); } catch (e) { observer.onError(e); return; } isPromise(result) && (result = observableFromPromise(result)); observer.onNext(result); observer.onCompleted(); }); }, source).mergeAll(); }; /** * Projects each element of an observable sequence into a new sequence of observable sequences by incorporating the element's index and then * transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence. * @param {Function} selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source producing an Observable of Observable sequences * and that at any point in time produces the elements of the most recent inner observable sequence that has been received. */ observableProto.selectSwitch = observableProto.flatMapLatest = observableProto.switchMap = function (selector, thisArg) { return this.select(selector, thisArg).switchLatest(); }; var SkipObservable = (function(__super__) { inherits(SkipObservable, __super__); function SkipObservable(source, count) { this.source = source; this.skipCount = count; __super__.call(this); } SkipObservable.prototype.subscribeCore = function (o) { return this.source.subscribe(new InnerObserver(o, this.skipCount)); }; function InnerObserver(o, c) { this.c = c; this.r = c; this.o = o; this.isStopped = false; } InnerObserver.prototype.onNext = function (x) { if (this.isStopped) { return; } if (this.r <= 0) { this.o.onNext(x); } else { this.r--; } }; InnerObserver.prototype.onError = function(e) { if (!this.isStopped) { this.isStopped = true; this.o.onError(e); } }; InnerObserver.prototype.onCompleted = function() { if (!this.isStopped) { this.isStopped = true; this.o.onCompleted(); } }; InnerObserver.prototype.dispose = function() { this.isStopped = true; }; InnerObserver.prototype.fail = function(e) { if (!this.isStopped) { this.isStopped = true; this.o.onError(e); return true; } return false; }; return SkipObservable; }(ObservableBase)); /** * Bypasses a specified number of elements in an observable sequence and then returns the remaining elements. * @param {Number} count The number of elements to skip before returning the remaining elements. * @returns {Observable} An observable sequence that contains the elements that occur after the specified index in the input sequence. */ observableProto.skip = function (count) { if (count < 0) { throw new ArgumentOutOfRangeError(); } return new SkipObservable(this, count); }; /** * Bypasses elements in an observable sequence as long as a specified condition is true and then returns the remaining elements. * The element's index is used in the logic of the predicate function. * * var res = source.skipWhile(function (value) { return value < 10; }); * var res = source.skipWhile(function (value, index) { return value < 10 || index < 10; }); * @param {Function} predicate A function to test each element for a condition; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence that contains the elements from the input sequence starting at the first element in the linear series that does not pass the test specified by predicate. */ observableProto.skipWhile = function (predicate, thisArg) { var source = this, callback = bindCallback(predicate, thisArg, 3); return new AnonymousObservable(function (o) { var i = 0, running = false; return source.subscribe(function (x) { if (!running) { try { running = !callback(x, i++, source); } catch (e) { o.onError(e); return; } } running && o.onNext(x); }, function (e) { o.onError(e); }, function () { o.onCompleted(); }); }, source); }; /** * Returns a specified number of contiguous elements from the start of an observable sequence, using the specified scheduler for the edge case of take(0). * * var res = source.take(5); * var res = source.take(0, Rx.Scheduler.timeout); * @param {Number} count The number of elements to return. * @param {Scheduler} [scheduler] Scheduler used to produce an OnCompleted message in case <paramref name="count count</paramref> is set to 0. * @returns {Observable} An observable sequence that contains the specified number of elements from the start of the input sequence. */ observableProto.take = function (count, scheduler) { if (count < 0) { throw new ArgumentOutOfRangeError(); } if (count === 0) { return observableEmpty(scheduler); } var source = this; return new AnonymousObservable(function (o) { var remaining = count; return source.subscribe(function (x) { if (remaining-- > 0) { o.onNext(x); remaining <= 0 && o.onCompleted(); } }, function (e) { o.onError(e); }, function () { o.onCompleted(); }); }, source); }; /** * Returns elements from an observable sequence as long as a specified condition is true. * The element's index is used in the logic of the predicate function. * @param {Function} predicate A function to test each element for a condition; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence that contains the elements from the input sequence that occur before the element at which the test no longer passes. */ observableProto.takeWhile = function (predicate, thisArg) { var source = this, callback = bindCallback(predicate, thisArg, 3); return new AnonymousObservable(function (o) { var i = 0, running = true; return source.subscribe(function (x) { if (running) { try { running = callback(x, i++, source); } catch (e) { o.onError(e); return; } if (running) { o.onNext(x); } else { o.onCompleted(); } } }, function (e) { o.onError(e); }, function () { o.onCompleted(); }); }, source); }; var FilterObservable = (function (__super__) { inherits(FilterObservable, __super__); function FilterObservable(source, predicate, thisArg) { this.source = source; this.predicate = bindCallback(predicate, thisArg, 3); __super__.call(this); } FilterObservable.prototype.subscribeCore = function (o) { return this.source.subscribe(new InnerObserver(o, this.predicate, this)); }; function innerPredicate(predicate, self) { return function(x, i, o) { return self.predicate(x, i, o) && predicate.call(this, x, i, o); } } FilterObservable.prototype.internalFilter = function(predicate, thisArg) { return new FilterObservable(this.source, innerPredicate(predicate, this), thisArg); }; function InnerObserver(o, predicate, source) { this.o = o; this.predicate = predicate; this.source = source; this.i = 0; this.isStopped = false; } InnerObserver.prototype.onNext = function(x) { if (this.isStopped) { return; } var shouldYield = tryCatch(this.predicate)(x, this.i++, this.source); if (shouldYield === errorObj) { return this.o.onError(shouldYield.e); } shouldYield && this.o.onNext(x); }; InnerObserver.prototype.onError = function (e) { if(!this.isStopped) { this.isStopped = true; this.o.onError(e); } }; InnerObserver.prototype.onCompleted = function () { if(!this.isStopped) { this.isStopped = true; this.o.onCompleted(); } }; InnerObserver.prototype.dispose = function() { this.isStopped = true; }; InnerObserver.prototype.fail = function (e) { if (!this.isStopped) { this.isStopped = true; this.o.onError(e); return true; } return false; }; return FilterObservable; }(ObservableBase)); /** * Filters the elements of an observable sequence based on a predicate by incorporating the element's index. * @param {Function} predicate A function to test each source element for a condition; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence that contains elements from the input sequence that satisfy the condition. */ observableProto.filter = observableProto.where = function (predicate, thisArg) { return this instanceof FilterObservable ? this.internalFilter(predicate, thisArg) : new FilterObservable(this, predicate, thisArg); }; function extremaBy(source, keySelector, comparer) { return new AnonymousObservable(function (o) { var hasValue = false, lastKey = null, list = []; return source.subscribe(function (x) { var comparison, key; try { key = keySelector(x); } catch (ex) { o.onError(ex); return; } comparison = 0; if (!hasValue) { hasValue = true; lastKey = key; } else { try { comparison = comparer(key, lastKey); } catch (ex1) { o.onError(ex1); return; } } if (comparison > 0) { lastKey = key; list = []; } if (comparison >= 0) { list.push(x); } }, function (e) { o.onError(e); }, function () { o.onNext(list); o.onCompleted(); }); }, source); } function firstOnly(x) { if (x.length === 0) { throw new EmptyError(); } return x[0]; } /** * Applies an accumulator function over an observable sequence, returning the result of the aggregation as a single element in the result sequence. The specified seed value is used as the initial accumulator value. * For aggregation behavior with incremental intermediate results, see Observable.scan. * @deprecated Use #reduce instead * @param {Mixed} [seed] The initial accumulator value. * @param {Function} accumulator An accumulator function to be invoked on each element. * @returns {Observable} An observable sequence containing a single element with the final accumulator value. */ observableProto.aggregate = function () { var hasSeed = false, accumulator, seed, source = this; if (arguments.length === 2) { hasSeed = true; seed = arguments[0]; accumulator = arguments[1]; } else { accumulator = arguments[0]; } return new AnonymousObservable(function (o) { var hasAccumulation, accumulation, hasValue; return source.subscribe ( function (x) { !hasValue && (hasValue = true); try { if (hasAccumulation) { accumulation = accumulator(accumulation, x); } else { accumulation = hasSeed ? accumulator(seed, x) : x; hasAccumulation = true; } } catch (e) { return o.onError(e); } }, function (e) { o.onError(e); }, function () { hasValue && o.onNext(accumulation); !hasValue && hasSeed && o.onNext(seed); !hasValue && !hasSeed && o.onError(new EmptyError()); o.onCompleted(); } ); }, source); }; var ReduceObservable = (function(__super__) { inherits(ReduceObservable, __super__); function ReduceObservable(source, acc, hasSeed, seed) { this.source = source; this.acc = acc; this.hasSeed = hasSeed; this.seed = seed; __super__.call(this); } ReduceObservable.prototype.subscribeCore = function(observer) { return this.source.subscribe(new InnerObserver(observer,this)); }; function InnerObserver(o, parent) { this.o = o; this.acc = parent.acc; this.hasSeed = parent.hasSeed; this.seed = parent.seed; this.hasAccumulation = false; this.result = null; this.hasValue = false; this.isStopped = false; } InnerObserver.prototype.onNext = function (x) { if (this.isStopped) { return; } !this.hasValue && (this.hasValue = true); if (this.hasAccumulation) { this.result = tryCatch(this.acc)(this.result, x); } else { this.result = this.hasSeed ? tryCatch(this.acc)(this.seed, x) : x; this.hasAccumulation = true; } if (this.result === errorObj) { this.o.onError(this.result.e); } }; InnerObserver.prototype.onError = function (e) { if (!this.isStopped) { this.isStopped = true; this.o.onError(e); } }; InnerObserver.prototype.onCompleted = function () { if (!this.isStopped) { this.isStopped = true; this.hasValue && this.o.onNext(this.result); !this.hasValue && this.hasSeed && this.o.onNext(this.seed); !this.hasValue && !this.hasSeed && this.o.onError(new EmptyError()); this.o.onCompleted(); } }; InnerObserver.prototype.dispose = function () { this.isStopped = true; }; InnerObserver.prototype.fail = function(e) { if (!this.isStopped) { this.isStopped = true; this.o.onError(e); return true; } return false; }; return ReduceObservable; }(ObservableBase)); /** * Applies an accumulator function over an observable sequence, returning the result of the aggregation as a single element in the result sequence. The specified seed value is used as the initial accumulator value. * For aggregation behavior with incremental intermediate results, see Observable.scan. * @param {Function} accumulator An accumulator function to be invoked on each element. * @param {Any} [seed] The initial accumulator value. * @returns {Observable} An observable sequence containing a single element with the final accumulator value. */ observableProto.reduce = function (accumulator) { var hasSeed = false; if (arguments.length === 2) { hasSeed = true; var seed = arguments[1]; } return new ReduceObservable(this, accumulator, hasSeed, seed); }; /** * Determines whether any element of an observable sequence satisfies a condition if present, else if any items are in the sequence. * @param {Function} [predicate] A function to test each element for a condition. * @returns {Observable} An observable sequence containing a single element determining whether any elements in the source sequence pass the test in the specified predicate if given, else if any items are in the sequence. */ observableProto.some = function (predicate, thisArg) { var source = this; return predicate ? source.filter(predicate, thisArg).some() : new AnonymousObservable(function (observer) { return source.subscribe(function () { observer.onNext(true); observer.onCompleted(); }, function (e) { observer.onError(e); }, function () { observer.onNext(false); observer.onCompleted(); }); }, source); }; /** @deprecated use #some instead */ observableProto.any = function () { //deprecate('any', 'some'); return this.some.apply(this, arguments); }; /** * Determines whether an observable sequence is empty. * @returns {Observable} An observable sequence containing a single element determining whether the source sequence is empty. */ observableProto.isEmpty = function () { return this.any().map(not); }; /** * Determines whether all elements of an observable sequence satisfy a condition. * @param {Function} [predicate] A function to test each element for a condition. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence containing a single element determining whether all elements in the source sequence pass the test in the specified predicate. */ observableProto.every = function (predicate, thisArg) { return this.filter(function (v) { return !predicate(v); }, thisArg).some().map(not); }; /** @deprecated use #every instead */ observableProto.all = function () { //deprecate('all', 'every'); return this.every.apply(this, arguments); }; /** * Determines whether an observable sequence includes a specified element with an optional equality comparer. * @param searchElement The value to locate in the source sequence. * @param {Number} [fromIndex] An equality comparer to compare elements. * @returns {Observable} An observable sequence containing a single element determining whether the source sequence includes an element that has the specified value from the given index. */ observableProto.includes = function (searchElement, fromIndex) { var source = this; function comparer(a, b) { return (a === 0 && b === 0) || (a === b || (isNaN(a) && isNaN(b))); } return new AnonymousObservable(function (o) { var i = 0, n = +fromIndex || 0; Math.abs(n) === Infinity && (n = 0); if (n < 0) { o.onNext(false); o.onCompleted(); return disposableEmpty; } return source.subscribe( function (x) { if (i++ >= n && comparer(x, searchElement)) { o.onNext(true); o.onCompleted(); } }, function (e) { o.onError(e); }, function () { o.onNext(false); o.onCompleted(); }); }, this); }; /** * @deprecated use #includes instead. */ observableProto.contains = function (searchElement, fromIndex) { //deprecate('contains', 'includes'); observableProto.includes(searchElement, fromIndex); }; /** * Returns an observable sequence containing a value that represents how many elements in the specified observable sequence satisfy a condition if provided, else the count of items. * @example * res = source.count(); * res = source.count(function (x) { return x > 3; }); * @param {Function} [predicate]A function to test each element for a condition. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence containing a single element with a number that represents how many elements in the input sequence satisfy the condition in the predicate function if provided, else the count of items in the sequence. */ observableProto.count = function (predicate, thisArg) { return predicate ? this.filter(predicate, thisArg).count() : this.reduce(function (count) { return count + 1; }, 0); }; /** * Returns the first index at which a given element can be found in the observable sequence, or -1 if it is not present. * @param {Any} searchElement Element to locate in the array. * @param {Number} [fromIndex] The index to start the search. If not specified, defaults to 0. * @returns {Observable} And observable sequence containing the first index at which a given element can be found in the observable sequence, or -1 if it is not present. */ observableProto.indexOf = function(searchElement, fromIndex) { var source = this; return new AnonymousObservable(function (o) { var i = 0, n = +fromIndex || 0; Math.abs(n) === Infinity && (n = 0); if (n < 0) { o.onNext(-1); o.onCompleted(); return disposableEmpty; } return source.subscribe( function (x) { if (i >= n && x === searchElement) { o.onNext(i); o.onCompleted(); } i++; }, function (e) { o.onError(e); }, function () { o.onNext(-1); o.onCompleted(); }); }, source); }; /** * Computes the sum of a sequence of values that are obtained by invoking an optional transform function on each element of the input sequence, else if not specified computes the sum on each item in the sequence. * @param {Function} [selector] A transform function to apply to each element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence containing a single element with the sum of the values in the source sequence. */ observableProto.sum = function (keySelector, thisArg) { return keySelector && isFunction(keySelector) ? this.map(keySelector, thisArg).sum() : this.reduce(function (prev, curr) { return prev + curr; }, 0); }; /** * Returns the elements in an observable sequence with the minimum key value according to the specified comparer. * @example * var res = source.minBy(function (x) { return x.value; }); * var res = source.minBy(function (x) { return x.value; }, function (x, y) { return x - y; }); * @param {Function} keySelector Key selector function. * @param {Function} [comparer] Comparer used to compare key values. * @returns {Observable} An observable sequence containing a list of zero or more elements that have a minimum key value. */ observableProto.minBy = function (keySelector, comparer) { comparer || (comparer = defaultSubComparer); return extremaBy(this, keySelector, function (x, y) { return comparer(x, y) * -1; }); }; /** * Returns the minimum element in an observable sequence according to the optional comparer else a default greater than less than check. * @example * var res = source.min(); * var res = source.min(function (x, y) { return x.value - y.value; }); * @param {Function} [comparer] Comparer used to compare elements. * @returns {Observable} An observable sequence containing a single element with the minimum element in the source sequence. */ observableProto.min = function (comparer) { return this.minBy(identity, comparer).map(function (x) { return firstOnly(x); }); }; /** * Returns the elements in an observable sequence with the maximum key value according to the specified comparer. * @example * var res = source.maxBy(function (x) { return x.value; }); * var res = source.maxBy(function (x) { return x.value; }, function (x, y) { return x - y;; }); * @param {Function} keySelector Key selector function. * @param {Function} [comparer] Comparer used to compare key values. * @returns {Observable} An observable sequence containing a list of zero or more elements that have a maximum key value. */ observableProto.maxBy = function (keySelector, comparer) { comparer || (comparer = defaultSubComparer); return extremaBy(this, keySelector, comparer); }; /** * Returns the maximum value in an observable sequence according to the specified comparer. * @example * var res = source.max(); * var res = source.max(function (x, y) { return x.value - y.value; }); * @param {Function} [comparer] Comparer used to compare elements. * @returns {Observable} An observable sequence containing a single element with the maximum element in the source sequence. */ observableProto.max = function (comparer) { return this.maxBy(identity, comparer).map(function (x) { return firstOnly(x); }); }; /** * Computes the average of an observable sequence of values that are in the sequence or obtained by invoking a transform function on each element of the input sequence if present. * @param {Function} [selector] A transform function to apply to each element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence containing a single element with the average of the sequence of values. */ observableProto.average = function (keySelector, thisArg) { return keySelector && isFunction(keySelector) ? this.map(keySelector, thisArg).average() : this.reduce(function (prev, cur) { return { sum: prev.sum + cur, count: prev.count + 1 }; }, {sum: 0, count: 0 }).map(function (s) { if (s.count === 0) { throw new EmptyError(); } return s.sum / s.count; }); }; /** * Determines whether two sequences are equal by comparing the elements pairwise using a specified equality comparer. * * @example * var res = res = source.sequenceEqual([1,2,3]); * var res = res = source.sequenceEqual([{ value: 42 }], function (x, y) { return x.value === y.value; }); * 3 - res = source.sequenceEqual(Rx.Observable.returnValue(42)); * 4 - res = source.sequenceEqual(Rx.Observable.returnValue({ value: 42 }), function (x, y) { return x.value === y.value; }); * @param {Observable} second Second observable sequence or array to compare. * @param {Function} [comparer] Comparer used to compare elements of both sequences. * @returns {Observable} An observable sequence that contains a single element which indicates whether both sequences are of equal length and their corresponding elements are equal according to the specified equality comparer. */ observableProto.sequenceEqual = function (second, comparer) { var first = this; comparer || (comparer = defaultComparer); return new AnonymousObservable(function (o) { var donel = false, doner = false, ql = [], qr = []; var subscription1 = first.subscribe(function (x) { var equal, v; if (qr.length > 0) { v = qr.shift(); try { equal = comparer(v, x); } catch (e) { o.onError(e); return; } if (!equal) { o.onNext(false); o.onCompleted(); } } else if (doner) { o.onNext(false); o.onCompleted(); } else { ql.push(x); } }, function(e) { o.onError(e); }, function () { donel = true; if (ql.length === 0) { if (qr.length > 0) { o.onNext(false); o.onCompleted(); } else if (doner) { o.onNext(true); o.onCompleted(); } } }); (isArrayLike(second) || isIterable(second)) && (second = observableFrom(second)); isPromise(second) && (second = observableFromPromise(second)); var subscription2 = second.subscribe(function (x) { var equal; if (ql.length > 0) { var v = ql.shift(); try { equal = comparer(v, x); } catch (exception) { o.onError(exception); return; } if (!equal) { o.onNext(false); o.onCompleted(); } } else if (donel) { o.onNext(false); o.onCompleted(); } else { qr.push(x); } }, function(e) { o.onError(e); }, function () { doner = true; if (qr.length === 0) { if (ql.length > 0) { o.onNext(false); o.onCompleted(); } else if (donel) { o.onNext(true); o.onCompleted(); } } }); return new CompositeDisposable(subscription1, subscription2); }, first); }; function elementAtOrDefault(source, index, hasDefault, defaultValue) { if (index < 0) { throw new ArgumentOutOfRangeError(); } return new AnonymousObservable(function (o) { var i = index; return source.subscribe(function (x) { if (i-- === 0) { o.onNext(x); o.onCompleted(); } }, function (e) { o.onError(e); }, function () { if (!hasDefault) { o.onError(new ArgumentOutOfRangeError()); } else { o.onNext(defaultValue); o.onCompleted(); } }); }, source); } /** * Returns the element at a specified index in a sequence. * @example * var res = source.elementAt(5); * @param {Number} index The zero-based index of the element to retrieve. * @returns {Observable} An observable sequence that produces the element at the specified position in the source sequence. */ observableProto.elementAt = function (index) { return elementAtOrDefault(this, index, false); }; /** * Returns the element at a specified index in a sequence or a default value if the index is out of range. * @example * var res = source.elementAtOrDefault(5); * var res = source.elementAtOrDefault(5, 0); * @param {Number} index The zero-based index of the element to retrieve. * @param [defaultValue] The default value if the index is outside the bounds of the source sequence. * @returns {Observable} An observable sequence that produces the element at the specified position in the source sequence, or a default value if the index is outside the bounds of the source sequence. */ observableProto.elementAtOrDefault = function (index, defaultValue) { return elementAtOrDefault(this, index, true, defaultValue); }; function singleOrDefaultAsync(source, hasDefault, defaultValue) { return new AnonymousObservable(function (o) { var value = defaultValue, seenValue = false; return source.subscribe(function (x) { if (seenValue) { o.onError(new Error('Sequence contains more than one element')); } else { value = x; seenValue = true; } }, function (e) { o.onError(e); }, function () { if (!seenValue && !hasDefault) { o.onError(new EmptyError()); } else { o.onNext(value); o.onCompleted(); } }); }, source); } /** * Returns the only element of an observable sequence that satisfies the condition in the optional predicate, and reports an exception if there is not exactly one element in the observable sequence. * @param {Function} [predicate] A predicate function to evaluate for elements in the source sequence. * @param {Any} [thisArg] Object to use as `this` when executing the predicate. * @returns {Observable} Sequence containing the single element in the observable sequence that satisfies the condition in the predicate. */ observableProto.single = function (predicate, thisArg) { return predicate && isFunction(predicate) ? this.where(predicate, thisArg).single() : singleOrDefaultAsync(this, false); }; /** * Returns the only element of an observable sequence that matches the predicate, or a default value if no such element exists; this method reports an exception if there is more than one element in the observable sequence. * @example * var res = res = source.singleOrDefault(); * var res = res = source.singleOrDefault(function (x) { return x === 42; }); * res = source.singleOrDefault(function (x) { return x === 42; }, 0); * res = source.singleOrDefault(null, 0); * @memberOf Observable# * @param {Function} predicate A predicate function to evaluate for elements in the source sequence. * @param [defaultValue] The default value if the index is outside the bounds of the source sequence. * @param {Any} [thisArg] Object to use as `this` when executing the predicate. * @returns {Observable} Sequence containing the single element in the observable sequence that satisfies the condition in the predicate, or a default value if no such element exists. */ observableProto.singleOrDefault = function (predicate, defaultValue, thisArg) { return predicate && isFunction(predicate) ? this.filter(predicate, thisArg).singleOrDefault(null, defaultValue) : singleOrDefaultAsync(this, true, defaultValue); }; function firstOrDefaultAsync(source, hasDefault, defaultValue) { return new AnonymousObservable(function (o) { return source.subscribe(function (x) { o.onNext(x); o.onCompleted(); }, function (e) { o.onError(e); }, function () { if (!hasDefault) { o.onError(new EmptyError()); } else { o.onNext(defaultValue); o.onCompleted(); } }); }, source); } /** * Returns the first element of an observable sequence that satisfies the condition in the predicate if present else the first item in the sequence. * @example * var res = res = source.first(); * var res = res = source.first(function (x) { return x > 3; }); * @param {Function} [predicate] A predicate function to evaluate for elements in the source sequence. * @param {Any} [thisArg] Object to use as `this` when executing the predicate. * @returns {Observable} Sequence containing the first element in the observable sequence that satisfies the condition in the predicate if provided, else the first item in the sequence. */ observableProto.first = function (predicate, thisArg) { return predicate ? this.where(predicate, thisArg).first() : firstOrDefaultAsync(this, false); }; /** * Returns the first element of an observable sequence that satisfies the condition in the predicate, or a default value if no such element exists. * @param {Function} [predicate] A predicate function to evaluate for elements in the source sequence. * @param {Any} [defaultValue] The default value if no such element exists. If not specified, defaults to null. * @param {Any} [thisArg] Object to use as `this` when executing the predicate. * @returns {Observable} Sequence containing the first element in the observable sequence that satisfies the condition in the predicate, or a default value if no such element exists. */ observableProto.firstOrDefault = function (predicate, defaultValue, thisArg) { return predicate ? this.where(predicate).firstOrDefault(null, defaultValue) : firstOrDefaultAsync(this, true, defaultValue); }; function lastOrDefaultAsync(source, hasDefault, defaultValue) { return new AnonymousObservable(function (o) { var value = defaultValue, seenValue = false; return source.subscribe(function (x) { value = x; seenValue = true; }, function (e) { o.onError(e); }, function () { if (!seenValue && !hasDefault) { o.onError(new EmptyError()); } else { o.onNext(value); o.onCompleted(); } }); }, source); } /** * Returns the last element of an observable sequence that satisfies the condition in the predicate if specified, else the last element. * @param {Function} [predicate] A predicate function to evaluate for elements in the source sequence. * @param {Any} [thisArg] Object to use as `this` when executing the predicate. * @returns {Observable} Sequence containing the last element in the observable sequence that satisfies the condition in the predicate. */ observableProto.last = function (predicate, thisArg) { return predicate ? this.where(predicate, thisArg).last() : lastOrDefaultAsync(this, false); }; /** * Returns the last element of an observable sequence that satisfies the condition in the predicate, or a default value if no such element exists. * @param {Function} [predicate] A predicate function to evaluate for elements in the source sequence. * @param [defaultValue] The default value if no such element exists. If not specified, defaults to null. * @param {Any} [thisArg] Object to use as `this` when executing the predicate. * @returns {Observable} Sequence containing the last element in the observable sequence that satisfies the condition in the predicate, or a default value if no such element exists. */ observableProto.lastOrDefault = function (predicate, defaultValue, thisArg) { return predicate ? this.where(predicate, thisArg).lastOrDefault(null, defaultValue) : lastOrDefaultAsync(this, true, defaultValue); }; function findValue (source, predicate, thisArg, yieldIndex) { var callback = bindCallback(predicate, thisArg, 3); return new AnonymousObservable(function (o) { var i = 0; return source.subscribe(function (x) { var shouldRun; try { shouldRun = callback(x, i, source); } catch (e) { o.onError(e); return; } if (shouldRun) { o.onNext(yieldIndex ? i : x); o.onCompleted(); } else { i++; } }, function (e) { o.onError(e); }, function () { o.onNext(yieldIndex ? -1 : undefined); o.onCompleted(); }); }, source); } /** * Searches for an element that matches the conditions defined by the specified predicate, and returns the first occurrence within the entire Observable sequence. * @param {Function} predicate The predicate that defines the conditions of the element to search for. * @param {Any} [thisArg] Object to use as `this` when executing the predicate. * @returns {Observable} An Observable sequence with the first element that matches the conditions defined by the specified predicate, if found; otherwise, undefined. */ observableProto.find = function (predicate, thisArg) { return findValue(this, predicate, thisArg, false); }; /** * Searches for an element that matches the conditions defined by the specified predicate, and returns * an Observable sequence with the zero-based index of the first occurrence within the entire Observable sequence. * @param {Function} predicate The predicate that defines the conditions of the element to search for. * @param {Any} [thisArg] Object to use as `this` when executing the predicate. * @returns {Observable} An Observable sequence with the zero-based index of the first occurrence of an element that matches the conditions defined by match, if found; otherwise, –1. */ observableProto.findIndex = function (predicate, thisArg) { return findValue(this, predicate, thisArg, true); }; /** * Converts the observable sequence to a Set if it exists. * @returns {Observable} An observable sequence with a single value of a Set containing the values from the observable sequence. */ observableProto.toSet = function () { if (typeof root.Set === 'undefined') { throw new TypeError(); } var source = this; return new AnonymousObservable(function (o) { var s = new root.Set(); return source.subscribe( function (x) { s.add(x); }, function (e) { o.onError(e); }, function () { o.onNext(s); o.onCompleted(); }); }, source); }; /** * Converts the observable sequence to a Map if it exists. * @param {Function} keySelector A function which produces the key for the Map. * @param {Function} [elementSelector] An optional function which produces the element for the Map. If not present, defaults to the value from the observable sequence. * @returns {Observable} An observable sequence with a single value of a Map containing the values from the observable sequence. */ observableProto.toMap = function (keySelector, elementSelector) { if (typeof root.Map === 'undefined') { throw new TypeError(); } var source = this; return new AnonymousObservable(function (o) { var m = new root.Map(); return source.subscribe( function (x) { var key; try { key = keySelector(x); } catch (e) { o.onError(e); return; } var element = x; if (elementSelector) { try { element = elementSelector(x); } catch (e) { o.onError(e); return; } } m.set(key, element); }, function (e) { o.onError(e); }, function () { o.onNext(m); o.onCompleted(); }); }, source); }; var fnString = 'function', throwString = 'throw', isObject = Rx.internals.isObject; function toThunk(obj, ctx) { if (Array.isArray(obj)) { return objectToThunk.call(ctx, obj); } if (isGeneratorFunction(obj)) { return observableSpawn(obj.call(ctx)); } if (isGenerator(obj)) { return observableSpawn(obj); } if (isObservable(obj)) { return observableToThunk(obj); } if (isPromise(obj)) { return promiseToThunk(obj); } if (typeof obj === fnString) { return obj; } if (isObject(obj) || Array.isArray(obj)) { return objectToThunk.call(ctx, obj); } return obj; } function objectToThunk(obj) { var ctx = this; return function (done) { var keys = Object.keys(obj), pending = keys.length, results = new obj.constructor(), finished; if (!pending) { timeoutScheduler.schedule(function () { done(null, results); }); return; } for (var i = 0, len = keys.length; i < len; i++) { run(obj[keys[i]], keys[i]); } function run(fn, key) { if (finished) { return; } try { fn = toThunk(fn, ctx); if (typeof fn !== fnString) { results[key] = fn; return --pending || done(null, results); } fn.call(ctx, function(err, res) { if (finished) { return; } if (err) { finished = true; return done(err); } results[key] = res; --pending || done(null, results); }); } catch (e) { finished = true; done(e); } } } } function observableToThunk(observable) { return function (fn) { var value, hasValue = false; observable.subscribe( function (v) { value = v; hasValue = true; }, fn, function () { hasValue && fn(null, value); }); } } function promiseToThunk(promise) { return function(fn) { promise.then(function(res) { fn(null, res); }, fn); } } function isObservable(obj) { return obj && typeof obj.subscribe === fnString; } function isGeneratorFunction(obj) { return obj && obj.constructor && obj.constructor.name === 'GeneratorFunction'; } function isGenerator(obj) { return obj && typeof obj.next === fnString && typeof obj[throwString] === fnString; } /* * Spawns a generator function which allows for Promises, Observable sequences, Arrays, Objects, Generators and functions. * @param {Function} The spawning function. * @returns {Function} a function which has a done continuation. */ var observableSpawn = Rx.spawn = function (fn) { var isGenFun = isGeneratorFunction(fn); return function (done) { var ctx = this, gen = fn; if (isGenFun) { for(var args = [], i = 0, len = arguments.length; i < len; i++) { args.push(arguments[i]); } var len = args.length, hasCallback = len && typeof args[len - 1] === fnString; done = hasCallback ? args.pop() : handleError; gen = fn.apply(this, args); } else { done = done || handleError; } next(); function exit(err, res) { timeoutScheduler.schedule(done.bind(ctx, err, res)); } function next(err, res) { var ret; // multiple args if (arguments.length > 2) { for(var res = [], i = 1, len = arguments.length; i < len; i++) { res.push(arguments[i]); } } if (err) { try { ret = gen[throwString](err); } catch (e) { return exit(e); } } if (!err) { try { ret = gen.next(res); } catch (e) { return exit(e); } } if (ret.done) { return exit(null, ret.value); } ret.value = toThunk(ret.value, ctx); if (typeof ret.value === fnString) { var called = false; try { ret.value.call(ctx, function() { if (called) { return; } called = true; next.apply(ctx, arguments); }); } catch (e) { timeoutScheduler.schedule(function () { if (called) { return; } called = true; next.call(ctx, e); }); } return; } // Not supported next(new TypeError('Rx.spawn only supports a function, Promise, Observable, Object or Array.')); } } }; function handleError(err) { if (!err) { return; } timeoutScheduler.schedule(function() { throw err; }); } /** * Invokes the specified function asynchronously on the specified scheduler, surfacing the result through an observable sequence. * * @example * var res = Rx.Observable.start(function () { console.log('hello'); }); * var res = Rx.Observable.start(function () { console.log('hello'); }, Rx.Scheduler.timeout); * var res = Rx.Observable.start(function () { this.log('hello'); }, Rx.Scheduler.timeout, console); * * @param {Function} func Function to run asynchronously. * @param {Scheduler} [scheduler] Scheduler to run the function on. If not specified, defaults to Scheduler.timeout. * @param [context] The context for the func parameter to be executed. If not specified, defaults to undefined. * @returns {Observable} An observable sequence exposing the function's result value, or an exception. * * Remarks * * The function is called immediately, not during the subscription of the resulting sequence. * * Multiple subscriptions to the resulting sequence can observe the function's result. */ Observable.start = function (func, context, scheduler) { return observableToAsync(func, context, scheduler)(); }; /** * Converts the function into an asynchronous function. Each invocation of the resulting asynchronous function causes an invocation of the original synchronous function on the specified scheduler. * @param {Function} function Function to convert to an asynchronous function. * @param {Scheduler} [scheduler] Scheduler to run the function on. If not specified, defaults to Scheduler.timeout. * @param {Mixed} [context] The context for the func parameter to be executed. If not specified, defaults to undefined. * @returns {Function} Asynchronous function. */ var observableToAsync = Observable.toAsync = function (func, context, scheduler) { isScheduler(scheduler) || (scheduler = timeoutScheduler); return function () { var args = arguments, subject = new AsyncSubject(); scheduler.schedule(function () { var result; try { result = func.apply(context, args); } catch (e) { subject.onError(e); return; } subject.onNext(result); subject.onCompleted(); }); return subject.asObservable(); }; }; /** * Converts a callback function to an observable sequence. * * @param {Function} function Function with a callback as the last parameter to convert to an Observable sequence. * @param {Mixed} [context] The context for the func parameter to be executed. If not specified, defaults to undefined. * @param {Function} [selector] A selector which takes the arguments from the callback to produce a single item to yield on next. * @returns {Function} A function, when executed with the required parameters minus the callback, produces an Observable sequence with a single value of the arguments to the callback as an array. */ Observable.fromCallback = function (func, context, selector) { return function () { var len = arguments.length, args = new Array(len) for(var i = 0; i < len; i++) { args[i] = arguments[i]; } return new AnonymousObservable(function (observer) { function handler() { var len = arguments.length, results = new Array(len); for(var i = 0; i < len; i++) { results[i] = arguments[i]; } if (selector) { try { results = selector.apply(context, results); } catch (e) { return observer.onError(e); } observer.onNext(results); } else { if (results.length <= 1) { observer.onNext.apply(observer, results); } else { observer.onNext(results); } } observer.onCompleted(); } args.push(handler); func.apply(context, args); }).publishLast().refCount(); }; }; /** * Converts a Node.js callback style function to an observable sequence. This must be in function (err, ...) format. * @param {Function} func The function to call * @param {Mixed} [context] The context for the func parameter to be executed. If not specified, defaults to undefined. * @param {Function} [selector] A selector which takes the arguments from the callback minus the error to produce a single item to yield on next. * @returns {Function} An async function which when applied, returns an observable sequence with the callback arguments as an array. */ Observable.fromNodeCallback = function (func, context, selector) { return function () { var len = arguments.length, args = new Array(len); for(var i = 0; i < len; i++) { args[i] = arguments[i]; } return new AnonymousObservable(function (observer) { function handler(err) { if (err) { observer.onError(err); return; } var len = arguments.length, results = []; for(var i = 1; i < len; i++) { results[i - 1] = arguments[i]; } if (selector) { try { results = selector.apply(context, results); } catch (e) { return observer.onError(e); } observer.onNext(results); } else { if (results.length <= 1) { observer.onNext.apply(observer, results); } else { observer.onNext(results); } } observer.onCompleted(); } args.push(handler); func.apply(context, args); }).publishLast().refCount(); }; }; function createListener (element, name, handler) { if (element.addEventListener) { element.addEventListener(name, handler, false); return disposableCreate(function () { element.removeEventListener(name, handler, false); }); } throw new Error('No listener found'); } function createEventListener (el, eventName, handler) { var disposables = new CompositeDisposable(); // Asume NodeList or HTMLCollection var toStr = Object.prototype.toString; if (toStr.call(el) === '[object NodeList]' || toStr.call(el) === '[object HTMLCollection]') { for (var i = 0, len = el.length; i < len; i++) { disposables.add(createEventListener(el.item(i), eventName, handler)); } } else if (el) { disposables.add(createListener(el, eventName, handler)); } return disposables; } /** * Configuration option to determine whether to use native events only */ Rx.config.useNativeEvents = false; /** * Creates an observable sequence by adding an event listener to the matching DOMElement or each item in the NodeList. * * @example * var source = Rx.Observable.fromEvent(element, 'mouseup'); * * @param {Object} element The DOMElement or NodeList to attach a listener. * @param {String} eventName The event name to attach the observable sequence. * @param {Function} [selector] A selector which takes the arguments from the event handler to produce a single item to yield on next. * @returns {Observable} An observable sequence of events from the specified element and the specified event. */ Observable.fromEvent = function (element, eventName, selector) { // Node.js specific if (element.addListener) { return fromEventPattern( function (h) { element.addListener(eventName, h); }, function (h) { element.removeListener(eventName, h); }, selector); } // Use only if non-native events are allowed if (!Rx.config.useNativeEvents) { // Handles jq, Angular.js, Zepto, Marionette, Ember.js if (typeof element.on === 'function' && typeof element.off === 'function') { return fromEventPattern( function (h) { element.on(eventName, h); }, function (h) { element.off(eventName, h); }, selector); } } return new AnonymousObservable(function (observer) { return createEventListener( element, eventName, function handler (e) { var results = e; if (selector) { try { results = selector(arguments); } catch (err) { return observer.onError(err); } } observer.onNext(results); }); }).publish().refCount(); }; /** * Creates an observable sequence from an event emitter via an addHandler/removeHandler pair. * @param {Function} addHandler The function to add a handler to the emitter. * @param {Function} [removeHandler] The optional function to remove a handler from an emitter. * @param {Function} [selector] A selector which takes the arguments from the event handler to produce a single item to yield on next. * @returns {Observable} An observable sequence which wraps an event from an event emitter */ var fromEventPattern = Observable.fromEventPattern = function (addHandler, removeHandler, selector) { return new AnonymousObservable(function (observer) { function innerHandler (e) { var result = e; if (selector) { try { result = selector(arguments); } catch (err) { return observer.onError(err); } } observer.onNext(result); } var returnValue = addHandler(innerHandler); return disposableCreate(function () { if (removeHandler) { removeHandler(innerHandler, returnValue); } }); }).publish().refCount(); }; /** * Invokes the asynchronous function, surfacing the result through an observable sequence. * @param {Function} functionAsync Asynchronous function which returns a Promise to run. * @returns {Observable} An observable sequence exposing the function's result value, or an exception. */ Observable.startAsync = function (functionAsync) { var promise; try { promise = functionAsync(); } catch (e) { return observableThrow(e); } return observableFromPromise(promise); } var PausableObservable = (function (__super__) { inherits(PausableObservable, __super__); function subscribe(observer) { var conn = this.source.publish(), subscription = conn.subscribe(observer), connection = disposableEmpty; var pausable = this.pauser.distinctUntilChanged().subscribe(function (b) { if (b) { connection = conn.connect(); } else { connection.dispose(); connection = disposableEmpty; } }); return new CompositeDisposable(subscription, connection, pausable); } function PausableObservable(source, pauser) { this.source = source; this.controller = new Subject(); if (pauser && pauser.subscribe) { this.pauser = this.controller.merge(pauser); } else { this.pauser = this.controller; } __super__.call(this, subscribe, source); } PausableObservable.prototype.pause = function () { this.controller.onNext(false); }; PausableObservable.prototype.resume = function () { this.controller.onNext(true); }; return PausableObservable; }(Observable)); /** * Pauses the underlying observable sequence based upon the observable sequence which yields true/false. * @example * var pauser = new Rx.Subject(); * var source = Rx.Observable.interval(100).pausable(pauser); * @param {Observable} pauser The observable sequence used to pause the underlying sequence. * @returns {Observable} The observable sequence which is paused based upon the pauser. */ observableProto.pausable = function (pauser) { return new PausableObservable(this, pauser); }; function combineLatestSource(source, subject, resultSelector) { return new AnonymousObservable(function (o) { var hasValue = [false, false], hasValueAll = false, isDone = false, values = new Array(2), err; function next(x, i) { values[i] = x hasValue[i] = true; if (hasValueAll || (hasValueAll = hasValue.every(identity))) { if (err) { return o.onError(err); } var res = tryCatch(resultSelector).apply(null, values); if (res === errorObj) { return o.onError(res.e); } o.onNext(res); } isDone && values[1] && o.onCompleted(); } return new CompositeDisposable( source.subscribe( function (x) { next(x, 0); }, function (e) { if (values[1]) { o.onError(e); } else { err = e; } }, function () { isDone = true; values[1] && o.onCompleted(); }), subject.subscribe( function (x) { next(x, 1); }, function (e) { o.onError(e); }, function () { isDone = true; next(true, 1); }) ); }, source); } var PausableBufferedObservable = (function (__super__) { inherits(PausableBufferedObservable, __super__); function subscribe(o) { var q = [], previousShouldFire; function drainQueue() { while (q.length > 0) { o.onNext(q.shift()); } } var subscription = combineLatestSource( this.source, this.pauser.distinctUntilChanged().startWith(false), function (data, shouldFire) { return { data: data, shouldFire: shouldFire }; }) .subscribe( function (results) { if (previousShouldFire !== undefined && results.shouldFire != previousShouldFire) { previousShouldFire = results.shouldFire; // change in shouldFire if (results.shouldFire) { drainQueue(); } } else { previousShouldFire = results.shouldFire; // new data if (results.shouldFire) { o.onNext(results.data); } else { q.push(results.data); } } }, function (err) { drainQueue(); o.onError(err); }, function () { drainQueue(); o.onCompleted(); } ); return subscription; } function PausableBufferedObservable(source, pauser) { this.source = source; this.controller = new Subject(); if (pauser && pauser.subscribe) { this.pauser = this.controller.merge(pauser); } else { this.pauser = this.controller; } __super__.call(this, subscribe, source); } PausableBufferedObservable.prototype.pause = function () { this.controller.onNext(false); }; PausableBufferedObservable.prototype.resume = function () { this.controller.onNext(true); }; return PausableBufferedObservable; }(Observable)); /** * Pauses the underlying observable sequence based upon the observable sequence which yields true/false, * and yields the values that were buffered while paused. * @example * var pauser = new Rx.Subject(); * var source = Rx.Observable.interval(100).pausableBuffered(pauser); * @param {Observable} pauser The observable sequence used to pause the underlying sequence. * @returns {Observable} The observable sequence which is paused based upon the pauser. */ observableProto.pausableBuffered = function (subject) { return new PausableBufferedObservable(this, subject); }; var ControlledObservable = (function (__super__) { inherits(ControlledObservable, __super__); function subscribe (observer) { return this.source.subscribe(observer); } function ControlledObservable (source, enableQueue, scheduler) { __super__.call(this, subscribe, source); this.subject = new ControlledSubject(enableQueue, scheduler); this.source = source.multicast(this.subject).refCount(); } ControlledObservable.prototype.request = function (numberOfItems) { return this.subject.request(numberOfItems == null ? -1 : numberOfItems); }; return ControlledObservable; }(Observable)); var ControlledSubject = (function (__super__) { function subscribe (observer) { return this.subject.subscribe(observer); } inherits(ControlledSubject, __super__); function ControlledSubject(enableQueue, scheduler) { enableQueue == null && (enableQueue = true); __super__.call(this, subscribe); this.subject = new Subject(); this.enableQueue = enableQueue; this.queue = enableQueue ? [] : null; this.requestedCount = 0; this.requestedDisposable = disposableEmpty; this.error = null; this.hasFailed = false; this.hasCompleted = false; this.scheduler = scheduler || currentThreadScheduler; } addProperties(ControlledSubject.prototype, Observer, { onCompleted: function () { this.hasCompleted = true; if (!this.enableQueue || this.queue.length === 0) { this.subject.onCompleted(); } else { this.queue.push(Notification.createOnCompleted()); } }, onError: function (error) { this.hasFailed = true; this.error = error; if (!this.enableQueue || this.queue.length === 0) { this.subject.onError(error); } else { this.queue.push(Notification.createOnError(error)); } }, onNext: function (value) { var hasRequested = false; if (this.requestedCount === 0) { this.enableQueue && this.queue.push(Notification.createOnNext(value)); } else { (this.requestedCount !== -1 && this.requestedCount-- === 0) && this.disposeCurrentRequest(); hasRequested = true; } hasRequested && this.subject.onNext(value); }, _processRequest: function (numberOfItems) { if (this.enableQueue) { while ((this.queue.length >= numberOfItems && numberOfItems > 0) || (this.queue.length > 0 && this.queue[0].kind !== 'N')) { var first = this.queue.shift(); first.accept(this.subject); if (first.kind === 'N') { numberOfItems--; } else { this.disposeCurrentRequest(); this.queue = []; } } return { numberOfItems : numberOfItems, returnValue: this.queue.length !== 0}; } return { numberOfItems: numberOfItems, returnValue: false }; }, request: function (number) { this.disposeCurrentRequest(); var self = this; this.requestedDisposable = this.scheduler.scheduleWithState(number, function(s, i) { var r = self._processRequest(i), remaining = r.numberOfItems; if (!r.returnValue) { self.requestedCount = remaining; self.requestedDisposable = disposableCreate(function () { self.requestedCount = 0; }); } }); return this.requestedDisposable; }, disposeCurrentRequest: function () { this.requestedDisposable.dispose(); this.requestedDisposable = disposableEmpty; } }); return ControlledSubject; }(Observable)); /** * Attaches a controller to the observable sequence with the ability to queue. * @example * var source = Rx.Observable.interval(100).controlled(); * source.request(3); // Reads 3 values * @param {bool} enableQueue truthy value to determine if values should be queued pending the next request * @param {Scheduler} scheduler determines how the requests will be scheduled * @returns {Observable} The observable sequence which only propagates values on request. */ observableProto.controlled = function (enableQueue, scheduler) { if (enableQueue && isScheduler(enableQueue)) { scheduler = enableQueue; enableQueue = true; } if (enableQueue == null) { enableQueue = true; } return new ControlledObservable(this, enableQueue, scheduler); }; var StopAndWaitObservable = (function (__super__) { function subscribe (observer) { this.subscription = this.source.subscribe(new StopAndWaitObserver(observer, this, this.subscription)); var self = this; timeoutScheduler.schedule(function () { self.source.request(1); }); return this.subscription; } inherits(StopAndWaitObservable, __super__); function StopAndWaitObservable (source) { __super__.call(this, subscribe, source); this.source = source; } var StopAndWaitObserver = (function (__sub__) { inherits(StopAndWaitObserver, __sub__); function StopAndWaitObserver (observer, observable, cancel) { __sub__.call(this); this.observer = observer; this.observable = observable; this.cancel = cancel; } var stopAndWaitObserverProto = StopAndWaitObserver.prototype; stopAndWaitObserverProto.completed = function () { this.observer.onCompleted(); this.dispose(); }; stopAndWaitObserverProto.error = function (error) { this.observer.onError(error); this.dispose(); } stopAndWaitObserverProto.next = function (value) { this.observer.onNext(value); var self = this; timeoutScheduler.schedule(function () { self.observable.source.request(1); }); }; stopAndWaitObserverProto.dispose = function () { this.observer = null; if (this.cancel) { this.cancel.dispose(); this.cancel = null; } __sub__.prototype.dispose.call(this); }; return StopAndWaitObserver; }(AbstractObserver)); return StopAndWaitObservable; }(Observable)); /** * Attaches a stop and wait observable to the current observable. * @returns {Observable} A stop and wait observable. */ ControlledObservable.prototype.stopAndWait = function () { return new StopAndWaitObservable(this); }; var WindowedObservable = (function (__super__) { function subscribe (observer) { this.subscription = this.source.subscribe(new WindowedObserver(observer, this, this.subscription)); var self = this; timeoutScheduler.schedule(function () { self.source.request(self.windowSize); }); return this.subscription; } inherits(WindowedObservable, __super__); function WindowedObservable(source, windowSize) { __super__.call(this, subscribe, source); this.source = source; this.windowSize = windowSize; } var WindowedObserver = (function (__sub__) { inherits(WindowedObserver, __sub__); function WindowedObserver(observer, observable, cancel) { this.observer = observer; this.observable = observable; this.cancel = cancel; this.received = 0; } var windowedObserverPrototype = WindowedObserver.prototype; windowedObserverPrototype.completed = function () { this.observer.onCompleted(); this.dispose(); }; windowedObserverPrototype.error = function (error) { this.observer.onError(error); this.dispose(); }; windowedObserverPrototype.next = function (value) { this.observer.onNext(value); this.received = ++this.received % this.observable.windowSize; if (this.received === 0) { var self = this; timeoutScheduler.schedule(function () { self.observable.source.request(self.observable.windowSize); }); } }; windowedObserverPrototype.dispose = function () { this.observer = null; if (this.cancel) { this.cancel.dispose(); this.cancel = null; } __sub__.prototype.dispose.call(this); }; return WindowedObserver; }(AbstractObserver)); return WindowedObservable; }(Observable)); /** * Creates a sliding windowed observable based upon the window size. * @param {Number} windowSize The number of items in the window * @returns {Observable} A windowed observable based upon the window size. */ ControlledObservable.prototype.windowed = function (windowSize) { return new WindowedObservable(this, windowSize); }; /** * Pipes the existing Observable sequence into a Node.js Stream. * @param {Stream} dest The destination Node.js stream. * @returns {Stream} The destination stream. */ observableProto.pipe = function (dest) { var source = this.pausableBuffered(); function onDrain() { source.resume(); } dest.addListener('drain', onDrain); source.subscribe( function (x) { !dest.write(String(x)) && source.pause(); }, function (err) { dest.emit('error', err); }, function () { // Hack check because STDIO is not closable !dest._isStdio && dest.end(); dest.removeListener('drain', onDrain); }); source.resume(); return dest; }; /** * Multicasts the source sequence notifications through an instantiated subject into all uses of the sequence within a selector function. Each * subscription to the resulting sequence causes a separate multicast invocation, exposing the sequence resulting from the selector function's * invocation. For specializations with fixed subject types, see Publish, PublishLast, and Replay. * * @example * 1 - res = source.multicast(observable); * 2 - res = source.multicast(function () { return new Subject(); }, function (x) { return x; }); * * @param {Function|Subject} subjectOrSubjectSelector * Factory function to create an intermediate subject through which the source sequence's elements will be multicast to the selector function. * Or: * Subject to push source elements into. * * @param {Function} [selector] Optional selector function which can use the multicasted source sequence subject to the policies enforced by the created subject. Specified only if <paramref name="subjectOrSubjectSelector" is a factory function. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. */ observableProto.multicast = function (subjectOrSubjectSelector, selector) { var source = this; return typeof subjectOrSubjectSelector === 'function' ? new AnonymousObservable(function (observer) { var connectable = source.multicast(subjectOrSubjectSelector()); return new CompositeDisposable(selector(connectable).subscribe(observer), connectable.connect()); }, source) : new ConnectableObservable(source, subjectOrSubjectSelector); }; /** * Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence. * This operator is a specialization of Multicast using a regular Subject. * * @example * var resres = source.publish(); * var res = source.publish(function (x) { return x; }); * * @param {Function} [selector] Selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will receive all notifications of the source from the time of the subscription on. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. */ observableProto.publish = function (selector) { return selector && isFunction(selector) ? this.multicast(function () { return new Subject(); }, selector) : this.multicast(new Subject()); }; /** * Returns an observable sequence that shares a single subscription to the underlying sequence. * This operator is a specialization of publish which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence. */ observableProto.share = function () { return this.publish().refCount(); }; /** * Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence containing only the last notification. * This operator is a specialization of Multicast using a AsyncSubject. * * @example * var res = source.publishLast(); * var res = source.publishLast(function (x) { return x; }); * * @param selector [Optional] Selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will only receive the last notification of the source. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. */ observableProto.publishLast = function (selector) { return selector && isFunction(selector) ? this.multicast(function () { return new AsyncSubject(); }, selector) : this.multicast(new AsyncSubject()); }; /** * Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence and starts with initialValue. * This operator is a specialization of Multicast using a BehaviorSubject. * * @example * var res = source.publishValue(42); * var res = source.publishValue(function (x) { return x.select(function (y) { return y * y; }) }, 42); * * @param {Function} [selector] Optional selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will receive immediately receive the initial value, followed by all notifications of the source from the time of the subscription on. * @param {Mixed} initialValue Initial value received by observers upon subscription. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. */ observableProto.publishValue = function (initialValueOrSelector, initialValue) { return arguments.length === 2 ? this.multicast(function () { return new BehaviorSubject(initialValue); }, initialValueOrSelector) : this.multicast(new BehaviorSubject(initialValueOrSelector)); }; /** * Returns an observable sequence that shares a single subscription to the underlying sequence and starts with an initialValue. * This operator is a specialization of publishValue which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed. * @param {Mixed} initialValue Initial value received by observers upon subscription. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence. */ observableProto.shareValue = function (initialValue) { return this.publishValue(initialValue).refCount(); }; /** * Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence replaying notifications subject to a maximum time length for the replay buffer. * This operator is a specialization of Multicast using a ReplaySubject. * * @example * var res = source.replay(null, 3); * var res = source.replay(null, 3, 500); * var res = source.replay(null, 3, 500, scheduler); * var res = source.replay(function (x) { return x.take(6).repeat(); }, 3, 500, scheduler); * * @param selector [Optional] Selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will receive all the notifications of the source subject to the specified replay buffer trimming policy. * @param bufferSize [Optional] Maximum element count of the replay buffer. * @param windowSize [Optional] Maximum time length of the replay buffer. * @param scheduler [Optional] Scheduler where connected observers within the selector function will be invoked on. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. */ observableProto.replay = function (selector, bufferSize, windowSize, scheduler) { return selector && isFunction(selector) ? this.multicast(function () { return new ReplaySubject(bufferSize, windowSize, scheduler); }, selector) : this.multicast(new ReplaySubject(bufferSize, windowSize, scheduler)); }; /** * Returns an observable sequence that shares a single subscription to the underlying sequence replaying notifications subject to a maximum time length for the replay buffer. * This operator is a specialization of replay which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed. * * @example * var res = source.shareReplay(3); * var res = source.shareReplay(3, 500); * var res = source.shareReplay(3, 500, scheduler); * * @param bufferSize [Optional] Maximum element count of the replay buffer. * @param window [Optional] Maximum time length of the replay buffer. * @param scheduler [Optional] Scheduler where connected observers within the selector function will be invoked on. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence. */ observableProto.shareReplay = function (bufferSize, windowSize, scheduler) { return this.replay(null, bufferSize, windowSize, scheduler).refCount(); }; var InnerSubscription = function (subject, observer) { this.subject = subject; this.observer = observer; }; InnerSubscription.prototype.dispose = function () { if (!this.subject.isDisposed && this.observer !== null) { var idx = this.subject.observers.indexOf(this.observer); this.subject.observers.splice(idx, 1); this.observer = null; } }; /** * Represents a value that changes over time. * Observers can subscribe to the subject to receive the last (or initial) value and all subsequent notifications. */ var BehaviorSubject = Rx.BehaviorSubject = (function (__super__) { function subscribe(observer) { checkDisposed(this); if (!this.isStopped) { this.observers.push(observer); observer.onNext(this.value); return new InnerSubscription(this, observer); } if (this.hasError) { observer.onError(this.error); } else { observer.onCompleted(); } return disposableEmpty; } inherits(BehaviorSubject, __super__); /** * Initializes a new instance of the BehaviorSubject class which creates a subject that caches its last value and starts with the specified value. * @param {Mixed} value Initial value sent to observers when no other value has been received by the subject yet. */ function BehaviorSubject(value) { __super__.call(this, subscribe); this.value = value, this.observers = [], this.isDisposed = false, this.isStopped = false, this.hasError = false; } addProperties(BehaviorSubject.prototype, Observer, { /** * Gets the current value or throws an exception. * Value is frozen after onCompleted is called. * After onError is called always throws the specified exception. * An exception is always thrown after dispose is called. * @returns {Mixed} The initial value passed to the constructor until onNext is called; after which, the last value passed to onNext. */ getValue: function () { checkDisposed(this); if (this.hasError) { throw this.error; } return this.value; }, /** * Indicates whether the subject has observers subscribed to it. * @returns {Boolean} Indicates whether the subject has observers subscribed to it. */ hasObservers: function () { return this.observers.length > 0; }, /** * Notifies all subscribed observers about the end of the sequence. */ onCompleted: function () { checkDisposed(this); if (this.isStopped) { return; } this.isStopped = true; for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) { os[i].onCompleted(); } this.observers.length = 0; }, /** * Notifies all subscribed observers about the exception. * @param {Mixed} error The exception to send to all observers. */ onError: function (error) { checkDisposed(this); if (this.isStopped) { return; } this.isStopped = true; this.hasError = true; this.error = error; for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) { os[i].onError(error); } this.observers.length = 0; }, /** * Notifies all subscribed observers about the arrival of the specified element in the sequence. * @param {Mixed} value The value to send to all observers. */ onNext: function (value) { checkDisposed(this); if (this.isStopped) { return; } this.value = value; for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) { os[i].onNext(value); } }, /** * Unsubscribe all observers and release resources. */ dispose: function () { this.isDisposed = true; this.observers = null; this.value = null; this.exception = null; } }); return BehaviorSubject; }(Observable)); /** * Represents an object that is both an observable sequence as well as an observer. * Each notification is broadcasted to all subscribed and future observers, subject to buffer trimming policies. */ var ReplaySubject = Rx.ReplaySubject = (function (__super__) { var maxSafeInteger = Math.pow(2, 53) - 1; function createRemovableDisposable(subject, observer) { return disposableCreate(function () { observer.dispose(); !subject.isDisposed && subject.observers.splice(subject.observers.indexOf(observer), 1); }); } function subscribe(observer) { var so = new ScheduledObserver(this.scheduler, observer), subscription = createRemovableDisposable(this, so); checkDisposed(this); this._trim(this.scheduler.now()); this.observers.push(so); for (var i = 0, len = this.q.length; i < len; i++) { so.onNext(this.q[i].value); } if (this.hasError) { so.onError(this.error); } else if (this.isStopped) { so.onCompleted(); } so.ensureActive(); return subscription; } inherits(ReplaySubject, __super__); /** * Initializes a new instance of the ReplaySubject class with the specified buffer size, window size and scheduler. * @param {Number} [bufferSize] Maximum element count of the replay buffer. * @param {Number} [windowSize] Maximum time length of the replay buffer. * @param {Scheduler} [scheduler] Scheduler the observers are invoked on. */ function ReplaySubject(bufferSize, windowSize, scheduler) { this.bufferSize = bufferSize == null ? maxSafeInteger : bufferSize; this.windowSize = windowSize == null ? maxSafeInteger : windowSize; this.scheduler = scheduler || currentThreadScheduler; this.q = []; this.observers = []; this.isStopped = false; this.isDisposed = false; this.hasError = false; this.error = null; __super__.call(this, subscribe); } addProperties(ReplaySubject.prototype, Observer.prototype, { /** * Indicates whether the subject has observers subscribed to it. * @returns {Boolean} Indicates whether the subject has observers subscribed to it. */ hasObservers: function () { return this.observers.length > 0; }, _trim: function (now) { while (this.q.length > this.bufferSize) { this.q.shift(); } while (this.q.length > 0 && (now - this.q[0].interval) > this.windowSize) { this.q.shift(); } }, /** * Notifies all subscribed observers about the arrival of the specified element in the sequence. * @param {Mixed} value The value to send to all observers. */ onNext: function (value) { checkDisposed(this); if (this.isStopped) { return; } var now = this.scheduler.now(); this.q.push({ interval: now, value: value }); this._trim(now); for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) { var observer = os[i]; observer.onNext(value); observer.ensureActive(); } }, /** * Notifies all subscribed observers about the exception. * @param {Mixed} error The exception to send to all observers. */ onError: function (error) { checkDisposed(this); if (this.isStopped) { return; } this.isStopped = true; this.error = error; this.hasError = true; var now = this.scheduler.now(); this._trim(now); for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) { var observer = os[i]; observer.onError(error); observer.ensureActive(); } this.observers.length = 0; }, /** * Notifies all subscribed observers about the end of the sequence. */ onCompleted: function () { checkDisposed(this); if (this.isStopped) { return; } this.isStopped = true; var now = this.scheduler.now(); this._trim(now); for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) { var observer = os[i]; observer.onCompleted(); observer.ensureActive(); } this.observers.length = 0; }, /** * Unsubscribe all observers and release resources. */ dispose: function () { this.isDisposed = true; this.observers = null; } }); return ReplaySubject; }(Observable)); var ConnectableObservable = Rx.ConnectableObservable = (function (__super__) { inherits(ConnectableObservable, __super__); function ConnectableObservable(source, subject) { var hasSubscription = false, subscription, sourceObservable = source.asObservable(); this.connect = function () { if (!hasSubscription) { hasSubscription = true; subscription = new CompositeDisposable(sourceObservable.subscribe(subject), disposableCreate(function () { hasSubscription = false; })); } return subscription; }; __super__.call(this, function (o) { return subject.subscribe(o); }); } ConnectableObservable.prototype.refCount = function () { var connectableSubscription, count = 0, source = this; return new AnonymousObservable(function (observer) { var shouldConnect = ++count === 1, subscription = source.subscribe(observer); shouldConnect && (connectableSubscription = source.connect()); return function () { subscription.dispose(); --count === 0 && connectableSubscription.dispose(); }; }); }; return ConnectableObservable; }(Observable)); /** * Returns an observable sequence that shares a single subscription to the underlying sequence. This observable sequence * can be resubscribed to, even if all prior subscriptions have ended. (unlike `.publish().refCount()`) * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source. */ observableProto.singleInstance = function() { var source = this, hasObservable = false, observable; function getObservable() { if (!hasObservable) { hasObservable = true; observable = source.finally(function() { hasObservable = false; }).publish().refCount(); } return observable; }; return new AnonymousObservable(function(o) { return getObservable().subscribe(o); }); }; var Dictionary = (function () { var primes = [1, 3, 7, 13, 31, 61, 127, 251, 509, 1021, 2039, 4093, 8191, 16381, 32749, 65521, 131071, 262139, 524287, 1048573, 2097143, 4194301, 8388593, 16777213, 33554393, 67108859, 134217689, 268435399, 536870909, 1073741789, 2147483647], noSuchkey = "no such key", duplicatekey = "duplicate key"; function isPrime(candidate) { if ((candidate & 1) === 0) { return candidate === 2; } var num1 = Math.sqrt(candidate), num2 = 3; while (num2 <= num1) { if (candidate % num2 === 0) { return false; } num2 += 2; } return true; } function getPrime(min) { var index, num, candidate; for (index = 0; index < primes.length; ++index) { num = primes[index]; if (num >= min) { return num; } } candidate = min | 1; while (candidate < primes[primes.length - 1]) { if (isPrime(candidate)) { return candidate; } candidate += 2; } return min; } function stringHashFn(str) { var hash = 757602046; if (!str.length) { return hash; } for (var i = 0, len = str.length; i < len; i++) { var character = str.charCodeAt(i); hash = ((hash << 5) - hash) + character; hash = hash & hash; } return hash; } function numberHashFn(key) { var c2 = 0x27d4eb2d; key = (key ^ 61) ^ (key >>> 16); key = key + (key << 3); key = key ^ (key >>> 4); key = key * c2; key = key ^ (key >>> 15); return key; } var getHashCode = (function () { var uniqueIdCounter = 0; return function (obj) { if (obj == null) { throw new Error(noSuchkey); } // Check for built-ins before tacking on our own for any object if (typeof obj === 'string') { return stringHashFn(obj); } if (typeof obj === 'number') { return numberHashFn(obj); } if (typeof obj === 'boolean') { return obj === true ? 1 : 0; } if (obj instanceof Date) { return numberHashFn(obj.valueOf()); } if (obj instanceof RegExp) { return stringHashFn(obj.toString()); } if (typeof obj.valueOf === 'function') { // Hack check for valueOf var valueOf = obj.valueOf(); if (typeof valueOf === 'number') { return numberHashFn(valueOf); } if (typeof valueOf === 'string') { return stringHashFn(valueOf); } } if (obj.hashCode) { return obj.hashCode(); } var id = 17 * uniqueIdCounter++; obj.hashCode = function () { return id; }; return id; }; }()); function newEntry() { return { key: null, value: null, next: 0, hashCode: 0 }; } function Dictionary(capacity, comparer) { if (capacity < 0) { throw new ArgumentOutOfRangeError(); } if (capacity > 0) { this._initialize(capacity); } this.comparer = comparer || defaultComparer; this.freeCount = 0; this.size = 0; this.freeList = -1; } var dictionaryProto = Dictionary.prototype; dictionaryProto._initialize = function (capacity) { var prime = getPrime(capacity), i; this.buckets = new Array(prime); this.entries = new Array(prime); for (i = 0; i < prime; i++) { this.buckets[i] = -1; this.entries[i] = newEntry(); } this.freeList = -1; }; dictionaryProto.add = function (key, value) { this._insert(key, value, true); }; dictionaryProto._insert = function (key, value, add) { if (!this.buckets) { this._initialize(0); } var index3, num = getHashCode(key) & 2147483647, index1 = num % this.buckets.length; for (var index2 = this.buckets[index1]; index2 >= 0; index2 = this.entries[index2].next) { if (this.entries[index2].hashCode === num && this.comparer(this.entries[index2].key, key)) { if (add) { throw new Error(duplicatekey); } this.entries[index2].value = value; return; } } if (this.freeCount > 0) { index3 = this.freeList; this.freeList = this.entries[index3].next; --this.freeCount; } else { if (this.size === this.entries.length) { this._resize(); index1 = num % this.buckets.length; } index3 = this.size; ++this.size; } this.entries[index3].hashCode = num; this.entries[index3].next = this.buckets[index1]; this.entries[index3].key = key; this.entries[index3].value = value; this.buckets[index1] = index3; }; dictionaryProto._resize = function () { var prime = getPrime(this.size * 2), numArray = new Array(prime); for (index = 0; index < numArray.length; ++index) { numArray[index] = -1; } var entryArray = new Array(prime); for (index = 0; index < this.size; ++index) { entryArray[index] = this.entries[index]; } for (var index = this.size; index < prime; ++index) { entryArray[index] = newEntry(); } for (var index1 = 0; index1 < this.size; ++index1) { var index2 = entryArray[index1].hashCode % prime; entryArray[index1].next = numArray[index2]; numArray[index2] = index1; } this.buckets = numArray; this.entries = entryArray; }; dictionaryProto.remove = function (key) { if (this.buckets) { var num = getHashCode(key) & 2147483647, index1 = num % this.buckets.length, index2 = -1; for (var index3 = this.buckets[index1]; index3 >= 0; index3 = this.entries[index3].next) { if (this.entries[index3].hashCode === num && this.comparer(this.entries[index3].key, key)) { if (index2 < 0) { this.buckets[index1] = this.entries[index3].next; } else { this.entries[index2].next = this.entries[index3].next; } this.entries[index3].hashCode = -1; this.entries[index3].next = this.freeList; this.entries[index3].key = null; this.entries[index3].value = null; this.freeList = index3; ++this.freeCount; return true; } else { index2 = index3; } } } return false; }; dictionaryProto.clear = function () { var index, len; if (this.size <= 0) { return; } for (index = 0, len = this.buckets.length; index < len; ++index) { this.buckets[index] = -1; } for (index = 0; index < this.size; ++index) { this.entries[index] = newEntry(); } this.freeList = -1; this.size = 0; }; dictionaryProto._findEntry = function (key) { if (this.buckets) { var num = getHashCode(key) & 2147483647; for (var index = this.buckets[num % this.buckets.length]; index >= 0; index = this.entries[index].next) { if (this.entries[index].hashCode === num && this.comparer(this.entries[index].key, key)) { return index; } } } return -1; }; dictionaryProto.count = function () { return this.size - this.freeCount; }; dictionaryProto.tryGetValue = function (key) { var entry = this._findEntry(key); return entry >= 0 ? this.entries[entry].value : undefined; }; dictionaryProto.getValues = function () { var index = 0, results = []; if (this.entries) { for (var index1 = 0; index1 < this.size; index1++) { if (this.entries[index1].hashCode >= 0) { results[index++] = this.entries[index1].value; } } } return results; }; dictionaryProto.get = function (key) { var entry = this._findEntry(key); if (entry >= 0) { return this.entries[entry].value; } throw new Error(noSuchkey); }; dictionaryProto.set = function (key, value) { this._insert(key, value, false); }; dictionaryProto.containskey = function (key) { return this._findEntry(key) >= 0; }; return Dictionary; }()); /** * Correlates the elements of two sequences based on overlapping durations. * * @param {Observable} right The right observable sequence to join elements for. * @param {Function} leftDurationSelector A function to select the duration (expressed as an observable sequence) of each element of the left observable sequence, used to determine overlap. * @param {Function} rightDurationSelector A function to select the duration (expressed as an observable sequence) of each element of the right observable sequence, used to determine overlap. * @param {Function} resultSelector A function invoked to compute a result element for any two overlapping elements of the left and right observable sequences. The parameters passed to the function correspond with the elements from the left and right source sequences for which overlap occurs. * @returns {Observable} An observable sequence that contains result elements computed from source elements that have an overlapping duration. */ observableProto.join = function (right, leftDurationSelector, rightDurationSelector, resultSelector) { var left = this; return new AnonymousObservable(function (observer) { var group = new CompositeDisposable(); var leftDone = false, rightDone = false; var leftId = 0, rightId = 0; var leftMap = new Dictionary(), rightMap = new Dictionary(); group.add(left.subscribe( function (value) { var id = leftId++; var md = new SingleAssignmentDisposable(); leftMap.add(id, value); group.add(md); var expire = function () { leftMap.remove(id) && leftMap.count() === 0 && leftDone && observer.onCompleted(); group.remove(md); }; var duration; try { duration = leftDurationSelector(value); } catch (e) { observer.onError(e); return; } md.setDisposable(duration.take(1).subscribe(noop, observer.onError.bind(observer), expire)); rightMap.getValues().forEach(function (v) { var result; try { result = resultSelector(value, v); } catch (exn) { observer.onError(exn); return; } observer.onNext(result); }); }, observer.onError.bind(observer), function () { leftDone = true; (rightDone || leftMap.count() === 0) && observer.onCompleted(); }) ); group.add(right.subscribe( function (value) { var id = rightId++; var md = new SingleAssignmentDisposable(); rightMap.add(id, value); group.add(md); var expire = function () { rightMap.remove(id) && rightMap.count() === 0 && rightDone && observer.onCompleted(); group.remove(md); }; var duration; try { duration = rightDurationSelector(value); } catch (e) { observer.onError(e); return; } md.setDisposable(duration.take(1).subscribe(noop, observer.onError.bind(observer), expire)); leftMap.getValues().forEach(function (v) { var result; try { result = resultSelector(v, value); } catch (exn) { observer.onError(exn); return; } observer.onNext(result); }); }, observer.onError.bind(observer), function () { rightDone = true; (leftDone || rightMap.count() === 0) && observer.onCompleted(); }) ); return group; }, left); }; /** * Correlates the elements of two sequences based on overlapping durations, and groups the results. * * @param {Observable} right The right observable sequence to join elements for. * @param {Function} leftDurationSelector A function to select the duration (expressed as an observable sequence) of each element of the left observable sequence, used to determine overlap. * @param {Function} rightDurationSelector A function to select the duration (expressed as an observable sequence) of each element of the right observable sequence, used to determine overlap. * @param {Function} resultSelector A function invoked to compute a result element for any element of the left sequence with overlapping elements from the right observable sequence. The first parameter passed to the function is an element of the left sequence. The second parameter passed to the function is an observable sequence with elements from the right sequence that overlap with the left sequence's element. * @returns {Observable} An observable sequence that contains result elements computed from source elements that have an overlapping duration. */ observableProto.groupJoin = function (right, leftDurationSelector, rightDurationSelector, resultSelector) { var left = this; return new AnonymousObservable(function (observer) { var group = new CompositeDisposable(); var r = new RefCountDisposable(group); var leftMap = new Dictionary(), rightMap = new Dictionary(); var leftId = 0, rightId = 0; function handleError(e) { return function (v) { v.onError(e); }; }; group.add(left.subscribe( function (value) { var s = new Subject(); var id = leftId++; leftMap.add(id, s); var result; try { result = resultSelector(value, addRef(s, r)); } catch (e) { leftMap.getValues().forEach(handleError(e)); observer.onError(e); return; } observer.onNext(result); rightMap.getValues().forEach(function (v) { s.onNext(v); }); var md = new SingleAssignmentDisposable(); group.add(md); var expire = function () { leftMap.remove(id) && s.onCompleted(); group.remove(md); }; var duration; try { duration = leftDurationSelector(value); } catch (e) { leftMap.getValues().forEach(handleError(e)); observer.onError(e); return; } md.setDisposable(duration.take(1).subscribe( noop, function (e) { leftMap.getValues().forEach(handleError(e)); observer.onError(e); }, expire) ); }, function (e) { leftMap.getValues().forEach(handleError(e)); observer.onError(e); }, observer.onCompleted.bind(observer)) ); group.add(right.subscribe( function (value) { var id = rightId++; rightMap.add(id, value); var md = new SingleAssignmentDisposable(); group.add(md); var expire = function () { rightMap.remove(id); group.remove(md); }; var duration; try { duration = rightDurationSelector(value); } catch (e) { leftMap.getValues().forEach(handleError(e)); observer.onError(e); return; } md.setDisposable(duration.take(1).subscribe( noop, function (e) { leftMap.getValues().forEach(handleError(e)); observer.onError(e); }, expire) ); leftMap.getValues().forEach(function (v) { v.onNext(value); }); }, function (e) { leftMap.getValues().forEach(handleError(e)); observer.onError(e); }) ); return r; }, left); }; /** * Projects each element of an observable sequence into zero or more buffers. * * @param {Mixed} bufferOpeningsOrClosingSelector Observable sequence whose elements denote the creation of new windows, or, a function invoked to define the boundaries of the produced windows (a new window is started when the previous one is closed, resulting in non-overlapping windows). * @param {Function} [bufferClosingSelector] A function invoked to define the closing of each produced window. If a closing selector function is specified for the first parameter, this parameter is ignored. * @returns {Observable} An observable sequence of windows. */ observableProto.buffer = function (bufferOpeningsOrClosingSelector, bufferClosingSelector) { return this.window.apply(this, arguments).selectMany(function (x) { return x.toArray(); }); }; /** * Projects each element of an observable sequence into zero or more windows. * * @param {Mixed} windowOpeningsOrClosingSelector Observable sequence whose elements denote the creation of new windows, or, a function invoked to define the boundaries of the produced windows (a new window is started when the previous one is closed, resulting in non-overlapping windows). * @param {Function} [windowClosingSelector] A function invoked to define the closing of each produced window. If a closing selector function is specified for the first parameter, this parameter is ignored. * @returns {Observable} An observable sequence of windows. */ observableProto.window = function (windowOpeningsOrClosingSelector, windowClosingSelector) { if (arguments.length === 1 && typeof arguments[0] !== 'function') { return observableWindowWithBoundaries.call(this, windowOpeningsOrClosingSelector); } return typeof windowOpeningsOrClosingSelector === 'function' ? observableWindowWithClosingSelector.call(this, windowOpeningsOrClosingSelector) : observableWindowWithOpenings.call(this, windowOpeningsOrClosingSelector, windowClosingSelector); }; function observableWindowWithOpenings(windowOpenings, windowClosingSelector) { return windowOpenings.groupJoin(this, windowClosingSelector, observableEmpty, function (_, win) { return win; }); } function observableWindowWithBoundaries(windowBoundaries) { var source = this; return new AnonymousObservable(function (observer) { var win = new Subject(), d = new CompositeDisposable(), r = new RefCountDisposable(d); observer.onNext(addRef(win, r)); d.add(source.subscribe(function (x) { win.onNext(x); }, function (err) { win.onError(err); observer.onError(err); }, function () { win.onCompleted(); observer.onCompleted(); })); isPromise(windowBoundaries) && (windowBoundaries = observableFromPromise(windowBoundaries)); d.add(windowBoundaries.subscribe(function (w) { win.onCompleted(); win = new Subject(); observer.onNext(addRef(win, r)); }, function (err) { win.onError(err); observer.onError(err); }, function () { win.onCompleted(); observer.onCompleted(); })); return r; }, source); } function observableWindowWithClosingSelector(windowClosingSelector) { var source = this; return new AnonymousObservable(function (observer) { var m = new SerialDisposable(), d = new CompositeDisposable(m), r = new RefCountDisposable(d), win = new Subject(); observer.onNext(addRef(win, r)); d.add(source.subscribe(function (x) { win.onNext(x); }, function (err) { win.onError(err); observer.onError(err); }, function () { win.onCompleted(); observer.onCompleted(); })); function createWindowClose () { var windowClose; try { windowClose = windowClosingSelector(); } catch (e) { observer.onError(e); return; } isPromise(windowClose) && (windowClose = observableFromPromise(windowClose)); var m1 = new SingleAssignmentDisposable(); m.setDisposable(m1); m1.setDisposable(windowClose.take(1).subscribe(noop, function (err) { win.onError(err); observer.onError(err); }, function () { win.onCompleted(); win = new Subject(); observer.onNext(addRef(win, r)); createWindowClose(); })); } createWindowClose(); return r; }, source); } /** * Returns a new observable that triggers on the second and subsequent triggerings of the input observable. * The Nth triggering of the input observable passes the arguments from the N-1th and Nth triggering as a pair. * The argument passed to the N-1th triggering is held in hidden internal state until the Nth triggering occurs. * @returns {Observable} An observable that triggers on successive pairs of observations from the input observable as an array. */ observableProto.pairwise = function () { var source = this; return new AnonymousObservable(function (observer) { var previous, hasPrevious = false; return source.subscribe( function (x) { if (hasPrevious) { observer.onNext([previous, x]); } else { hasPrevious = true; } previous = x; }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }, source); }; /** * Returns two observables which partition the observations of the source by the given function. * The first will trigger observations for those values for which the predicate returns true. * The second will trigger observations for those values where the predicate returns false. * The predicate is executed once for each subscribed observer. * Both also propagate all error observations arising from the source and each completes * when the source completes. * @param {Function} predicate * The function to determine which output Observable will trigger a particular observation. * @returns {Array} * An array of observables. The first triggers when the predicate returns true, * and the second triggers when the predicate returns false. */ observableProto.partition = function(predicate, thisArg) { return [ this.filter(predicate, thisArg), this.filter(function (x, i, o) { return !predicate.call(thisArg, x, i, o); }) ]; }; var WhileEnumerable = (function(__super__) { inherits(WhileEnumerable, __super__); function WhileEnumerable(c, s) { this.c = c; this.s = s; } WhileEnumerable.prototype[$iterator$] = function () { var self = this; return { next: function () { return self.c() ? { done: false, value: self.s } : { done: true, value: void 0 }; } }; }; return WhileEnumerable; }(Enumerable)); function enumerableWhile(condition, source) { return new WhileEnumerable(condition, source); } /** * Returns an observable sequence that is the result of invoking the selector on the source sequence, without sharing subscriptions. * This operator allows for a fluent style of writing queries that use the same sequence multiple times. * * @param {Function} selector Selector function which can use the source sequence as many times as needed, without sharing subscriptions to the source sequence. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. */ observableProto.letBind = observableProto['let'] = function (func) { return func(this); }; /** * Determines whether an observable collection contains values. There is an alias for this method called 'ifThen' for browsers <IE9 * * @example * 1 - res = Rx.Observable.if(condition, obs1); * 2 - res = Rx.Observable.if(condition, obs1, obs2); * 3 - res = Rx.Observable.if(condition, obs1, scheduler); * @param {Function} condition The condition which determines if the thenSource or elseSource will be run. * @param {Observable} thenSource The observable sequence or Promise that will be run if the condition function returns true. * @param {Observable} [elseSource] The observable sequence or Promise that will be run if the condition function returns false. If this is not provided, it defaults to Rx.Observabe.Empty with the specified scheduler. * @returns {Observable} An observable sequence which is either the thenSource or elseSource. */ Observable['if'] = Observable.ifThen = function (condition, thenSource, elseSourceOrScheduler) { return observableDefer(function () { elseSourceOrScheduler || (elseSourceOrScheduler = observableEmpty()); isPromise(thenSource) && (thenSource = observableFromPromise(thenSource)); isPromise(elseSourceOrScheduler) && (elseSourceOrScheduler = observableFromPromise(elseSourceOrScheduler)); // Assume a scheduler for empty only typeof elseSourceOrScheduler.now === 'function' && (elseSourceOrScheduler = observableEmpty(elseSourceOrScheduler)); return condition() ? thenSource : elseSourceOrScheduler; }); }; /** * Concatenates the observable sequences obtained by running the specified result selector for each element in source. * There is an alias for this method called 'forIn' for browsers <IE9 * @param {Array} sources An array of values to turn into an observable sequence. * @param {Function} resultSelector A function to apply to each item in the sources array to turn it into an observable sequence. * @returns {Observable} An observable sequence from the concatenated observable sequences. */ Observable['for'] = Observable.forIn = function (sources, resultSelector, thisArg) { return enumerableOf(sources, resultSelector, thisArg).concat(); }; /** * Repeats source as long as condition holds emulating a while loop. * There is an alias for this method called 'whileDo' for browsers <IE9 * * @param {Function} condition The condition which determines if the source will be repeated. * @param {Observable} source The observable sequence that will be run if the condition function returns true. * @returns {Observable} An observable sequence which is repeated as long as the condition holds. */ var observableWhileDo = Observable['while'] = Observable.whileDo = function (condition, source) { isPromise(source) && (source = observableFromPromise(source)); return enumerableWhile(condition, source).concat(); }; /** * Repeats source as long as condition holds emulating a do while loop. * * @param {Function} condition The condition which determines if the source will be repeated. * @param {Observable} source The observable sequence that will be run if the condition function returns true. * @returns {Observable} An observable sequence which is repeated as long as the condition holds. */ observableProto.doWhile = function (condition) { return observableConcat([this, observableWhileDo(condition, this)]); }; /** * Uses selector to determine which source in sources to use. * There is an alias 'switchCase' for browsers <IE9. * * @example * 1 - res = Rx.Observable.case(selector, { '1': obs1, '2': obs2 }); * 1 - res = Rx.Observable.case(selector, { '1': obs1, '2': obs2 }, obs0); * 1 - res = Rx.Observable.case(selector, { '1': obs1, '2': obs2 }, scheduler); * * @param {Function} selector The function which extracts the value for to test in a case statement. * @param {Array} sources A object which has keys which correspond to the case statement labels. * @param {Observable} [elseSource] The observable sequence or Promise that will be run if the sources are not matched. If this is not provided, it defaults to Rx.Observabe.empty with the specified scheduler. * * @returns {Observable} An observable sequence which is determined by a case statement. */ Observable['case'] = Observable.switchCase = function (selector, sources, defaultSourceOrScheduler) { return observableDefer(function () { isPromise(defaultSourceOrScheduler) && (defaultSourceOrScheduler = observableFromPromise(defaultSourceOrScheduler)); defaultSourceOrScheduler || (defaultSourceOrScheduler = observableEmpty()); typeof defaultSourceOrScheduler.now === 'function' && (defaultSourceOrScheduler = observableEmpty(defaultSourceOrScheduler)); var result = sources[selector()]; isPromise(result) && (result = observableFromPromise(result)); return result || defaultSourceOrScheduler; }); }; /** * Expands an observable sequence by recursively invoking selector. * * @param {Function} selector Selector function to invoke for each produced element, resulting in another sequence to which the selector will be invoked recursively again. * @param {Scheduler} [scheduler] Scheduler on which to perform the expansion. If not provided, this defaults to the current thread scheduler. * @returns {Observable} An observable sequence containing all the elements produced by the recursive expansion. */ observableProto.expand = function (selector, scheduler) { isScheduler(scheduler) || (scheduler = immediateScheduler); var source = this; return new AnonymousObservable(function (observer) { var q = [], m = new SerialDisposable(), d = new CompositeDisposable(m), activeCount = 0, isAcquired = false; var ensureActive = function () { var isOwner = false; if (q.length > 0) { isOwner = !isAcquired; isAcquired = true; } if (isOwner) { m.setDisposable(scheduler.scheduleRecursive(function (self) { var work; if (q.length > 0) { work = q.shift(); } else { isAcquired = false; return; } var m1 = new SingleAssignmentDisposable(); d.add(m1); m1.setDisposable(work.subscribe(function (x) { observer.onNext(x); var result = null; try { result = selector(x); } catch (e) { observer.onError(e); } q.push(result); activeCount++; ensureActive(); }, observer.onError.bind(observer), function () { d.remove(m1); activeCount--; if (activeCount === 0) { observer.onCompleted(); } })); self(); })); } }; q.push(source); activeCount++; ensureActive(); return d; }, this); }; /** * Runs all observable sequences in parallel and collect their last elements. * * @example * 1 - res = Rx.Observable.forkJoin([obs1, obs2]); * 1 - res = Rx.Observable.forkJoin(obs1, obs2, ...); * @returns {Observable} An observable sequence with an array collecting the last elements of all the input sequences. */ Observable.forkJoin = function () { var allSources = []; if (Array.isArray(arguments[0])) { allSources = arguments[0]; } else { for(var i = 0, len = arguments.length; i < len; i++) { allSources.push(arguments[i]); } } return new AnonymousObservable(function (subscriber) { var count = allSources.length; if (count === 0) { subscriber.onCompleted(); return disposableEmpty; } var group = new CompositeDisposable(), finished = false, hasResults = new Array(count), hasCompleted = new Array(count), results = new Array(count); for (var idx = 0; idx < count; idx++) { (function (i) { var source = allSources[i]; isPromise(source) && (source = observableFromPromise(source)); group.add( source.subscribe( function (value) { if (!finished) { hasResults[i] = true; results[i] = value; } }, function (e) { finished = true; subscriber.onError(e); group.dispose(); }, function () { if (!finished) { if (!hasResults[i]) { subscriber.onCompleted(); return; } hasCompleted[i] = true; for (var ix = 0; ix < count; ix++) { if (!hasCompleted[ix]) { return; } } finished = true; subscriber.onNext(results); subscriber.onCompleted(); } })); })(idx); } return group; }); }; /** * Runs two observable sequences in parallel and combines their last elemenets. * * @param {Observable} second Second observable sequence. * @param {Function} resultSelector Result selector function to invoke with the last elements of both sequences. * @returns {Observable} An observable sequence with the result of calling the selector function with the last elements of both input sequences. */ observableProto.forkJoin = function (second, resultSelector) { var first = this; return new AnonymousObservable(function (observer) { var leftStopped = false, rightStopped = false, hasLeft = false, hasRight = false, lastLeft, lastRight, leftSubscription = new SingleAssignmentDisposable(), rightSubscription = new SingleAssignmentDisposable(); isPromise(second) && (second = observableFromPromise(second)); leftSubscription.setDisposable( first.subscribe(function (left) { hasLeft = true; lastLeft = left; }, function (err) { rightSubscription.dispose(); observer.onError(err); }, function () { leftStopped = true; if (rightStopped) { if (!hasLeft) { observer.onCompleted(); } else if (!hasRight) { observer.onCompleted(); } else { var result; try { result = resultSelector(lastLeft, lastRight); } catch (e) { observer.onError(e); return; } observer.onNext(result); observer.onCompleted(); } } }) ); rightSubscription.setDisposable( second.subscribe(function (right) { hasRight = true; lastRight = right; }, function (err) { leftSubscription.dispose(); observer.onError(err); }, function () { rightStopped = true; if (leftStopped) { if (!hasLeft) { observer.onCompleted(); } else if (!hasRight) { observer.onCompleted(); } else { var result; try { result = resultSelector(lastLeft, lastRight); } catch (e) { observer.onError(e); return; } observer.onNext(result); observer.onCompleted(); } } }) ); return new CompositeDisposable(leftSubscription, rightSubscription); }, first); }; /** * Comonadic bind operator. * @param {Function} selector A transform function to apply to each element. * @param {Object} scheduler Scheduler used to execute the operation. If not specified, defaults to the ImmediateScheduler. * @returns {Observable} An observable sequence which results from the comonadic bind operation. */ observableProto.manySelect = observableProto.extend = function (selector, scheduler) { isScheduler(scheduler) || (scheduler = immediateScheduler); var source = this; return observableDefer(function () { var chain; return source .map(function (x) { var curr = new ChainObservable(x); chain && chain.onNext(x); chain = curr; return curr; }) .tap( noop, function (e) { chain && chain.onError(e); }, function () { chain && chain.onCompleted(); } ) .observeOn(scheduler) .map(selector); }, source); }; var ChainObservable = (function (__super__) { function subscribe (observer) { var self = this, g = new CompositeDisposable(); g.add(currentThreadScheduler.schedule(function () { observer.onNext(self.head); g.add(self.tail.mergeAll().subscribe(observer)); })); return g; } inherits(ChainObservable, __super__); function ChainObservable(head) { __super__.call(this, subscribe); this.head = head; this.tail = new AsyncSubject(); } addProperties(ChainObservable.prototype, Observer, { onCompleted: function () { this.onNext(Observable.empty()); }, onError: function (e) { this.onNext(Observable.throwError(e)); }, onNext: function (v) { this.tail.onNext(v); this.tail.onCompleted(); } }); return ChainObservable; }(Observable)); /** @private */ var Map = root.Map || (function () { function Map() { this._keys = []; this._values = []; } Map.prototype.get = function (key) { var i = this._keys.indexOf(key); return i !== -1 ? this._values[i] : undefined; }; Map.prototype.set = function (key, value) { var i = this._keys.indexOf(key); i !== -1 && (this._values[i] = value); this._values[this._keys.push(key) - 1] = value; }; Map.prototype.forEach = function (callback, thisArg) { for (var i = 0, len = this._keys.length; i < len; i++) { callback.call(thisArg, this._values[i], this._keys[i]); } }; return Map; }()); /** * @constructor * Represents a join pattern over observable sequences. */ function Pattern(patterns) { this.patterns = patterns; } /** * Creates a pattern that matches the current plan matches and when the specified observable sequences has an available value. * @param other Observable sequence to match in addition to the current pattern. * @return {Pattern} Pattern object that matches when all observable sequences in the pattern have an available value. */ Pattern.prototype.and = function (other) { return new Pattern(this.patterns.concat(other)); }; /** * Matches when all observable sequences in the pattern (specified using a chain of and operators) have an available value and projects the values. * @param {Function} selector Selector that will be invoked with available values from the source sequences, in the same order of the sequences in the pattern. * @return {Plan} Plan that produces the projected values, to be fed (with other plans) to the when operator. */ Pattern.prototype.thenDo = function (selector) { return new Plan(this, selector); }; function Plan(expression, selector) { this.expression = expression; this.selector = selector; } Plan.prototype.activate = function (externalSubscriptions, observer, deactivate) { var self = this; var joinObservers = []; for (var i = 0, len = this.expression.patterns.length; i < len; i++) { joinObservers.push(planCreateObserver(externalSubscriptions, this.expression.patterns[i], observer.onError.bind(observer))); } var activePlan = new ActivePlan(joinObservers, function () { var result; try { result = self.selector.apply(self, arguments); } catch (e) { observer.onError(e); return; } observer.onNext(result); }, function () { for (var j = 0, jlen = joinObservers.length; j < jlen; j++) { joinObservers[j].removeActivePlan(activePlan); } deactivate(activePlan); }); for (i = 0, len = joinObservers.length; i < len; i++) { joinObservers[i].addActivePlan(activePlan); } return activePlan; }; function planCreateObserver(externalSubscriptions, observable, onError) { var entry = externalSubscriptions.get(observable); if (!entry) { var observer = new JoinObserver(observable, onError); externalSubscriptions.set(observable, observer); return observer; } return entry; } function ActivePlan(joinObserverArray, onNext, onCompleted) { this.joinObserverArray = joinObserverArray; this.onNext = onNext; this.onCompleted = onCompleted; this.joinObservers = new Map(); for (var i = 0, len = this.joinObserverArray.length; i < len; i++) { var joinObserver = this.joinObserverArray[i]; this.joinObservers.set(joinObserver, joinObserver); } } ActivePlan.prototype.dequeue = function () { this.joinObservers.forEach(function (v) { v.queue.shift(); }); }; ActivePlan.prototype.match = function () { var i, len, hasValues = true; for (i = 0, len = this.joinObserverArray.length; i < len; i++) { if (this.joinObserverArray[i].queue.length === 0) { hasValues = false; break; } } if (hasValues) { var firstValues = [], isCompleted = false; for (i = 0, len = this.joinObserverArray.length; i < len; i++) { firstValues.push(this.joinObserverArray[i].queue[0]); this.joinObserverArray[i].queue[0].kind === 'C' && (isCompleted = true); } if (isCompleted) { this.onCompleted(); } else { this.dequeue(); var values = []; for (i = 0, len = firstValues.length; i < firstValues.length; i++) { values.push(firstValues[i].value); } this.onNext.apply(this, values); } } }; var JoinObserver = (function (__super__) { inherits(JoinObserver, __super__); function JoinObserver(source, onError) { __super__.call(this); this.source = source; this.onError = onError; this.queue = []; this.activePlans = []; this.subscription = new SingleAssignmentDisposable(); this.isDisposed = false; } var JoinObserverPrototype = JoinObserver.prototype; JoinObserverPrototype.next = function (notification) { if (!this.isDisposed) { if (notification.kind === 'E') { return this.onError(notification.exception); } this.queue.push(notification); var activePlans = this.activePlans.slice(0); for (var i = 0, len = activePlans.length; i < len; i++) { activePlans[i].match(); } } }; JoinObserverPrototype.error = noop; JoinObserverPrototype.completed = noop; JoinObserverPrototype.addActivePlan = function (activePlan) { this.activePlans.push(activePlan); }; JoinObserverPrototype.subscribe = function () { this.subscription.setDisposable(this.source.materialize().subscribe(this)); }; JoinObserverPrototype.removeActivePlan = function (activePlan) { this.activePlans.splice(this.activePlans.indexOf(activePlan), 1); this.activePlans.length === 0 && this.dispose(); }; JoinObserverPrototype.dispose = function () { __super__.prototype.dispose.call(this); if (!this.isDisposed) { this.isDisposed = true; this.subscription.dispose(); } }; return JoinObserver; } (AbstractObserver)); /** * Creates a pattern that matches when both observable sequences have an available value. * * @param right Observable sequence to match with the current sequence. * @return {Pattern} Pattern object that matches when both observable sequences have an available value. */ observableProto.and = function (right) { return new Pattern([this, right]); }; /** * Matches when the observable sequence has an available value and projects the value. * * @param {Function} selector Selector that will be invoked for values in the source sequence. * @returns {Plan} Plan that produces the projected values, to be fed (with other plans) to the when operator. */ observableProto.thenDo = function (selector) { return new Pattern([this]).thenDo(selector); }; /** * Joins together the results from several patterns. * * @param plans A series of plans (specified as an Array of as a series of arguments) created by use of the Then operator on patterns. * @returns {Observable} Observable sequence with the results form matching several patterns. */ Observable.when = function () { var len = arguments.length, plans; if (Array.isArray(arguments[0])) { plans = arguments[0]; } else { plans = new Array(len); for(var i = 0; i < len; i++) { plans[i] = arguments[i]; } } return new AnonymousObservable(function (o) { var activePlans = [], externalSubscriptions = new Map(); var outObserver = observerCreate( function (x) { o.onNext(x); }, function (err) { externalSubscriptions.forEach(function (v) { v.onError(err); }); o.onError(err); }, function (x) { o.onCompleted(); } ); try { for (var i = 0, len = plans.length; i < len; i++) { activePlans.push(plans[i].activate(externalSubscriptions, outObserver, function (activePlan) { var idx = activePlans.indexOf(activePlan); activePlans.splice(idx, 1); activePlans.length === 0 && o.onCompleted(); })); } } catch (e) { observableThrow(e).subscribe(o); } var group = new CompositeDisposable(); externalSubscriptions.forEach(function (joinObserver) { joinObserver.subscribe(); group.add(joinObserver); }); return group; }); }; function observableTimerDate(dueTime, scheduler) { return new AnonymousObservable(function (observer) { return scheduler.scheduleWithAbsolute(dueTime, function () { observer.onNext(0); observer.onCompleted(); }); }); } function observableTimerDateAndPeriod(dueTime, period, scheduler) { return new AnonymousObservable(function (observer) { var d = dueTime, p = normalizeTime(period); return scheduler.scheduleRecursiveWithAbsoluteAndState(0, d, function (count, self) { if (p > 0) { var now = scheduler.now(); d = d + p; d <= now && (d = now + p); } observer.onNext(count); self(count + 1, d); }); }); } function observableTimerTimeSpan(dueTime, scheduler) { return new AnonymousObservable(function (observer) { return scheduler.scheduleWithRelative(normalizeTime(dueTime), function () { observer.onNext(0); observer.onCompleted(); }); }); } function observableTimerTimeSpanAndPeriod(dueTime, period, scheduler) { return dueTime === period ? new AnonymousObservable(function (observer) { return scheduler.schedulePeriodicWithState(0, period, function (count) { observer.onNext(count); return count + 1; }); }) : observableDefer(function () { return observableTimerDateAndPeriod(scheduler.now() + dueTime, period, scheduler); }); } /** * Returns an observable sequence that produces a value after each period. * * @example * 1 - res = Rx.Observable.interval(1000); * 2 - res = Rx.Observable.interval(1000, Rx.Scheduler.timeout); * * @param {Number} period Period for producing the values in the resulting sequence (specified as an integer denoting milliseconds). * @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, Rx.Scheduler.timeout is used. * @returns {Observable} An observable sequence that produces a value after each period. */ var observableinterval = Observable.interval = function (period, scheduler) { return observableTimerTimeSpanAndPeriod(period, period, isScheduler(scheduler) ? scheduler : timeoutScheduler); }; /** * Returns an observable sequence that produces a value after dueTime has elapsed and then after each period. * @param {Number} dueTime Absolute (specified as a Date object) or relative time (specified as an integer denoting milliseconds) at which to produce the first value. * @param {Mixed} [periodOrScheduler] Period to produce subsequent values (specified as an integer denoting milliseconds), or the scheduler to run the timer on. If not specified, the resulting timer is not recurring. * @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, the timeout scheduler is used. * @returns {Observable} An observable sequence that produces a value after due time has elapsed and then each period. */ var observableTimer = Observable.timer = function (dueTime, periodOrScheduler, scheduler) { var period; isScheduler(scheduler) || (scheduler = timeoutScheduler); if (periodOrScheduler !== undefined && typeof periodOrScheduler === 'number') { period = periodOrScheduler; } else if (isScheduler(periodOrScheduler)) { scheduler = periodOrScheduler; } if (dueTime instanceof Date && period === undefined) { return observableTimerDate(dueTime.getTime(), scheduler); } if (dueTime instanceof Date && period !== undefined) { period = periodOrScheduler; return observableTimerDateAndPeriod(dueTime.getTime(), period, scheduler); } return period === undefined ? observableTimerTimeSpan(dueTime, scheduler) : observableTimerTimeSpanAndPeriod(dueTime, period, scheduler); }; function observableDelayTimeSpan(source, dueTime, scheduler) { return new AnonymousObservable(function (observer) { var active = false, cancelable = new SerialDisposable(), exception = null, q = [], running = false, subscription; subscription = source.materialize().timestamp(scheduler).subscribe(function (notification) { var d, shouldRun; if (notification.value.kind === 'E') { q = []; q.push(notification); exception = notification.value.exception; shouldRun = !running; } else { q.push({ value: notification.value, timestamp: notification.timestamp + dueTime }); shouldRun = !active; active = true; } if (shouldRun) { if (exception !== null) { observer.onError(exception); } else { d = new SingleAssignmentDisposable(); cancelable.setDisposable(d); d.setDisposable(scheduler.scheduleRecursiveWithRelative(dueTime, function (self) { var e, recurseDueTime, result, shouldRecurse; if (exception !== null) { return; } running = true; do { result = null; if (q.length > 0 && q[0].timestamp - scheduler.now() <= 0) { result = q.shift().value; } if (result !== null) { result.accept(observer); } } while (result !== null); shouldRecurse = false; recurseDueTime = 0; if (q.length > 0) { shouldRecurse = true; recurseDueTime = Math.max(0, q[0].timestamp - scheduler.now()); } else { active = false; } e = exception; running = false; if (e !== null) { observer.onError(e); } else if (shouldRecurse) { self(recurseDueTime); } })); } } }); return new CompositeDisposable(subscription, cancelable); }, source); } function observableDelayDate(source, dueTime, scheduler) { return observableDefer(function () { return observableDelayTimeSpan(source, dueTime - scheduler.now(), scheduler); }); } /** * Time shifts the observable sequence by dueTime. The relative time intervals between the values are preserved. * * @example * 1 - res = Rx.Observable.delay(new Date()); * 2 - res = Rx.Observable.delay(new Date(), Rx.Scheduler.timeout); * * 3 - res = Rx.Observable.delay(5000); * 4 - res = Rx.Observable.delay(5000, 1000, Rx.Scheduler.timeout); * @memberOf Observable# * @param {Number} dueTime Absolute (specified as a Date object) or relative time (specified as an integer denoting milliseconds) by which to shift the observable sequence. * @param {Scheduler} [scheduler] Scheduler to run the delay timers on. If not specified, the timeout scheduler is used. * @returns {Observable} Time-shifted sequence. */ observableProto.delay = function (dueTime, scheduler) { isScheduler(scheduler) || (scheduler = timeoutScheduler); return dueTime instanceof Date ? observableDelayDate(this, dueTime.getTime(), scheduler) : observableDelayTimeSpan(this, dueTime, scheduler); }; /** * Ignores values from an observable sequence which are followed by another value before dueTime. * @param {Number} dueTime Duration of the debounce period for each value (specified as an integer denoting milliseconds). * @param {Scheduler} [scheduler] Scheduler to run the debounce timers on. If not specified, the timeout scheduler is used. * @returns {Observable} The debounced sequence. */ observableProto.debounce = observableProto.throttleWithTimeout = function (dueTime, scheduler) { isScheduler(scheduler) || (scheduler = timeoutScheduler); var source = this; return new AnonymousObservable(function (observer) { var cancelable = new SerialDisposable(), hasvalue = false, value, id = 0; var subscription = source.subscribe( function (x) { hasvalue = true; value = x; id++; var currentId = id, d = new SingleAssignmentDisposable(); cancelable.setDisposable(d); d.setDisposable(scheduler.scheduleWithRelative(dueTime, function () { hasvalue && id === currentId && observer.onNext(value); hasvalue = false; })); }, function (e) { cancelable.dispose(); observer.onError(e); hasvalue = false; id++; }, function () { cancelable.dispose(); hasvalue && observer.onNext(value); observer.onCompleted(); hasvalue = false; id++; }); return new CompositeDisposable(subscription, cancelable); }, this); }; /** * @deprecated use #debounce or #throttleWithTimeout instead. */ observableProto.throttle = function(dueTime, scheduler) { //deprecate('throttle', 'debounce or throttleWithTimeout'); return this.debounce(dueTime, scheduler); }; /** * Projects each element of an observable sequence into zero or more windows which are produced based on timing information. * @param {Number} timeSpan Length of each window (specified as an integer denoting milliseconds). * @param {Mixed} [timeShiftOrScheduler] Interval between creation of consecutive windows (specified as an integer denoting milliseconds), or an optional scheduler parameter. If not specified, the time shift corresponds to the timeSpan parameter, resulting in non-overlapping adjacent windows. * @param {Scheduler} [scheduler] Scheduler to run windowing timers on. If not specified, the timeout scheduler is used. * @returns {Observable} An observable sequence of windows. */ observableProto.windowWithTime = function (timeSpan, timeShiftOrScheduler, scheduler) { var source = this, timeShift; timeShiftOrScheduler == null && (timeShift = timeSpan); isScheduler(scheduler) || (scheduler = timeoutScheduler); if (typeof timeShiftOrScheduler === 'number') { timeShift = timeShiftOrScheduler; } else if (isScheduler(timeShiftOrScheduler)) { timeShift = timeSpan; scheduler = timeShiftOrScheduler; } return new AnonymousObservable(function (observer) { var groupDisposable, nextShift = timeShift, nextSpan = timeSpan, q = [], refCountDisposable, timerD = new SerialDisposable(), totalTime = 0; groupDisposable = new CompositeDisposable(timerD), refCountDisposable = new RefCountDisposable(groupDisposable); function createTimer () { var m = new SingleAssignmentDisposable(), isSpan = false, isShift = false; timerD.setDisposable(m); if (nextSpan === nextShift) { isSpan = true; isShift = true; } else if (nextSpan < nextShift) { isSpan = true; } else { isShift = true; } var newTotalTime = isSpan ? nextSpan : nextShift, ts = newTotalTime - totalTime; totalTime = newTotalTime; if (isSpan) { nextSpan += timeShift; } if (isShift) { nextShift += timeShift; } m.setDisposable(scheduler.scheduleWithRelative(ts, function () { if (isShift) { var s = new Subject(); q.push(s); observer.onNext(addRef(s, refCountDisposable)); } isSpan && q.shift().onCompleted(); createTimer(); })); }; q.push(new Subject()); observer.onNext(addRef(q[0], refCountDisposable)); createTimer(); groupDisposable.add(source.subscribe( function (x) { for (var i = 0, len = q.length; i < len; i++) { q[i].onNext(x); } }, function (e) { for (var i = 0, len = q.length; i < len; i++) { q[i].onError(e); } observer.onError(e); }, function () { for (var i = 0, len = q.length; i < len; i++) { q[i].onCompleted(); } observer.onCompleted(); } )); return refCountDisposable; }, source); }; /** * Projects each element of an observable sequence into a window that is completed when either it's full or a given amount of time has elapsed. * @param {Number} timeSpan Maximum time length of a window. * @param {Number} count Maximum element count of a window. * @param {Scheduler} [scheduler] Scheduler to run windowing timers on. If not specified, the timeout scheduler is used. * @returns {Observable} An observable sequence of windows. */ observableProto.windowWithTimeOrCount = function (timeSpan, count, scheduler) { var source = this; isScheduler(scheduler) || (scheduler = timeoutScheduler); return new AnonymousObservable(function (observer) { var timerD = new SerialDisposable(), groupDisposable = new CompositeDisposable(timerD), refCountDisposable = new RefCountDisposable(groupDisposable), n = 0, windowId = 0, s = new Subject(); function createTimer(id) { var m = new SingleAssignmentDisposable(); timerD.setDisposable(m); m.setDisposable(scheduler.scheduleWithRelative(timeSpan, function () { if (id !== windowId) { return; } n = 0; var newId = ++windowId; s.onCompleted(); s = new Subject(); observer.onNext(addRef(s, refCountDisposable)); createTimer(newId); })); } observer.onNext(addRef(s, refCountDisposable)); createTimer(0); groupDisposable.add(source.subscribe( function (x) { var newId = 0, newWindow = false; s.onNext(x); if (++n === count) { newWindow = true; n = 0; newId = ++windowId; s.onCompleted(); s = new Subject(); observer.onNext(addRef(s, refCountDisposable)); } newWindow && createTimer(newId); }, function (e) { s.onError(e); observer.onError(e); }, function () { s.onCompleted(); observer.onCompleted(); } )); return refCountDisposable; }, source); }; /** * Projects each element of an observable sequence into zero or more buffers which are produced based on timing information. * * @example * 1 - res = xs.bufferWithTime(1000, scheduler); // non-overlapping segments of 1 second * 2 - res = xs.bufferWithTime(1000, 500, scheduler; // segments of 1 second with time shift 0.5 seconds * * @param {Number} timeSpan Length of each buffer (specified as an integer denoting milliseconds). * @param {Mixed} [timeShiftOrScheduler] Interval between creation of consecutive buffers (specified as an integer denoting milliseconds), or an optional scheduler parameter. If not specified, the time shift corresponds to the timeSpan parameter, resulting in non-overlapping adjacent buffers. * @param {Scheduler} [scheduler] Scheduler to run buffer timers on. If not specified, the timeout scheduler is used. * @returns {Observable} An observable sequence of buffers. */ observableProto.bufferWithTime = function (timeSpan, timeShiftOrScheduler, scheduler) { return this.windowWithTime.apply(this, arguments).selectMany(function (x) { return x.toArray(); }); }; /** * Projects each element of an observable sequence into a buffer that is completed when either it's full or a given amount of time has elapsed. * * @example * 1 - res = source.bufferWithTimeOrCount(5000, 50); // 5s or 50 items in an array * 2 - res = source.bufferWithTimeOrCount(5000, 50, scheduler); // 5s or 50 items in an array * * @param {Number} timeSpan Maximum time length of a buffer. * @param {Number} count Maximum element count of a buffer. * @param {Scheduler} [scheduler] Scheduler to run bufferin timers on. If not specified, the timeout scheduler is used. * @returns {Observable} An observable sequence of buffers. */ observableProto.bufferWithTimeOrCount = function (timeSpan, count, scheduler) { return this.windowWithTimeOrCount(timeSpan, count, scheduler).selectMany(function (x) { return x.toArray(); }); }; /** * Records the time interval between consecutive values in an observable sequence. * * @example * 1 - res = source.timeInterval(); * 2 - res = source.timeInterval(Rx.Scheduler.timeout); * * @param [scheduler] Scheduler used to compute time intervals. If not specified, the timeout scheduler is used. * @returns {Observable} An observable sequence with time interval information on values. */ observableProto.timeInterval = function (scheduler) { var source = this; isScheduler(scheduler) || (scheduler = timeoutScheduler); return observableDefer(function () { var last = scheduler.now(); return source.map(function (x) { var now = scheduler.now(), span = now - last; last = now; return { value: x, interval: span }; }); }); }; /** * Records the timestamp for each value in an observable sequence. * * @example * 1 - res = source.timestamp(); // produces { value: x, timestamp: ts } * 2 - res = source.timestamp(Rx.Scheduler.default); * * @param {Scheduler} [scheduler] Scheduler used to compute timestamps. If not specified, the default scheduler is used. * @returns {Observable} An observable sequence with timestamp information on values. */ observableProto.timestamp = function (scheduler) { isScheduler(scheduler) || (scheduler = timeoutScheduler); return this.map(function (x) { return { value: x, timestamp: scheduler.now() }; }); }; function sampleObservable(source, sampler) { return new AnonymousObservable(function (o) { var atEnd = false, value, hasValue = false; function sampleSubscribe() { if (hasValue) { hasValue = false; o.onNext(value); } atEnd && o.onCompleted(); } var sourceSubscription = new SingleAssignmentDisposable(); sourceSubscription.setDisposable(source.subscribe( function (newValue) { hasValue = true; value = newValue; }, function (e) { o.onError(e); }, function () { atEnd = true; sourceSubscription.dispose(); } )); return new CompositeDisposable( sourceSubscription, sampler.subscribe(sampleSubscribe, function (e) { o.onError(e); }, sampleSubscribe) ); }, source); } /** * Samples the observable sequence at each interval. * * @example * 1 - res = source.sample(sampleObservable); // Sampler tick sequence * 2 - res = source.sample(5000); // 5 seconds * 2 - res = source.sample(5000, Rx.Scheduler.timeout); // 5 seconds * * @param {Mixed} intervalOrSampler Interval at which to sample (specified as an integer denoting milliseconds) or Sampler Observable. * @param {Scheduler} [scheduler] Scheduler to run the sampling timer on. If not specified, the timeout scheduler is used. * @returns {Observable} Sampled observable sequence. */ observableProto.sample = observableProto.throttleLatest = function (intervalOrSampler, scheduler) { isScheduler(scheduler) || (scheduler = timeoutScheduler); return typeof intervalOrSampler === 'number' ? sampleObservable(this, observableinterval(intervalOrSampler, scheduler)) : sampleObservable(this, intervalOrSampler); }; /** * Returns the source observable sequence or the other observable sequence if dueTime elapses. * @param {Number} dueTime Absolute (specified as a Date object) or relative time (specified as an integer denoting milliseconds) when a timeout occurs. * @param {Observable} [other] Sequence to return in case of a timeout. If not specified, a timeout error throwing sequence will be used. * @param {Scheduler} [scheduler] Scheduler to run the timeout timers on. If not specified, the timeout scheduler is used. * @returns {Observable} The source sequence switching to the other sequence in case of a timeout. */ observableProto.timeout = function (dueTime, other, scheduler) { (other == null || typeof other === 'string') && (other = observableThrow(new Error(other || 'Timeout'))); isScheduler(scheduler) || (scheduler = timeoutScheduler); var source = this, schedulerMethod = dueTime instanceof Date ? 'scheduleWithAbsolute' : 'scheduleWithRelative'; return new AnonymousObservable(function (observer) { var id = 0, original = new SingleAssignmentDisposable(), subscription = new SerialDisposable(), switched = false, timer = new SerialDisposable(); subscription.setDisposable(original); function createTimer() { var myId = id; timer.setDisposable(scheduler[schedulerMethod](dueTime, function () { if (id === myId) { isPromise(other) && (other = observableFromPromise(other)); subscription.setDisposable(other.subscribe(observer)); } })); } createTimer(); original.setDisposable(source.subscribe(function (x) { if (!switched) { id++; observer.onNext(x); createTimer(); } }, function (e) { if (!switched) { id++; observer.onError(e); } }, function () { if (!switched) { id++; observer.onCompleted(); } })); return new CompositeDisposable(subscription, timer); }, source); }; /** * Generates an observable sequence by iterating a state from an initial state until the condition fails. * * @example * res = source.generateWithAbsoluteTime(0, * function (x) { return return true; }, * function (x) { return x + 1; }, * function (x) { return x; }, * function (x) { return new Date(); } * }); * * @param {Mixed} initialState Initial state. * @param {Function} condition Condition to terminate generation (upon returning false). * @param {Function} iterate Iteration step function. * @param {Function} resultSelector Selector function for results produced in the sequence. * @param {Function} timeSelector Time selector function to control the speed of values being produced each iteration, returning Date values. * @param {Scheduler} [scheduler] Scheduler on which to run the generator loop. If not specified, the timeout scheduler is used. * @returns {Observable} The generated sequence. */ Observable.generateWithAbsoluteTime = function (initialState, condition, iterate, resultSelector, timeSelector, scheduler) { isScheduler(scheduler) || (scheduler = timeoutScheduler); return new AnonymousObservable(function (observer) { var first = true, hasResult = false; return scheduler.scheduleRecursiveWithAbsoluteAndState(initialState, scheduler.now(), function (state, self) { hasResult && observer.onNext(state); try { if (first) { first = false; } else { state = iterate(state); } hasResult = condition(state); if (hasResult) { var result = resultSelector(state); var time = timeSelector(state); } } catch (e) { observer.onError(e); return; } if (hasResult) { self(result, time); } else { observer.onCompleted(); } }); }); }; /** * Generates an observable sequence by iterating a state from an initial state until the condition fails. * * @example * res = source.generateWithRelativeTime(0, * function (x) { return return true; }, * function (x) { return x + 1; }, * function (x) { return x; }, * function (x) { return 500; } * ); * * @param {Mixed} initialState Initial state. * @param {Function} condition Condition to terminate generation (upon returning false). * @param {Function} iterate Iteration step function. * @param {Function} resultSelector Selector function for results produced in the sequence. * @param {Function} timeSelector Time selector function to control the speed of values being produced each iteration, returning integer values denoting milliseconds. * @param {Scheduler} [scheduler] Scheduler on which to run the generator loop. If not specified, the timeout scheduler is used. * @returns {Observable} The generated sequence. */ Observable.generateWithRelativeTime = function (initialState, condition, iterate, resultSelector, timeSelector, scheduler) { isScheduler(scheduler) || (scheduler = timeoutScheduler); return new AnonymousObservable(function (observer) { var first = true, hasResult = false; return scheduler.scheduleRecursiveWithRelativeAndState(initialState, 0, function (state, self) { hasResult && observer.onNext(state); try { if (first) { first = false; } else { state = iterate(state); } hasResult = condition(state); if (hasResult) { var result = resultSelector(state); var time = timeSelector(state); } } catch (e) { observer.onError(e); return; } if (hasResult) { self(result, time); } else { observer.onCompleted(); } }); }); }; /** * Time shifts the observable sequence by delaying the subscription with the specified relative time duration, using the specified scheduler to run timers. * * @example * 1 - res = source.delaySubscription(5000); // 5s * 2 - res = source.delaySubscription(5000, Rx.Scheduler.default); // 5 seconds * * @param {Number} dueTime Relative or absolute time shift of the subscription. * @param {Scheduler} [scheduler] Scheduler to run the subscription delay timer on. If not specified, the timeout scheduler is used. * @returns {Observable} Time-shifted sequence. */ observableProto.delaySubscription = function (dueTime, scheduler) { var scheduleMethod = dueTime instanceof Date ? 'scheduleWithAbsolute' : 'scheduleWithRelative'; var source = this; isScheduler(scheduler) || (scheduler = timeoutScheduler); return new AnonymousObservable(function (o) { var d = new SerialDisposable(); d.setDisposable(scheduler[scheduleMethod](dueTime, function() { d.setDisposable(source.subscribe(o)); })); return d; }, this); }; /** * Time shifts the observable sequence based on a subscription delay and a delay selector function for each element. * * @example * 1 - res = source.delayWithSelector(function (x) { return Rx.Scheduler.timer(5000); }); // with selector only * 1 - res = source.delayWithSelector(Rx.Observable.timer(2000), function (x) { return Rx.Observable.timer(x); }); // with delay and selector * * @param {Observable} [subscriptionDelay] Sequence indicating the delay for the subscription to the source. * @param {Function} delayDurationSelector Selector function to retrieve a sequence indicating the delay for each given element. * @returns {Observable} Time-shifted sequence. */ observableProto.delayWithSelector = function (subscriptionDelay, delayDurationSelector) { var source = this, subDelay, selector; if (isFunction(subscriptionDelay)) { selector = subscriptionDelay; } else { subDelay = subscriptionDelay; selector = delayDurationSelector; } return new AnonymousObservable(function (observer) { var delays = new CompositeDisposable(), atEnd = false, subscription = new SerialDisposable(); function start() { subscription.setDisposable(source.subscribe( function (x) { var delay = tryCatch(selector)(x); if (delay === errorObj) { return observer.onError(delay.e); } var d = new SingleAssignmentDisposable(); delays.add(d); d.setDisposable(delay.subscribe( function () { observer.onNext(x); delays.remove(d); done(); }, function (e) { observer.onError(e); }, function () { observer.onNext(x); delays.remove(d); done(); } )) }, function (e) { observer.onError(e); }, function () { atEnd = true; subscription.dispose(); done(); } )) } function done () { atEnd && delays.length === 0 && observer.onCompleted(); } if (!subDelay) { start(); } else { subscription.setDisposable(subDelay.subscribe(start, function (e) { observer.onError(e); }, start)); } return new CompositeDisposable(subscription, delays); }, this); }; /** * Returns the source observable sequence, switching to the other observable sequence if a timeout is signaled. * @param {Observable} [firstTimeout] Observable sequence that represents the timeout for the first element. If not provided, this defaults to Observable.never(). * @param {Function} timeoutDurationSelector Selector to retrieve an observable sequence that represents the timeout between the current element and the next element. * @param {Observable} [other] Sequence to return in case of a timeout. If not provided, this is set to Observable.throwException(). * @returns {Observable} The source sequence switching to the other sequence in case of a timeout. */ observableProto.timeoutWithSelector = function (firstTimeout, timeoutdurationSelector, other) { if (arguments.length === 1) { timeoutdurationSelector = firstTimeout; firstTimeout = observableNever(); } other || (other = observableThrow(new Error('Timeout'))); var source = this; return new AnonymousObservable(function (observer) { var subscription = new SerialDisposable(), timer = new SerialDisposable(), original = new SingleAssignmentDisposable(); subscription.setDisposable(original); var id = 0, switched = false; function setTimer(timeout) { var myId = id; function timerWins () { return id === myId; } var d = new SingleAssignmentDisposable(); timer.setDisposable(d); d.setDisposable(timeout.subscribe(function () { timerWins() && subscription.setDisposable(other.subscribe(observer)); d.dispose(); }, function (e) { timerWins() && observer.onError(e); }, function () { timerWins() && subscription.setDisposable(other.subscribe(observer)); })); }; setTimer(firstTimeout); function observerWins() { var res = !switched; if (res) { id++; } return res; } original.setDisposable(source.subscribe(function (x) { if (observerWins()) { observer.onNext(x); var timeout; try { timeout = timeoutdurationSelector(x); } catch (e) { observer.onError(e); return; } setTimer(isPromise(timeout) ? observableFromPromise(timeout) : timeout); } }, function (e) { observerWins() && observer.onError(e); }, function () { observerWins() && observer.onCompleted(); })); return new CompositeDisposable(subscription, timer); }, source); }; /** * Ignores values from an observable sequence which are followed by another value within a computed throttle duration. * @param {Function} durationSelector Selector function to retrieve a sequence indicating the throttle duration for each given element. * @returns {Observable} The debounced sequence. */ observableProto.debounceWithSelector = function (durationSelector) { var source = this; return new AnonymousObservable(function (observer) { var value, hasValue = false, cancelable = new SerialDisposable(), id = 0; var subscription = source.subscribe(function (x) { var throttle; try { throttle = durationSelector(x); } catch (e) { observer.onError(e); return; } isPromise(throttle) && (throttle = observableFromPromise(throttle)); hasValue = true; value = x; id++; var currentid = id, d = new SingleAssignmentDisposable(); cancelable.setDisposable(d); d.setDisposable(throttle.subscribe(function () { hasValue && id === currentid && observer.onNext(value); hasValue = false; d.dispose(); }, observer.onError.bind(observer), function () { hasValue && id === currentid && observer.onNext(value); hasValue = false; d.dispose(); })); }, function (e) { cancelable.dispose(); observer.onError(e); hasValue = false; id++; }, function () { cancelable.dispose(); hasValue && observer.onNext(value); observer.onCompleted(); hasValue = false; id++; }); return new CompositeDisposable(subscription, cancelable); }, source); }; /** * @deprecated use #debounceWithSelector instead. */ observableProto.throttleWithSelector = function (durationSelector) { //deprecate('throttleWithSelector', 'debounceWithSelector'); return this.debounceWithSelector(durationSelector); }; /** * Skips elements for the specified duration from the end of the observable source sequence, using the specified scheduler to run timers. * * 1 - res = source.skipLastWithTime(5000); * 2 - res = source.skipLastWithTime(5000, scheduler); * * @description * This operator accumulates a queue with a length enough to store elements received during the initial duration window. * As more elements are received, elements older than the specified duration are taken from the queue and produced on the * result sequence. This causes elements to be delayed with duration. * @param {Number} duration Duration for skipping elements from the end of the sequence. * @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout * @returns {Observable} An observable sequence with the elements skipped during the specified duration from the end of the source sequence. */ observableProto.skipLastWithTime = function (duration, scheduler) { isScheduler(scheduler) || (scheduler = timeoutScheduler); var source = this; return new AnonymousObservable(function (o) { var q = []; return source.subscribe(function (x) { var now = scheduler.now(); q.push({ interval: now, value: x }); while (q.length > 0 && now - q[0].interval >= duration) { o.onNext(q.shift().value); } }, function (e) { o.onError(e); }, function () { var now = scheduler.now(); while (q.length > 0 && now - q[0].interval >= duration) { o.onNext(q.shift().value); } o.onCompleted(); }); }, source); }; /** * Returns elements within the specified duration from the end of the observable source sequence, using the specified schedulers to run timers and to drain the collected elements. * @description * This operator accumulates a queue with a length enough to store elements received during the initial duration window. * As more elements are received, elements older than the specified duration are taken from the queue and produced on the * result sequence. This causes elements to be delayed with duration. * @param {Number} duration Duration for taking elements from the end of the sequence. * @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. * @returns {Observable} An observable sequence with the elements taken during the specified duration from the end of the source sequence. */ observableProto.takeLastWithTime = function (duration, scheduler) { var source = this; isScheduler(scheduler) || (scheduler = timeoutScheduler); return new AnonymousObservable(function (o) { var q = []; return source.subscribe(function (x) { var now = scheduler.now(); q.push({ interval: now, value: x }); while (q.length > 0 && now - q[0].interval >= duration) { q.shift(); } }, function (e) { o.onError(e); }, function () { var now = scheduler.now(); while (q.length > 0) { var next = q.shift(); if (now - next.interval <= duration) { o.onNext(next.value); } } o.onCompleted(); }); }, source); }; /** * Returns an array with the elements within the specified duration from the end of the observable source sequence, using the specified scheduler to run timers. * @description * This operator accumulates a queue with a length enough to store elements received during the initial duration window. * As more elements are received, elements older than the specified duration are taken from the queue and produced on the * result sequence. This causes elements to be delayed with duration. * @param {Number} duration Duration for taking elements from the end of the sequence. * @param {Scheduler} scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. * @returns {Observable} An observable sequence containing a single array with the elements taken during the specified duration from the end of the source sequence. */ observableProto.takeLastBufferWithTime = function (duration, scheduler) { var source = this; isScheduler(scheduler) || (scheduler = timeoutScheduler); return new AnonymousObservable(function (o) { var q = []; return source.subscribe(function (x) { var now = scheduler.now(); q.push({ interval: now, value: x }); while (q.length > 0 && now - q[0].interval >= duration) { q.shift(); } }, function (e) { o.onError(e); }, function () { var now = scheduler.now(), res = []; while (q.length > 0) { var next = q.shift(); now - next.interval <= duration && res.push(next.value); } o.onNext(res); o.onCompleted(); }); }, source); }; /** * Takes elements for the specified duration from the start of the observable source sequence, using the specified scheduler to run timers. * * @example * 1 - res = source.takeWithTime(5000, [optional scheduler]); * @description * This operator accumulates a queue with a length enough to store elements received during the initial duration window. * As more elements are received, elements older than the specified duration are taken from the queue and produced on the * result sequence. This causes elements to be delayed with duration. * @param {Number} duration Duration for taking elements from the start of the sequence. * @param {Scheduler} scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. * @returns {Observable} An observable sequence with the elements taken during the specified duration from the start of the source sequence. */ observableProto.takeWithTime = function (duration, scheduler) { var source = this; isScheduler(scheduler) || (scheduler = timeoutScheduler); return new AnonymousObservable(function (o) { return new CompositeDisposable(scheduler.scheduleWithRelative(duration, function () { o.onCompleted(); }), source.subscribe(o)); }, source); }; /** * Skips elements for the specified duration from the start of the observable source sequence, using the specified scheduler to run timers. * * @example * 1 - res = source.skipWithTime(5000, [optional scheduler]); * * @description * Specifying a zero value for duration doesn't guarantee no elements will be dropped from the start of the source sequence. * This is a side-effect of the asynchrony introduced by the scheduler, where the action that causes callbacks from the source sequence to be forwarded * may not execute immediately, despite the zero due time. * * Errors produced by the source sequence are always forwarded to the result sequence, even if the error occurs before the duration. * @param {Number} duration Duration for skipping elements from the start of the sequence. * @param {Scheduler} scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. * @returns {Observable} An observable sequence with the elements skipped during the specified duration from the start of the source sequence. */ observableProto.skipWithTime = function (duration, scheduler) { var source = this; isScheduler(scheduler) || (scheduler = timeoutScheduler); return new AnonymousObservable(function (observer) { var open = false; return new CompositeDisposable( scheduler.scheduleWithRelative(duration, function () { open = true; }), source.subscribe(function (x) { open && observer.onNext(x); }, observer.onError.bind(observer), observer.onCompleted.bind(observer))); }, source); }; /** * Skips elements from the observable source sequence until the specified start time, using the specified scheduler to run timers. * Errors produced by the source sequence are always forwarded to the result sequence, even if the error occurs before the start time. * * @examples * 1 - res = source.skipUntilWithTime(new Date(), [scheduler]); * 2 - res = source.skipUntilWithTime(5000, [scheduler]); * @param {Date|Number} startTime Time to start taking elements from the source sequence. If this value is less than or equal to Date(), no elements will be skipped. * @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. * @returns {Observable} An observable sequence with the elements skipped until the specified start time. */ observableProto.skipUntilWithTime = function (startTime, scheduler) { isScheduler(scheduler) || (scheduler = timeoutScheduler); var source = this, schedulerMethod = startTime instanceof Date ? 'scheduleWithAbsolute' : 'scheduleWithRelative'; return new AnonymousObservable(function (o) { var open = false; return new CompositeDisposable( scheduler[schedulerMethod](startTime, function () { open = true; }), source.subscribe( function (x) { open && o.onNext(x); }, function (e) { o.onError(e); }, function () { o.onCompleted(); })); }, source); }; /** * Takes elements for the specified duration until the specified end time, using the specified scheduler to run timers. * @param {Number | Date} endTime Time to stop taking elements from the source sequence. If this value is less than or equal to new Date(), the result stream will complete immediately. * @param {Scheduler} [scheduler] Scheduler to run the timer on. * @returns {Observable} An observable sequence with the elements taken until the specified end time. */ observableProto.takeUntilWithTime = function (endTime, scheduler) { isScheduler(scheduler) || (scheduler = timeoutScheduler); var source = this, schedulerMethod = endTime instanceof Date ? 'scheduleWithAbsolute' : 'scheduleWithRelative'; return new AnonymousObservable(function (o) { return new CompositeDisposable( scheduler[schedulerMethod](endTime, function () { o.onCompleted(); }), source.subscribe(o)); }, source); }; /** * Returns an Observable that emits only the first item emitted by the source Observable during sequential time windows of a specified duration. * @param {Number} windowDuration time to wait before emitting another item after emitting the last item * @param {Scheduler} [scheduler] the Scheduler to use internally to manage the timers that handle timeout for each item. If not provided, defaults to Scheduler.timeout. * @returns {Observable} An Observable that performs the throttle operation. */ observableProto.throttleFirst = function (windowDuration, scheduler) { isScheduler(scheduler) || (scheduler = timeoutScheduler); var duration = +windowDuration || 0; if (duration <= 0) { throw new RangeError('windowDuration cannot be less or equal zero.'); } var source = this; return new AnonymousObservable(function (o) { var lastOnNext = 0; return source.subscribe( function (x) { var now = scheduler.now(); if (lastOnNext === 0 || now - lastOnNext >= duration) { lastOnNext = now; o.onNext(x); } },function (e) { o.onError(e); }, function () { o.onCompleted(); } ); }, source); }; /** * Executes a transducer to transform the observable sequence * @param {Transducer} transducer A transducer to execute * @returns {Observable} An Observable sequence containing the results from the transducer. */ observableProto.transduce = function(transducer) { var source = this; function transformForObserver(o) { return { '@@transducer/init': function() { return o; }, '@@transducer/step': function(obs, input) { return obs.onNext(input); }, '@@transducer/result': function(obs) { return obs.onCompleted(); } }; } return new AnonymousObservable(function(o) { var xform = transducer(transformForObserver(o)); return source.subscribe( function(v) { try { xform['@@transducer/step'](o, v); } catch (e) { o.onError(e); } }, function (e) { o.onError(e); }, function() { xform['@@transducer/result'](o); } ); }, source); }; /* * Performs a exclusive waiting for the first to finish before subscribing to another observable. * Observables that come in between subscriptions will be dropped on the floor. * @returns {Observable} A exclusive observable with only the results that happen when subscribed. */ observableProto.exclusive = function () { var sources = this; return new AnonymousObservable(function (observer) { var hasCurrent = false, isStopped = false, m = new SingleAssignmentDisposable(), g = new CompositeDisposable(); g.add(m); m.setDisposable(sources.subscribe( function (innerSource) { if (!hasCurrent) { hasCurrent = true; isPromise(innerSource) && (innerSource = observableFromPromise(innerSource)); var innerSubscription = new SingleAssignmentDisposable(); g.add(innerSubscription); innerSubscription.setDisposable(innerSource.subscribe( observer.onNext.bind(observer), observer.onError.bind(observer), function () { g.remove(innerSubscription); hasCurrent = false; if (isStopped && g.length === 1) { observer.onCompleted(); } })); } }, observer.onError.bind(observer), function () { isStopped = true; if (!hasCurrent && g.length === 1) { observer.onCompleted(); } })); return g; }, this); }; /* * Performs a exclusive map waiting for the first to finish before subscribing to another observable. * Observables that come in between subscriptions will be dropped on the floor. * @param {Function} selector Selector to invoke for every item in the current subscription. * @param {Any} [thisArg] An optional context to invoke with the selector parameter. * @returns {Observable} An exclusive observable with only the results that happen when subscribed. */ observableProto.exclusiveMap = function (selector, thisArg) { var sources = this, selectorFunc = bindCallback(selector, thisArg, 3); return new AnonymousObservable(function (observer) { var index = 0, hasCurrent = false, isStopped = true, m = new SingleAssignmentDisposable(), g = new CompositeDisposable(); g.add(m); m.setDisposable(sources.subscribe( function (innerSource) { if (!hasCurrent) { hasCurrent = true; innerSubscription = new SingleAssignmentDisposable(); g.add(innerSubscription); isPromise(innerSource) && (innerSource = observableFromPromise(innerSource)); innerSubscription.setDisposable(innerSource.subscribe( function (x) { var result; try { result = selectorFunc(x, index++, innerSource); } catch (e) { observer.onError(e); return; } observer.onNext(result); }, function (e) { observer.onError(e); }, function () { g.remove(innerSubscription); hasCurrent = false; if (isStopped && g.length === 1) { observer.onCompleted(); } })); } }, function (e) { observer.onError(e); }, function () { isStopped = true; if (g.length === 1 && !hasCurrent) { observer.onCompleted(); } })); return g; }, this); }; /** Provides a set of extension methods for virtual time scheduling. */ Rx.VirtualTimeScheduler = (function (__super__) { function localNow() { return this.toDateTimeOffset(this.clock); } function scheduleNow(state, action) { return this.scheduleAbsoluteWithState(state, this.clock, action); } function scheduleRelative(state, dueTime, action) { return this.scheduleRelativeWithState(state, this.toRelative(dueTime), action); } function scheduleAbsolute(state, dueTime, action) { return this.scheduleRelativeWithState(state, this.toRelative(dueTime - this.now()), action); } function invokeAction(scheduler, action) { action(); return disposableEmpty; } inherits(VirtualTimeScheduler, __super__); /** * Creates a new virtual time scheduler with the specified initial clock value and absolute time comparer. * * @constructor * @param {Number} initialClock Initial value for the clock. * @param {Function} comparer Comparer to determine causality of events based on absolute time. */ function VirtualTimeScheduler(initialClock, comparer) { this.clock = initialClock; this.comparer = comparer; this.isEnabled = false; this.queue = new PriorityQueue(1024); __super__.call(this, localNow, scheduleNow, scheduleRelative, scheduleAbsolute); } var VirtualTimeSchedulerPrototype = VirtualTimeScheduler.prototype; /** * Adds a relative time value to an absolute time value. * @param {Number} absolute Absolute virtual time value. * @param {Number} relative Relative virtual time value to add. * @return {Number} Resulting absolute virtual time sum value. */ VirtualTimeSchedulerPrototype.add = notImplemented; /** * Converts an absolute time to a number * @param {Any} The absolute time. * @returns {Number} The absolute time in ms */ VirtualTimeSchedulerPrototype.toDateTimeOffset = notImplemented; /** * Converts the TimeSpan value to a relative virtual time value. * @param {Number} timeSpan TimeSpan value to convert. * @return {Number} Corresponding relative virtual time value. */ VirtualTimeSchedulerPrototype.toRelative = notImplemented; /** * Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be emulated using recursive scheduling. * @param {Mixed} state Initial state passed to the action upon the first iteration. * @param {Number} period Period for running the work periodically. * @param {Function} action Action to be executed, potentially updating the state. * @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort). */ VirtualTimeSchedulerPrototype.schedulePeriodicWithState = function (state, period, action) { var s = new SchedulePeriodicRecursive(this, state, period, action); return s.start(); }; /** * Schedules an action to be executed after dueTime. * @param {Mixed} state State passed to the action to be executed. * @param {Number} dueTime Relative time after which to execute the action. * @param {Function} action Action to be executed. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ VirtualTimeSchedulerPrototype.scheduleRelativeWithState = function (state, dueTime, action) { var runAt = this.add(this.clock, dueTime); return this.scheduleAbsoluteWithState(state, runAt, action); }; /** * Schedules an action to be executed at dueTime. * @param {Number} dueTime Relative time after which to execute the action. * @param {Function} action Action to be executed. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ VirtualTimeSchedulerPrototype.scheduleRelative = function (dueTime, action) { return this.scheduleRelativeWithState(action, dueTime, invokeAction); }; /** * Starts the virtual time scheduler. */ VirtualTimeSchedulerPrototype.start = function () { if (!this.isEnabled) { this.isEnabled = true; do { var next = this.getNext(); if (next !== null) { this.comparer(next.dueTime, this.clock) > 0 && (this.clock = next.dueTime); next.invoke(); } else { this.isEnabled = false; } } while (this.isEnabled); } }; /** * Stops the virtual time scheduler. */ VirtualTimeSchedulerPrototype.stop = function () { this.isEnabled = false; }; /** * Advances the scheduler's clock to the specified time, running all work till that point. * @param {Number} time Absolute time to advance the scheduler's clock to. */ VirtualTimeSchedulerPrototype.advanceTo = function (time) { var dueToClock = this.comparer(this.clock, time); if (this.comparer(this.clock, time) > 0) { throw new ArgumentOutOfRangeError(); } if (dueToClock === 0) { return; } if (!this.isEnabled) { this.isEnabled = true; do { var next = this.getNext(); if (next !== null && this.comparer(next.dueTime, time) <= 0) { this.comparer(next.dueTime, this.clock) > 0 && (this.clock = next.dueTime); next.invoke(); } else { this.isEnabled = false; } } while (this.isEnabled); this.clock = time; } }; /** * Advances the scheduler's clock by the specified relative time, running all work scheduled for that timespan. * @param {Number} time Relative time to advance the scheduler's clock by. */ VirtualTimeSchedulerPrototype.advanceBy = function (time) { var dt = this.add(this.clock, time), dueToClock = this.comparer(this.clock, dt); if (dueToClock > 0) { throw new ArgumentOutOfRangeError(); } if (dueToClock === 0) { return; } this.advanceTo(dt); }; /** * Advances the scheduler's clock by the specified relative time. * @param {Number} time Relative time to advance the scheduler's clock by. */ VirtualTimeSchedulerPrototype.sleep = function (time) { var dt = this.add(this.clock, time); if (this.comparer(this.clock, dt) >= 0) { throw new ArgumentOutOfRangeError(); } this.clock = dt; }; /** * Gets the next scheduled item to be executed. * @returns {ScheduledItem} The next scheduled item. */ VirtualTimeSchedulerPrototype.getNext = function () { while (this.queue.length > 0) { var next = this.queue.peek(); if (next.isCancelled()) { this.queue.dequeue(); } else { return next; } } return null; }; /** * Schedules an action to be executed at dueTime. * @param {Scheduler} scheduler Scheduler to execute the action on. * @param {Number} dueTime Absolute time at which to execute the action. * @param {Function} action Action to be executed. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ VirtualTimeSchedulerPrototype.scheduleAbsolute = function (dueTime, action) { return this.scheduleAbsoluteWithState(action, dueTime, invokeAction); }; /** * Schedules an action to be executed at dueTime. * @param {Mixed} state State passed to the action to be executed. * @param {Number} dueTime Absolute time at which to execute the action. * @param {Function} action Action to be executed. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ VirtualTimeSchedulerPrototype.scheduleAbsoluteWithState = function (state, dueTime, action) { var self = this; function run(scheduler, state1) { self.queue.remove(si); return action(scheduler, state1); } var si = new ScheduledItem(this, state, run, dueTime, this.comparer); this.queue.enqueue(si); return si.disposable; }; return VirtualTimeScheduler; }(Scheduler)); /** Provides a virtual time scheduler that uses Date for absolute time and number for relative time. */ Rx.HistoricalScheduler = (function (__super__) { inherits(HistoricalScheduler, __super__); /** * Creates a new historical scheduler with the specified initial clock value. * @constructor * @param {Number} initialClock Initial value for the clock. * @param {Function} comparer Comparer to determine causality of events based on absolute time. */ function HistoricalScheduler(initialClock, comparer) { var clock = initialClock == null ? 0 : initialClock; var cmp = comparer || defaultSubComparer; __super__.call(this, clock, cmp); } var HistoricalSchedulerProto = HistoricalScheduler.prototype; /** * Adds a relative time value to an absolute time value. * @param {Number} absolute Absolute virtual time value. * @param {Number} relative Relative virtual time value to add. * @return {Number} Resulting absolute virtual time sum value. */ HistoricalSchedulerProto.add = function (absolute, relative) { return absolute + relative; }; HistoricalSchedulerProto.toDateTimeOffset = function (absolute) { return new Date(absolute).getTime(); }; /** * Converts the TimeSpan value to a relative virtual time value. * @memberOf HistoricalScheduler * @param {Number} timeSpan TimeSpan value to convert. * @return {Number} Corresponding relative virtual time value. */ HistoricalSchedulerProto.toRelative = function (timeSpan) { return timeSpan; }; return HistoricalScheduler; }(Rx.VirtualTimeScheduler)); var AnonymousObservable = Rx.AnonymousObservable = (function (__super__) { inherits(AnonymousObservable, __super__); // Fix subscriber to check for undefined or function returned to decorate as Disposable function fixSubscriber(subscriber) { return subscriber && isFunction(subscriber.dispose) ? subscriber : isFunction(subscriber) ? disposableCreate(subscriber) : disposableEmpty; } function setDisposable(s, state) { var ado = state[0], subscribe = state[1]; var sub = tryCatch(subscribe)(ado); if (sub === errorObj) { if(!ado.fail(errorObj.e)) { return thrower(errorObj.e); } } ado.setDisposable(fixSubscriber(sub)); } function AnonymousObservable(subscribe, parent) { this.source = parent; function s(observer) { var ado = new AutoDetachObserver(observer), state = [ado, subscribe]; if (currentThreadScheduler.scheduleRequired()) { currentThreadScheduler.scheduleWithState(state, setDisposable); } else { setDisposable(null, state); } return ado; } __super__.call(this, s); } return AnonymousObservable; }(Observable)); var AutoDetachObserver = (function (__super__) { inherits(AutoDetachObserver, __super__); function AutoDetachObserver(observer) { __super__.call(this); this.observer = observer; this.m = new SingleAssignmentDisposable(); } var AutoDetachObserverPrototype = AutoDetachObserver.prototype; AutoDetachObserverPrototype.next = function (value) { var result = tryCatch(this.observer.onNext).call(this.observer, value); if (result === errorObj) { this.dispose(); thrower(result.e); } }; AutoDetachObserverPrototype.error = function (err) { var result = tryCatch(this.observer.onError).call(this.observer, err); this.dispose(); result === errorObj && thrower(result.e); }; AutoDetachObserverPrototype.completed = function () { var result = tryCatch(this.observer.onCompleted).call(this.observer); this.dispose(); result === errorObj && thrower(result.e); }; AutoDetachObserverPrototype.setDisposable = function (value) { this.m.setDisposable(value); }; AutoDetachObserverPrototype.getDisposable = function () { return this.m.getDisposable(); }; AutoDetachObserverPrototype.dispose = function () { __super__.prototype.dispose.call(this); this.m.dispose(); }; return AutoDetachObserver; }(AbstractObserver)); var GroupedObservable = (function (__super__) { inherits(GroupedObservable, __super__); function subscribe(observer) { return this.underlyingObservable.subscribe(observer); } function GroupedObservable(key, underlyingObservable, mergedDisposable) { __super__.call(this, subscribe); this.key = key; this.underlyingObservable = !mergedDisposable ? underlyingObservable : new AnonymousObservable(function (observer) { return new CompositeDisposable(mergedDisposable.getDisposable(), underlyingObservable.subscribe(observer)); }); } return GroupedObservable; }(Observable)); /** * Represents an object that is both an observable sequence as well as an observer. * Each notification is broadcasted to all subscribed observers. */ var Subject = Rx.Subject = (function (__super__) { function subscribe(observer) { checkDisposed(this); if (!this.isStopped) { this.observers.push(observer); return new InnerSubscription(this, observer); } if (this.hasError) { observer.onError(this.error); return disposableEmpty; } observer.onCompleted(); return disposableEmpty; } inherits(Subject, __super__); /** * Creates a subject. */ function Subject() { __super__.call(this, subscribe); this.isDisposed = false, this.isStopped = false, this.observers = []; this.hasError = false; } addProperties(Subject.prototype, Observer.prototype, { /** * Indicates whether the subject has observers subscribed to it. * @returns {Boolean} Indicates whether the subject has observers subscribed to it. */ hasObservers: function () { return this.observers.length > 0; }, /** * Notifies all subscribed observers about the end of the sequence. */ onCompleted: function () { checkDisposed(this); if (!this.isStopped) { this.isStopped = true; for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) { os[i].onCompleted(); } this.observers.length = 0; } }, /** * Notifies all subscribed observers about the exception. * @param {Mixed} error The exception to send to all observers. */ onError: function (error) { checkDisposed(this); if (!this.isStopped) { this.isStopped = true; this.error = error; this.hasError = true; for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) { os[i].onError(error); } this.observers.length = 0; } }, /** * Notifies all subscribed observers about the arrival of the specified element in the sequence. * @param {Mixed} value The value to send to all observers. */ onNext: function (value) { checkDisposed(this); if (!this.isStopped) { for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) { os[i].onNext(value); } } }, /** * Unsubscribe all observers and release resources. */ dispose: function () { this.isDisposed = true; this.observers = null; } }); /** * Creates a subject from the specified observer and observable. * @param {Observer} observer The observer used to send messages to the subject. * @param {Observable} observable The observable used to subscribe to messages sent from the subject. * @returns {Subject} Subject implemented using the given observer and observable. */ Subject.create = function (observer, observable) { return new AnonymousSubject(observer, observable); }; return Subject; }(Observable)); /** * Represents the result of an asynchronous operation. * The last value before the OnCompleted notification, or the error received through OnError, is sent to all subscribed observers. */ var AsyncSubject = Rx.AsyncSubject = (function (__super__) { function subscribe(observer) { checkDisposed(this); if (!this.isStopped) { this.observers.push(observer); return new InnerSubscription(this, observer); } if (this.hasError) { observer.onError(this.error); } else if (this.hasValue) { observer.onNext(this.value); observer.onCompleted(); } else { observer.onCompleted(); } return disposableEmpty; } inherits(AsyncSubject, __super__); /** * Creates a subject that can only receive one value and that value is cached for all future observations. * @constructor */ function AsyncSubject() { __super__.call(this, subscribe); this.isDisposed = false; this.isStopped = false; this.hasValue = false; this.observers = []; this.hasError = false; } addProperties(AsyncSubject.prototype, Observer, { /** * Indicates whether the subject has observers subscribed to it. * @returns {Boolean} Indicates whether the subject has observers subscribed to it. */ hasObservers: function () { checkDisposed(this); return this.observers.length > 0; }, /** * Notifies all subscribed observers about the end of the sequence, also causing the last received value to be sent out (if any). */ onCompleted: function () { var i, len; checkDisposed(this); if (!this.isStopped) { this.isStopped = true; var os = cloneArray(this.observers), len = os.length; if (this.hasValue) { for (i = 0; i < len; i++) { var o = os[i]; o.onNext(this.value); o.onCompleted(); } } else { for (i = 0; i < len; i++) { os[i].onCompleted(); } } this.observers.length = 0; } }, /** * Notifies all subscribed observers about the error. * @param {Mixed} error The Error to send to all observers. */ onError: function (error) { checkDisposed(this); if (!this.isStopped) { this.isStopped = true; this.hasError = true; this.error = error; for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) { os[i].onError(error); } this.observers.length = 0; } }, /** * Sends a value to the subject. The last value received before successful termination will be sent to all subscribed and future observers. * @param {Mixed} value The value to store in the subject. */ onNext: function (value) { checkDisposed(this); if (this.isStopped) { return; } this.value = value; this.hasValue = true; }, /** * Unsubscribe all observers and release resources. */ dispose: function () { this.isDisposed = true; this.observers = null; this.exception = null; this.value = null; } }); return AsyncSubject; }(Observable)); var AnonymousSubject = Rx.AnonymousSubject = (function (__super__) { inherits(AnonymousSubject, __super__); function subscribe(observer) { return this.observable.subscribe(observer); } function AnonymousSubject(observer, observable) { this.observer = observer; this.observable = observable; __super__.call(this, subscribe); } addProperties(AnonymousSubject.prototype, Observer.prototype, { onCompleted: function () { this.observer.onCompleted(); }, onError: function (error) { this.observer.onError(error); }, onNext: function (value) { this.observer.onNext(value); } }); return AnonymousSubject; }(Observable)); /** * Used to pause and resume streams. */ Rx.Pauser = (function (__super__) { inherits(Pauser, __super__); function Pauser() { __super__.call(this); } /** * Pauses the underlying sequence. */ Pauser.prototype.pause = function () { this.onNext(false); }; /** * Resumes the underlying sequence. */ Pauser.prototype.resume = function () { this.onNext(true); }; return Pauser; }(Subject)); if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) { root.Rx = Rx; define(function() { return Rx; }); } else if (freeExports && freeModule) { // in Node.js or RingoJS if (moduleExports) { (freeModule.exports = Rx).Rx = Rx; } else { freeExports.Rx = Rx; } } else { // in a browser or Rhino root.Rx = Rx; } // All code before this point will be filtered from stack traces. var rEndingLine = captureLine(); }.call(this)); }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"_process":1}],3:[function(require,module,exports){ 'use strict'; var Rx = require('rx'); function makeRequestProxies(drivers) { var requestProxies = {}; for (var _name in drivers) { if (drivers.hasOwnProperty(_name)) { requestProxies[_name] = new Rx.ReplaySubject(1); } } return requestProxies; } function callDrivers(drivers, requestProxies) { var responses = {}; for (var _name2 in drivers) { if (drivers.hasOwnProperty(_name2)) { responses[_name2] = drivers[_name2](requestProxies[_name2], _name2); } } return responses; } function makeDispose(requestProxies, rawResponses) { return function dispose() { for (var x in requestProxies) { if (requestProxies.hasOwnProperty(x)) { requestProxies[x].dispose(); } } for (var _name3 in rawResponses) { if (rawResponses.hasOwnProperty(_name3) && typeof rawResponses[_name3].dispose === 'function') { rawResponses[_name3].dispose(); } } }; } function makeAppInput(requestProxies, rawResponses) { Object.defineProperty(rawResponses, 'dispose', { enumerable: false, value: makeDispose(requestProxies, rawResponses) }); return rawResponses; } function replicateMany(original, imitators) { for (var _name4 in original) { if (original.hasOwnProperty(_name4)) { if (imitators.hasOwnProperty(_name4) && !imitators[_name4].isDisposed) { original[_name4].subscribe(imitators[_name4].asObserver()); } } } } function isObjectEmpty(obj) { for (var key in obj) { if (obj.hasOwnProperty(key)) { return false; } } return true; } function run(app, drivers) { if (typeof app !== 'function') { throw new Error('First argument given to Cycle.run() must be the `app` ' + 'function.'); } if (typeof drivers !== 'object' || drivers === null) { throw new Error('Second argument given to Cycle.run() must be an object ' + 'with driver functions as properties.'); } if (isObjectEmpty(drivers)) { throw new Error('Second argument given to Cycle.run() must be an object ' + 'with at least one driver function declared as a property.'); } var requestProxies = makeRequestProxies(drivers); var rawResponses = callDrivers(drivers, requestProxies); var responses = makeAppInput(requestProxies, rawResponses); var requests = app(responses); setTimeout(function () { return replicateMany(requests, requestProxies); }, 1); return [requests, responses]; } var Cycle = { /** * Takes an `app` function and circularly connects it to the given collection * of driver functions. * * The `app` function expects a collection of "driver response" Observables as * input, and should return a collection of "driver request" Observables. * A "collection of Observables" is a JavaScript object where * keys match the driver names registered by the `drivers` object, and values * are Observables or a collection of Observables. * * @param {Function} app a function that takes `responses` as input * and outputs a collection of `requests` Observables. * @param {Object} drivers an object where keys are driver names and values * are driver functions. * @return {Array} an array where the first object is the collection of driver * requests, and the second objet is the collection of driver responses, that * can be used for debugging or testing. * @function run */ run: run, /** * A shortcut to the root object of * [RxJS](https://github.com/Reactive-Extensions/RxJS). * @name Rx */ Rx: Rx }; module.exports = Cycle; },{"rx":2}]},{},[3])(3) });
/* jQuery Plugin: imgLiquid v0.9.75 / 19-04-13 jQuery plugin to resize images to fit in a container. Copyright (c) 2012 Alejandro Emparan (karacas), twitter: @krc_ale Dual licensed under the MIT and GPL licenses https://github.com/karacas/imgLiquid ex: $(".imgLiquid").imgLiquid({fill:true}); //OPTIONS: >js fill: true, verticalAlign: //'center' //'top' //'bottom' horizontalAlign: //'center' //'left' //'right' fadeInTime: 0, delay: 0, //time to process next image in milliseconds responsive: false, responsiveCheckTime: 500, //time to check resize in milliseconds >js callBakcs onStart: function(){}, onFinish: function(){}, onItemResize: function(index, container, img){}, onItemStart: function(index, container, img){}, onItemFinish: function(index, container, img){} >css (set useCssAligns: true) (overwrite js) text-align: center; vertical-align : middle; >hml5 data attr (overwrite all) data-imgLiquid-fill="true" data-imgLiquid-horizontalAlign="center" data-imgLiquid-verticalAlign="center" data-imgLiquid-fadeInTime="500" */ // ;(function($){ $.fn.extend({ imgLiquid: function(options) { //is ie? var isIE = /*@cc_on!@*/false; //Sizes var totalItems = this.length; var processedItems = 0; //Settings - Options this.defaultOptions = {}; var self = this; //___________________________________________________________________ var settings = $.extend({ fill: true, verticalAlign: 'center', // 'top' // 'bottom' horizontalAlign: 'center', // 'left' // 'right' fadeInTime: 0, responsive: false, responsiveCheckTime: 100, /*time to check div resize, default 10fps > 1000/100*/ delay: 0, removeBoxBackground: true, ieFadeInDisabled: true, useDataHtmlAttr: true, useCssAligns: false, imageRendering: 'auto', hardPixels: false, checkvisibility: true, timecheckvisibility : 250, //CALLBACKS onStart: null, //no-params onFinish: null, //no-params onItemResize: null, //params: (index, container, img ) onItemStart: null, //params: (index, container, img ) onItemFinish: null //params: (index, container, img ) }, this.defaultOptions, options); //CALLBACK > Start if (settings.onStart) settings.onStart(); //SAVES NEW SETTINGS if (self.data('settings') !== undefined) { var settTmp = $.extend(self.data('settings')); settTmp = $.extend(options); self.data('settings', settTmp); } //___________________________________________________________________ return this.each(function($i) { //Obj var $imgBoxCont = $(this); var $img = $('img:first', $imgBoxCont); if (!$img || $img === null || $img.size() ===0){ onError(); return null; } if ($img.data('ILprocessed')){ settings = $.extend(self.data('settings')); process($imgBoxCont, $img, $i); return; } //STATUS $img.data('ILprocessed', false); $img.ILerror = false; //CALLBACK > ItemStart (index, container, img ) if (settings.onItemStart) settings.onItemStart($i , $imgBoxCont , $img); //Alpha to 0 & removes $img.fadeTo(0, 0); $('img:not(:first)', $imgBoxCont).css('display','none'); $img.css({'visibility':'visible', 'max-width':'none', 'max-height':'none', 'width':'auto', 'height':'auto', 'display':'block', 'image-rendering':settings.imageRendering }); $img.removeAttr("width"); $img.removeAttr("height"); //Delay > 1 if (settings.delay <1) settings.delay = 1; //set OverFlow $imgBoxCont.css({'overflow':'hidden'}); //SETTINGS OVERWRITE if (isIE && settings.imageRendering === 'optimizeQuality') $img.css('-ms-interpolation-mode', 'bicubic'); if (settings.useCssAligns) { var cha = $imgBoxCont.css('text-align'); var cva = $imgBoxCont.css('vertical-align'); if(cha === 'left' || cha === 'center' || cha === 'right') settings.horizontalAlign = cha; if (cva === 'top' || cva === 'middle' || cva === 'bottom' || cva === 'center') settings.verticalAlign = cva; } if (settings.useDataHtmlAttr) { if ($imgBoxCont.attr('data-imgLiquid-fill') === 'true') settings.fill = true; if ($imgBoxCont.attr('data-imgLiquid-fill') === 'false' ) settings.fill = false; if ($imgBoxCont.attr('data-imgLiquid-responsive') === 'true') settings.responsive = true; if ($imgBoxCont.attr('data-imgLiquid-responsive') === 'false' ) settings.responsive = false; if ( Number ($imgBoxCont.attr('data-imgLiquid-fadeInTime')) > 0) settings.fadeInTime = Number ($imgBoxCont.attr('data-imgLiquid-fadeInTime')); var ha = $imgBoxCont.attr('data-imgLiquid-horizontalAlign'); var va = $imgBoxCont.attr('data-imgLiquid-verticalAlign'); if (ha === 'left' || ha === 'center' || ha === 'right') settings.horizontalAlign = ha; if (va === 'top' || va === 'middle' || va === 'bottom' || va === 'center') settings.verticalAlign = va; } //ie no anims > (muere ie, muere!) if (isIE && settings.ieFadeInDisabled) settings.fadeInTime = 0; //RESPONSIVE function checkElementSize(){ setTimeout(checkElementSizeDelay, settings.responsiveCheckTime); } function checkElementSizeDelay(){ //UPDATE SETTINGS settings = $.extend(self.data('settings')); $imgBoxCont.actualSize = $imgBoxCont.get(0).offsetWidth + ($imgBoxCont.get(0).offsetHeight/100000); if ($imgBoxCont.actualSize !== $imgBoxCont.sizeOld){ if ($img.data('ILprocessed') && $imgBoxCont.sizeOld !== undefined){ //CALLBACK > onItemResize (index, container, img ) if (settings.onItemResize) settings.onItemResize($i , $imgBoxCont , $img); //Process again if (settings.responsive) process($imgBoxCont, $img, $i); } } $imgBoxCont.sizeOld = $imgBoxCont.actualSize; checkElementSize(); } if (settings.responsive) settings.hardPixels = true; if (settings.responsive || settings.onItemResize !== null) checkElementSize(); //SAVE FIRST TIME SETTINGS self.data('settings', settings); //LOAD $img.on('load', onLoad).on('error', onError); if($img[0].complete)$img.load(); function onLoad(e){ if (!Boolean($img[0].width === 0 && $img[0].height === 0)) { if (settings.checkvisibility){ checkProcess(); }else{ //DIRECT > OLD VERSION TEST AND DELETE setTimeout(function() { process($imgBoxCont, $img, $i); }, $i * settings.delay); } } if (e) e.preventDefault(); } function onError(){ $img.ILerror = true; checkFinish($imgBoxCont, $img, $i); $imgBoxCont.css('visibility', 'hidden'); } function checkProcess(){ if ($img.data('ILprocessed')) return; setTimeout(function() { if ($imgBoxCont.is(':visible')){ setTimeout(function() { process($imgBoxCont, $img, $i); }, $i * settings.delay); }else{ checkProcess(); } }, settings.timecheckvisibility); } //___________________________________________________________________ function process($imgBoxCont, $img, $i){ //RESIZE var w,h; if ($img.data('owidth') === undefined) $img.data('owidth', $img[0].width); if ($img.data('oheight') === undefined) $img.data('oheight', $img[0].height); if (settings.fill === ($imgBoxCont.width() / $imgBoxCont.height()) >= ($img.data('owidth') / $img.data('oheight'))){ w = '100%'; h = 'auto'; if (settings.hardPixels){ w = Math.floor ($imgBoxCont.width()); h = Math.floor ($imgBoxCont.width() * ($img.data('oheight') / $img.data('owidth'))); } }else{ h = '100%'; w = 'auto'; if (settings.hardPixels){ h = Math.floor ($imgBoxCont.height()); w = Math.floor ($imgBoxCont.height() * ($img.data('owidth') / $img.data('oheight'))); } } $img.css({'width':w, 'height':h}); //align X var ha = settings.horizontalAlign.toLowerCase(); var hdif = $imgBoxCont.width() - $img[0].width; var margL = 0; if (ha === 'center' || ha === 'middle')margL = hdif/2; if (ha === 'right') margL = hdif; $img.css('margin-left', Math.floor(margL)); //align Y var va = settings.verticalAlign.toLowerCase(); var vdif = $imgBoxCont.height() - $img[0].height; var margT = 0; if (va === 'center' || va === 'middle') margT = vdif/2; if (va === 'bottom') margT = vdif; $img.css('margin-top', Math.floor(margT)); //FadeIn if (!$img.data('ILprocessed')){ if (settings.removeBoxBackground) $imgBoxCont.css('background-image', 'none'); $img.fadeTo(settings.fadeInTime, 1); $img.data('ILprocessed', true) ; //CALLBACK > onItemFinish (index, container, img ) if (settings.onItemFinish) settings.onItemFinish($i , $imgBoxCont , $img); checkFinish($imgBoxCont, $img, $i); } } //___________________________________________________________________ function checkFinish($imgBoxCont, $img, $i){ processedItems ++; //CALLBACK > onFinish if (processedItems === totalItems){ if (settings.onFinish) settings.onFinish(); } } }); } }); })(jQuery);
// is.js 0.2.2 // Author: Aras Atasaygin // AMD with global, Node, or global ;(function(root, factory) { if(typeof define === 'function' && define.amd) { // AMD. Register as an anonymous module. define(['is'], function(is) { // Also create a global in case some scripts // that are loaded still are looking for // a global even when an AMD loader is in use. return (root.is = factory(is)); }); } else if(typeof exports === 'object') { // Node. Does not work with strict CommonJS, but // only CommonJS-like enviroments that support module.exports, // like Node. module.exports = factory(require('is_js')); } else { // Browser globals (root is window) root.is = factory(root.is); } }(this, function(is) { // Baseline /* -------------------------------------------------------------------------- */ var root = this; var previousIs = root.is; // define 'is' object and current version is = {}; is.VERSION = '0.2.2'; // define interfaces is.not = {}; is.all = {}; is.any = {}; // cache some methods to call later on var toString = Object.prototype.toString; var arraySlice = Array.prototype.slice; var hasOwnProperty = Object.prototype.hasOwnProperty; // helper function which reverses the sense of predicate result function not(func) { return function() { return !func.apply(null, arraySlice.call(arguments)); }; } // helper function which call predicate function per parameter and return true if all pass function all(func) { return function() { var parameters = arraySlice.call(arguments); var length = parameters.length; if(length === 1 && is.array(parameters[0])) { // support array parameters = parameters[0]; length = parameters.length; } var results = []; for (var i = 0; i < length; i++) { results.push(func.call(null, parameters[i])); } for (i = 0; i < results.length; i++) { if(!results[i]) { return false; } } return true; }; } // helper function which call predicate function per parameter and return true if any pass function any(func) { return function() { var parameters = arraySlice.call(arguments); var length = parameters.length; if(length === 1 && is.array(parameters[0])) { // support array parameters = parameters[0]; length = parameters.length; } var results = []; for (var i = 0; i < length; i++) { results.push(func.call(null, parameters[i])); } for (i = 0; i < results.length; i++) { if(results[i]) { return true; } } return false; }; } // Type checks /* -------------------------------------------------------------------------- */ // is a given value Arguments? is.arguments = function(value) { // fallback check is for IE return is.not.null(value) && (toString.call(value) === '[object Arguments]' || (typeof value === 'object' && 'callee' in value)); }; // is a given value Array? is.array = Array.isArray || function(value) { // check native isArray first return toString.call(value) === '[object Array]'; }; // is a given value Boolean? is.boolean = function(value) { return value === true || value === false || toString.call(value) === '[object Boolean]'; }; // is a given value Date Object? is.date = function(value) { return toString.call(value) === '[object Date]'; }; // is a given value Error object? is.error = function(value) { return toString.call(value) === '[object Error]'; }; // is a given value function? is.function = function(value) { // fallback check is for IE return toString.call(value) === '[object Function]' || typeof value === 'function'; }; // is a given value NaN? is.nan = function(value) { // NaN is number :) Also it is the only value which does not equal itself return is.number(value) && value !== value; }; // is a given value null? is.null = function(value) { return value === null || toString.call(value) === '[object Null]'; }; // is a given value number? is.number = function(value) { return toString.call(value) === '[object Number]'; }; // is a given value object? is.object = function(value) { var type = typeof value; return type === 'function' || type === 'object' && !!value; }; // is a given value RegExp? is.regexp = function(value) { return toString.call(value) === '[object RegExp]'; }; // are given values same type? // prevent NaN, Number same type check is.sameType = function(value1, value2) { if(is.nan(value1) || is.nan(value2)) { return is.nan(value1) === is.nan(value2); } return toString.call(value1) === toString.call(value2); }; // sameType method does not support 'all' and 'any' interfaces is.sameType.api = ['not']; // is a given value String? is.string = function(value) { return toString.call(value) === '[object String]'; }; // is a given value Char? is.char = function(value) { return is.string(value) && value.length === 1; }; // is a given value undefined? is.undefined = function(value) { return value === void 0; }; // Presence checks /* -------------------------------------------------------------------------- */ //is a given value empty? Objects, arrays, strings is.empty = function(value) { if(is.object(value)){ var num = Object.getOwnPropertyNames(value).length; if(num === 0 || (num === 1 && is.array(value)) || (num === 2 && is.arguments(value))){ return true; } return false; } else { return value === ''; } }; // is a given value existy? is.existy = function(value) { return value !== null && value !== undefined; }; // is a given value truthy? is.truthy = function(value) { return is.existy(value) && value !== false && is.not.nan(value) && value !== "" && value !== 0; }; // is a given value falsy? is.falsy = not(is.truthy); // is a given value space? // horizantal tab: 9, line feed: 10, vertical tab: 11, form feed: 12, carriage return: 13, space: 32 is.space = function(value) { if(is.string(value)) { var characterCode = value.charCodeAt(0); return (characterCode > 8 && characterCode < 14) || characterCode === 32; } else { return false; } }; // Arithmetic checks /* -------------------------------------------------------------------------- */ // are given values equal? supports numbers, strings, regexps, booleans // TODO: Add object and array support is.equal = function(value1, value2) { // check 0 and -0 equity with Infinity and -Infinity if(is.all.number(value1, value2)) { return value1 === value2 && 1 / value1 === 1 / value2; } // check regexps as strings too if(is.all.string(value1, value2) || is.all.regexp(value1, value2)) { return '' + value1 === '' + value2; } if(is.all.boolean(value1, value2)) { return value1 === value2; } return false; }; // equal method does not support 'all' and 'any' interfaces is.equal.api = ['not']; // is a given number even? is.even = function(numb) { return is.number(numb) && numb % 2 === 0; }; // is a given number odd? is.odd = function(numb) { return is.number(numb) && numb % 2 !== 0; }; // is a given number positive? is.positive = function(numb) { return is.number(numb) && numb > 0; }; // is a given number negative? is.negative = function(numb) { return is.number(numb) && numb < 0; }; // is a given number above minimum parameter? is.above = function(numb, min) { return is.all.number(numb, min) && numb > min; }; // above method does not support 'all' and 'any' interfaces is.above.api = ['not']; // is a given number above maximum parameter? is.under = function(numb, max) { return is.all.number(numb, max) && numb < max; }; // least method does not support 'all' and 'any' interfaces is.under.api = ['not']; // is a given number within minimum and maximum parameters? is.within = function(numb, min, max) { return is.all.number(numb, min, max) && numb > min && numb < max; }; // within method does not support 'all' and 'any' interfaces is.within.api = ['not']; // is a given number decimal? is.decimal = function(numb) { return is.number(numb) && numb % 1 !== 0; }; // is a given number integer? is.integer = function(numb) { return is.number(numb) && numb % 1 === 0; }; // is a given number finite? is.finite = isFinite || function(numb) { return numb !== Infinity && numb !== -Infinity && is.not.nan(numb); }; // is a given number infinite? is.infinite = not(is.finite); // Regexp checks /* -------------------------------------------------------------------------- */ // Steven Levithan, Jan Goyvaerts: Regular Expressions Cookbook // Scott Gonzalez: Email address validation // eppPhone match extensible provisioning protocol format // nanpPhone match north american number plan format // dateString match m/d/yy and mm/dd/yyyy, allowing any combination of one or two digits for the day and month, and two or four digits for the year // time match hours, minutes, and seconds, 24-hour clock var regexps = { url: /^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$/, email: /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))$/i, creditCard: /^(?:(4[0-9]{12}(?:[0-9]{3})?)|(5[1-5][0-9]{14})|(6(?:011|5[0-9]{2})[0-9]{12})|(3[47][0-9]{13})|(3(?:0[0-5]|[68][0-9])[0-9]{11})|((?:2131|1800|35[0-9]{3})[0-9]{11}))$/, alphaNumeric: /^[A-Za-z0-9]+$/, timeString: /^(2[0-3]|[01]?[0-9]):([0-5]?[0-9]):([0-5]?[0-9])$/, dateString: /^(1[0-2]|0?[1-9])\/(3[01]|[12][0-9]|0?[1-9])\/(?:[0-9]{2})?[0-9]{2}$/, usZipCode: /^[0-9]{5}(?:-[0-9]{4})?$/, caPostalCode: /^(?!.*[DFIOQU])[A-VXY][0-9][A-Z]?[0-9][A-Z][0-9]$/, ukPostCode: /^[A-Z]{1,2}[0-9R][0-9A-Z]?[0-9][ABD-HJLNP-UW-Z]{2}$/, nanpPhone: /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/, eppPhone: /^\+[0-9]{1,3}\.[0-9]{4,14}(?:x.+)?$/, socialSecurityNumber: /^(?!000|666)[0-8][0-9]{2}-(?!00)[0-9]{2}-(?!0000)[0-9]{4}$/, affirmative: /^(?:1|t(?:rue)?|y(?:es)?|ok(?:ay)?)$/ }; // create regexp checks methods from 'regexp' object for(var regexp in regexps) { if(regexps.hasOwnProperty(regexp)) { regexpCheck(regexp, regexps); } } function regexpCheck(regexp, regexps) { is[regexp] = function(value) { return regexps[regexp].test(value); }; } // String checks /* -------------------------------------------------------------------------- */ // is a given string inculde parameter substring? is.include = String.prototype.includes || function(str, substr) { return str.indexOf(substr) > -1; }; // include method does not support 'all' and 'any' interfaces is.include.api = ['not']; // is a given string all uppercase? is.upperCase = function(str) { return is.string(str) && str === str.toUpperCase(); }; // is a given string all lowercase? is.lowerCase = function(str) { return is.string(str) && str === str.toLowerCase(); }; // is string start with a given startWith parameter? is.startWith = function(str, startWith) { return is.string(str) && str.indexOf(startWith) === 0; }; // startWith method does not support 'all' and 'any' interfaces is.startWith.api = ['not']; // is string end with a given endWith parameter? is.endWith = function(str, endWith) { return is.string(str) && str.indexOf(endWith) === str.length - endWith.length; }; // endWith method does not support 'all' and 'any' interfaces is.endWith.api = ['not']; // is a given string or sentence capitalized? is.capitalized = function(str) { if(is.not.string(str)) { return false; } var words = str.split(' '); var capitalized = []; for(var i = 0; i < words.length; i++) { capitalized.push(words[i][0] === words[i][0].toUpperCase()); } return is.all.truthy.apply(null, capitalized); }; // Time checks /* -------------------------------------------------------------------------- */ var days = ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday']; var months = ['january', 'february', 'march', 'april', 'may', 'june', 'july', 'august', 'september', 'october', 'november', 'december']; // is a given date indicate today? is.today = function(obj) { var now = new Date(); var todayString = now.toDateString(); return is.date(obj) && obj.toDateString() === todayString; }; // is a given date indicate yesterday? is.yesterday = function(obj) { var now = new Date(); var yesterdayString = new Date(now.setDate(now.getDate() - 1)).toDateString(); return is.date(obj) && obj.toDateString() === yesterdayString; }; // is a given date indicate tomorrow? is.tomorrow = function(obj) { var now = new Date(); var tomorrowString = new Date(now.setDate(now.getDate() + 1)).toDateString(); return is.date(obj) && obj.toDateString() === tomorrowString; }; // is a given date past? is.past = function(obj) { var now = new Date(); return is.date(obj) && obj.getTime() < now.getTime(); }; // is a given date future? is.future = not(is.past); // is a given dates day equal given dayString parameter? is.day = function(obj, dayString) { return is.date(obj) && dayString.toLowerCase() === days[obj.getDay()]; }; // day method does not support 'all' and 'any' interfaces is.day.api = ['not']; // is a given dates month equal given monthString parameter? is.month = function(obj, monthString) { return is.date(obj) && monthString.toLowerCase() === months[obj.getMonth()]; }; // month method does not support 'all' and 'any' interfaces is.month.api = ['not']; // is a given dates year equal given year parameter? is.year = function(obj, year) { return is.date(obj) && is.number(year) && year === obj.getFullYear(); }; // year method does not support 'all' and 'any' interfaces is.year.api = ['not']; // is a given date weekend? // 6: Saturday, 0: Sunday is.weekend = function(obj) { return is.date(obj) && (obj.getDay() === 6 || obj.getDay() === 0); }; // is a given date weekday? is.weekday = not(is.weekend); // is date within given range? is.inDateRange = function(obj, startObj, endObj) { if(is.not.date(obj) || is.not.date(startObj) || is.not.date(endObj)) { return false; } var givenDate = obj.getTime(); var start = startObj.getTime(); var end = endObj.getTime(); return givenDate > start && givenDate < end; }; // inDateRange method does not support 'all' and 'any' interfaces is.inDateRange.api = ['not']; // is a given date in last week range? is.inLastWeek = function(obj) { return is.inDateRange(obj, new Date(new Date().setDate(new Date().getDate() - 7)), new Date()); }; // is a given date in last month range? is.inLastMonth = function(obj) { return is.inDateRange(obj, new Date(new Date().setMonth(new Date().getMonth() - 1)), new Date()); }; // is a given date in last year range? is.inLastYear = function(obj) { return is.inDateRange(obj, new Date(new Date().setFullYear(new Date().getFullYear() - 1)), new Date()); }; // is a given date in next week range? is.inNextWeek = function(obj) { return is.inDateRange(obj, new Date(), new Date(new Date().setDate(new Date().getDate() + 7))); }; // is a given date in next month range? is.inNextMonth = function(obj) { return is.inDateRange(obj, new Date(), new Date(new Date().setMonth(new Date().getMonth() + 1))); }; // is a given date in next year range? is.inNextYear = function(obj) { return is.inDateRange(obj, new Date(), new Date(new Date().setFullYear(new Date().getFullYear() + 1))); }; // is a given date in the parameter quarter? is.quarterOfYear = function(obj, quarterNumber) { return is.date(obj) && is.number(quarterNumber) && quarterNumber === Math.floor((obj.getMonth() + 3) / 3); }; // quarterOfYear method does not support 'all' and 'any' interfaces is.quarterOfYear.api = ['not']; // is a given date in daylight saving time? is.dayLightSavingTime = function(obj) { var january = new Date(obj.getFullYear(), 0, 1); var july = new Date(obj.getFullYear(), 6, 1); var stdTimezoneOffset = Math.max(january.getTimezoneOffset(), july.getTimezoneOffset()); return obj.getTimezoneOffset() < stdTimezoneOffset; }; // Environment checks /* -------------------------------------------------------------------------- */ // check if library is used as a Node.js module if(typeof window !== 'undefined') { // store navigator properties to use later var userAgent = 'navigator' in window && 'userAgent' in navigator && navigator.userAgent.toLowerCase() || ''; var vendor = 'navigator' in window && 'vendor' in navigator && navigator.vendor.toLowerCase() || ''; var appVersion = 'navigator' in window && 'appVersion' in navigator && navigator.appVersion.toLowerCase() || ''; // is current browser chrome? is.chrome = function() { return /chrome|chromium/i.test(userAgent) && /google inc/.test(vendor); }; // chrome method does not support 'all' and 'any' interfaces is.chrome.api = ['not']; // is current browser firefox? is.firefox = function() { return /firefox/i.test(userAgent); }; // firefox method does not support 'all' and 'any' interfaces is.firefox.api = ['not']; // is current browser internet explorer? // parameter is optional is.ie = function(version) { if(!version) { return /msie/i.test(userAgent); } return new RegExp('msie ' + version).test(userAgent); }; // ie method does not support 'all' and 'any' interfaces is.ie.api = ['not']; // is current browser opera? is.opera = function() { return /opr/i.test(userAgent); }; // opera method does not support 'all' and 'any' interfaces is.opera.api = ['not']; // is current browser safari? is.safari = function() { return /safari/i.test(userAgent) && /apple computer/i.test(vendor); }; // safari method does not support 'all' and 'any' interfaces is.safari.api = ['not']; // is current device ios? is.ios = function() { return is.iphone() || is.ipad() || is.ipod(); }; // ios method does not support 'all' and 'any' interfaces is.ios.api = ['not']; // is current device iphone? is.iphone = function() { return /iphone/i.test(userAgent); }; // iphone method does not support 'all' and 'any' interfaces is.iphone.api = ['not']; // is current device ipad? is.ipad = function() { return /ipad/i.test(userAgent); }; // ipad method does not support 'all' and 'any' interfaces is.ipad.api = ['not']; // is current device ipod? is.ipod = function() { return /ipod/i.test(userAgent); }; // ipod method does not support 'all' and 'any' interfaces is.ipod.api = ['not']; // is current device android? is.android = function() { return /android/i.test(userAgent); }; // android method does not support 'all' and 'any' interfaces is.android.api = ['not']; // is current device android phone? is.androidPhone = function() { return /android/i.test(userAgent) && /mobile/i.test(userAgent); }; // androidPhone method does not support 'all' and 'any' interfaces is.androidPhone.api = ['not']; // is current device android tablet? is.androidTablet = function() { return /android/i.test(userAgent) && !/mobile/i.test(userAgent); }; // androidTablet method does not support 'all' and 'any' interfaces is.androidTablet.api = ['not']; // is current device blackberry? is.blackberry = function() { return /blackberry/i.test(userAgent); }; // blackberry method does not support 'all' and 'any' interfaces is.blackberry.api = ['not']; // is current device desktop? is.desktop = function() { return is.not.mobile() && is.not.tablet(); }; // desktop method does not support 'all' and 'any' interfaces is.desktop.api = ['not']; // is current operating system linux? is.linux = function() { return /linux/i.test(appVersion); }; // linux method does not support 'all' and 'any' interfaces is.linux.api = ['not']; // is current operating system mac? is.mac = function() { return /mac/i.test(appVersion); }; // mac method does not support 'all' and 'any' interfaces is.mac.api = ['not']; // is current operating system windows? is.windows = function() { return /win/i.test(appVersion); }; // windows method does not support 'all' and 'any' interfaces is.windows.api = ['not']; // is current device windows phone? is.windowsPhone = function() { return is.windows() && /phone/i.test(userAgent); }; // windowsPhone method does not support 'all' and 'any' interfaces is.windowsPhone.api = ['not']; // is current device windows tablet? is.windowsTablet = function() { return is.windows() && is.not.windowsPhone() && /touch/i.test(userAgent); }; // windowsTablet method does not support 'all' and 'any' interfaces is.windowsTablet.api = ['not']; // is current device mobile? is.mobile = function() { return is.iphone() || is.ipod() || is.androidPhone() || is.blackberry() || is.windowsPhone(); }; // mobile method does not support 'all' and 'any' interfaces is.mobile.api = ['not']; // is current device tablet? is.tablet = function() { return is.ipad() || is.androidTablet() || is.windowsTablet(); }; // tablet method does not support 'all' and 'any' interfaces is.tablet.api = ['not']; // is current state online? is.online = function() { return navigator.onLine; }; // online method does not support 'all' and 'any' interfaces is.online.api = ['not']; // is current state offline? is.offline = not(is.online); // offline method does not support 'all' and 'any' interfaces is.offline.api = ['not']; } // Object checks /* -------------------------------------------------------------------------- */ // has a given object got parameterized count property? is.propertyCount = function(obj, count) { if(!is.object(obj) || !is.number(count)) { return false; } if(Object.keys) { return Object.keys(obj).length === count; } var properties = [], property; for(property in obj) { if (hasOwnProperty.call(obj, property)) { properties.push(property); } } return properties.length === count; }; // propertyCount method does not support 'all' and 'any' interfaces is.propertyCount.api = ['not']; // is given object has parameterized property? is.propertyDefined = function(obj, property) { return is.object(obj) && is.string(property) && property in obj; }; // propertyDefined method does not support 'all' and 'any' interfaces is.propertyDefined.api = ['not']; // is a given object window? // setInterval method is only available for window object is.windowObject = function(obj) { return typeof obj === 'object' && 'setInterval' in obj; }; // Array checks /* -------------------------------------------------------------------------- */ // is a given item in an array? is.inArray = function(val, arr){ if(is.not.array(arr)) { return false; } for(var i = 0; i < arr.length; i++) { if (arr[i] === val) return true; } return false; }; // inArray method does not support 'all' and 'any' interfaces is.inArray.api = ['not']; // is a given array sorted? is.sorted = function(arr) { if(is.not.array(arr)) { return false; } for(var i = 0; i < arr.length; i++) { if(arr[i] > arr[i + 1]) return false; } return true; }; // API // Set 'not', 'all' and 'any' interfaces to methods based on their api property /* -------------------------------------------------------------------------- */ function setInterfaces() { var options = is; for(var option in options) { if(hasOwnProperty.call(options, option) && is.function(options[option])) { var interfaces = options[option].api || ['not', 'all', 'any']; for (var i = 0; i < interfaces.length; i++) { if(interfaces[i] === 'not') { is.not[option] = not(is[option]); } if(interfaces[i] === 'all') { is.all[option] = all(is[option]); } if(interfaces[i] === 'any') { is.any[option] = any(is[option]); } } } } } setInterfaces(); // Configuration methods // Intentionally added after setInterfaces function /* -------------------------------------------------------------------------- */ // set optional regexps to methods if you think they suck is.setRegexp = function(regexp, regexpName) { for(var r in regexps) { if(hasOwnProperty.call(regexps, r) && (regexpName === r)) { regexps[r] = regexp; } } }; // change namespace of library to prevent name collisions // var preferredName = is.setNamespace(); // preferredName.odd(3); // => true is.setNamespace = function() { root.is = previousIs; return this; }; return is; }));
/* * Globalize Culture en-ZA * * http://github.com/jquery/globalize * * Copyright Software Freedom Conservancy, Inc. * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license * * This file was generated by the Globalize Culture Generator * Translation: bugs found in this file need to be fixed in the generator */ (function( window, undefined ) { var Globalize; if ( typeof require !== "undefined" && typeof exports !== "undefined" && typeof module !== "undefined" ) { // Assume CommonJS Globalize = require( "globalize" ); } else { // Global variable Globalize = window.Globalize; } Globalize.addCultureInfo( "en-ZA", "default", { name: "en-ZA", englishName: "English (South Africa)", nativeName: "English (South Africa)", numberFormat: { ",": " ", percent: { pattern: ["-n%","n%"], ",": " " }, currency: { pattern: ["$-n","$ n"], ",": " ", ".": ",", symbol: "R" } }, calendars: { standard: { patterns: { d: "yyyy/MM/dd", D: "dd MMMM yyyy", t: "hh:mm tt", T: "hh:mm:ss tt", f: "dd MMMM yyyy hh:mm tt", F: "dd MMMM yyyy hh:mm:ss tt", M: "dd MMMM", Y: "MMMM yyyy" } } } }); }( this ));
/* * Globalize Culture no * * http://github.com/jquery/globalize * * Copyright Software Freedom Conservancy, Inc. * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license * * This file was generated by the Globalize Culture Generator * Translation: bugs found in this file need to be fixed in the generator */ (function( window, undefined ) { var Globalize; if ( typeof require !== "undefined" && typeof exports !== "undefined" && typeof module !== "undefined" ) { // Assume CommonJS Globalize = require( "globalize" ); } else { // Global variable Globalize = window.Globalize; } Globalize.addCultureInfo( "no", "default", { name: "no", englishName: "Norwegian", nativeName: "norsk", language: "no", numberFormat: { ",": " ", ".": ",", negativeInfinity: "-INF", positiveInfinity: "INF", percent: { ",": " ", ".": "," }, currency: { pattern: ["$ -n","$ n"], ",": " ", ".": ",", symbol: "kr" } }, calendars: { standard: { "/": ".", firstDay: 1, days: { names: ["søndag","mandag","tirsdag","onsdag","torsdag","fredag","lørdag"], namesAbbr: ["sø","ma","ti","on","to","fr","lø"], namesShort: ["sø","ma","ti","on","to","fr","lø"] }, months: { names: ["januar","februar","mars","april","mai","juni","juli","august","september","oktober","november","desember",""], namesAbbr: ["jan","feb","mar","apr","mai","jun","jul","aug","sep","okt","nov","des",""] }, AM: null, PM: null, patterns: { d: "dd.MM.yyyy", D: "d. MMMM yyyy", t: "HH:mm", T: "HH:mm:ss", f: "d. MMMM yyyy HH:mm", F: "d. MMMM yyyy HH:mm:ss", M: "d. MMMM", Y: "MMMM yyyy" } } } }); }( this ));
var env = require('../../../spec/environment.js'); exports.config = { seleniumAddress: env.seleniumAddress, framework: 'jasmine2', specs: ['fail_spec.js'], baseUrl: env.baseUrl, plugins: [{ path: '../index.js', failOnWarning: true, failOnError: true }] };
$(function () { //Basic Map var basicMap = new GMaps({ el: '#gmap_basic_example', lat: -12.043333, lng: -77.028333 }); //Markers var markers = new GMaps({ div: '#gmap_markers', lat: -12.043333, lng: -77.028333 }); markers.addMarker({ lat: -12.043333, lng: -77.03, title: 'Lima', details: { database_id: 42, author: 'HPNeo' }, click: function (e) { if (console.log) console.log(e); alert('You clicked in this marker'); } }); markers.addMarker({ lat: -12.042, lng: -77.028333, title: 'Marker with InfoWindow', infoWindow: { content: '<p>HTML Content</p>' } }); //Static maps var staticMap = GMaps.staticMapURL({ size: [$('#gmap_static_map').width(), 400], lat: -12.043333, lng: -77.028333 }); $('<img/>').attr('src', staticMap).appendTo('#gmap_static_map'); //Static maps with markers var staticMapWithMarkers = GMaps.staticMapURL({ size: [$('#gmap_static_map_with_markers').width(), 400], lat: -12.043333, lng: -77.028333, markers: [ { lat: -12.043333, lng: -77.028333 }, { lat: -12.045333, lng: -77.034, size: 'small' }, { lat: -12.045633, lng: -77.022, color: 'blue' } ] }); $('<img/>').attr('src', staticMapWithMarkers).appendTo('#gmap_static_map_with_markers'); //Static maps with polyline var path = [ [-12.040397656836609, -77.03373871559225], [-12.040248585302038, -77.03993927003302], [-12.050047116528843, -77.02448169303511], [-12.044804866577001, -77.02154422636042], [-12.040397656836609, -77.03373871559225], ]; var staticMapPolyline = GMaps.staticMapURL({ size: [$('#gmap_static_map_polyline').width(), 400], lat: -12.043333, lng: -77.028333, polyline: { path: path, strokeColor: '#131540', strokeOpacity: 0.6, strokeWeight: 6 // fillColor: '#ffaf2ecc' } }); $('<img/>').attr('src', staticMapPolyline).appendTo('#gmap_static_map_polyline'); //Panorama var panorama = GMaps.createPanorama({ el: '#gmap_panorama', lat: 42.3455, lng: -71.0983 }); });
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = toBlock; var _generated = require("../validators/generated"); var _generated2 = require("../builders/generated"); function toBlock(node, parent) { if ((0, _generated.isBlockStatement)(node)) { return node; } let blockNodes = []; if ((0, _generated.isEmptyStatement)(node)) { blockNodes = []; } else { if (!(0, _generated.isStatement)(node)) { if ((0, _generated.isFunction)(parent)) { node = (0, _generated2.returnStatement)(node); } else { node = (0, _generated2.expressionStatement)(node); } } blockNodes = [node]; } return (0, _generated2.blockStatement)(blockNodes); }
/* * Remodal - v1.0.6 * Responsive, lightweight, fast, synchronized with CSS animations, fully customizable modal window plugin with declarative configuration and hash tracking. * http://vodkabears.github.io/remodal/ * * Made by Ilya Makarov * Under MIT License */ !(function(root, factory) { if (typeof define === 'function' && define.amd) { define(['jquery'], function($) { return factory(root, $); }); } else if (typeof exports === 'object') { factory(root, require('jquery')); } else { factory(root, root.jQuery || root.Zepto); } })(this, function(global, $) { 'use strict'; /** * Name of the plugin * @private * @const * @type {String} */ var PLUGIN_NAME = 'remodal'; /** * Namespace for CSS and events * @private * @const * @type {String} */ var NAMESPACE = global.REMODAL_GLOBALS && global.REMODAL_GLOBALS.NAMESPACE || PLUGIN_NAME; /** * Animationstart event with vendor prefixes * @private * @const * @type {String} */ var ANIMATIONSTART_EVENTS = $.map( ['animationstart', 'webkitAnimationStart', 'MSAnimationStart', 'oAnimationStart'], function(eventName) { return eventName + '.' + NAMESPACE; } ).join(' '); /** * Animationend event with vendor prefixes * @private * @const * @type {String} */ var ANIMATIONEND_EVENTS = $.map( ['animationend', 'webkitAnimationEnd', 'MSAnimationEnd', 'oAnimationEnd'], function(eventName) { return eventName + '.' + NAMESPACE; } ).join(' '); /** * Default settings * @private * @const * @type {Object} */ var DEFAULTS = $.extend({ hashTracking: true, closeOnConfirm: true, closeOnCancel: true, closeOnEscape: true, closeOnOutsideClick: true, modifier: '' }, global.REMODAL_GLOBALS && global.REMODAL_GLOBALS.DEFAULTS); /** * States of the Remodal * @private * @const * @enum {String} */ var STATES = { CLOSING: 'closing', CLOSED: 'closed', OPENING: 'opening', OPENED: 'opened' }; /** * Reasons of the state change. * @private * @const * @enum {String} */ var STATE_CHANGE_REASONS = { CONFIRMATION: 'confirmation', CANCELLATION: 'cancellation' }; /** * Is animation supported? * @private * @const * @type {Boolean} */ var IS_ANIMATION = (function() { var style = document.createElement('div').style; return style.animationName !== undefined || style.WebkitAnimationName !== undefined || style.MozAnimationName !== undefined || style.msAnimationName !== undefined || style.OAnimationName !== undefined; })(); /** * Is iOS? * @private * @const * @type {Boolean} */ var IS_IOS = /iPad|iPhone|iPod/.test(navigator.platform); /** * Current modal * @private * @type {Remodal} */ var current; /** * Scrollbar position * @private * @type {Number} */ var scrollTop; /** * Returns an animation duration * @private * @param {jQuery} $elem * @returns {Number} */ function getAnimationDuration($elem) { if ( IS_ANIMATION && $elem.css('animation-name') === 'none' && $elem.css('-webkit-animation-name') === 'none' && $elem.css('-moz-animation-name') === 'none' && $elem.css('-o-animation-name') === 'none' && $elem.css('-ms-animation-name') === 'none' ) { return 0; } var duration = $elem.css('animation-duration') || $elem.css('-webkit-animation-duration') || $elem.css('-moz-animation-duration') || $elem.css('-o-animation-duration') || $elem.css('-ms-animation-duration') || '0s'; var delay = $elem.css('animation-delay') || $elem.css('-webkit-animation-delay') || $elem.css('-moz-animation-delay') || $elem.css('-o-animation-delay') || $elem.css('-ms-animation-delay') || '0s'; var iterationCount = $elem.css('animation-iteration-count') || $elem.css('-webkit-animation-iteration-count') || $elem.css('-moz-animation-iteration-count') || $elem.css('-o-animation-iteration-count') || $elem.css('-ms-animation-iteration-count') || '1'; var max; var len; var num; var i; duration = duration.split(', '); delay = delay.split(', '); iterationCount = iterationCount.split(', '); // The 'duration' size is the same as the 'delay' size for (i = 0, len = duration.length, max = Number.NEGATIVE_INFINITY; i < len; i++) { num = parseFloat(duration[i]) * parseInt(iterationCount[i], 10) + parseFloat(delay[i]); if (num > max) { max = num; } } return num; } /** * Returns a scrollbar width * @private * @returns {Number} */ function getScrollbarWidth() { if ($(document.body).height() <= $(window).height()) { return 0; } var outer = document.createElement('div'); var inner = document.createElement('div'); var widthNoScroll; var widthWithScroll; outer.style.visibility = 'hidden'; outer.style.width = '100px'; document.body.appendChild(outer); widthNoScroll = outer.offsetWidth; // Force scrollbars outer.style.overflow = 'scroll'; // Add inner div inner.style.width = '100%'; outer.appendChild(inner); widthWithScroll = inner.offsetWidth; // Remove divs outer.parentNode.removeChild(outer); return widthNoScroll - widthWithScroll; } /** * Locks the screen * @private */ function lockScreen() { if (IS_IOS) { return; } var $html = $('html'); var lockedClass = namespacify('is-locked'); var paddingRight; var $body; if (!$html.hasClass(lockedClass)) { $body = $(document.body); // Zepto does not support '-=', '+=' in the `css` method paddingRight = parseInt($body.css('padding-right'), 10) + getScrollbarWidth(); $body.css('padding-right', paddingRight + 'px'); $html.addClass(lockedClass); } } /** * Unlocks the screen * @private */ function unlockScreen() { if (IS_IOS) { return; } var $html = $('html'); var lockedClass = namespacify('is-locked'); var paddingRight; var $body; if ($html.hasClass(lockedClass)) { $body = $(document.body); // Zepto does not support '-=', '+=' in the `css` method paddingRight = parseInt($body.css('padding-right'), 10) - getScrollbarWidth(); $body.css('padding-right', paddingRight + 'px'); $html.removeClass(lockedClass); } } /** * Sets a state for an instance * @private * @param {Remodal} instance * @param {STATES} state * @param {Boolean} isSilent If true, Remodal does not trigger events * @param {String} Reason of a state change. */ function setState(instance, state, isSilent, reason) { var newState = namespacify('is', state); var allStates = [namespacify('is', STATES.CLOSING), namespacify('is', STATES.OPENING), namespacify('is', STATES.CLOSED), namespacify('is', STATES.OPENED)].join(' '); instance.$bg .removeClass(allStates) .addClass(newState); instance.$overlay .removeClass(allStates) .addClass(newState); instance.$wrapper .removeClass(allStates) .addClass(newState); instance.$modal .removeClass(allStates) .addClass(newState); instance.state = state; !isSilent && instance.$modal.trigger({ type: state, reason: reason }, [{ reason: reason }]); } /** * Synchronizes with the animation * @param {Function} doBeforeAnimation * @param {Function} doAfterAnimation * @param {Remodal} instance */ function syncWithAnimation(doBeforeAnimation, doAfterAnimation, instance) { var runningAnimationsCount = 0; var handleAnimationStart = function(e) { if (e.target !== this) { return; } runningAnimationsCount++; }; var handleAnimationEnd = function(e) { if (e.target !== this) { return; } if (--runningAnimationsCount === 0) { // Remove event listeners $.each(['$bg', '$overlay', '$wrapper', '$modal'], function(index, elemName) { instance[elemName].off(ANIMATIONSTART_EVENTS + ' ' + ANIMATIONEND_EVENTS); }); doAfterAnimation(); } }; $.each(['$bg', '$overlay', '$wrapper', '$modal'], function(index, elemName) { instance[elemName] .on(ANIMATIONSTART_EVENTS, handleAnimationStart) .on(ANIMATIONEND_EVENTS, handleAnimationEnd); }); doBeforeAnimation(); // If the animation is not supported by a browser or its duration is 0 if ( getAnimationDuration(instance.$bg) === 0 && getAnimationDuration(instance.$overlay) === 0 && getAnimationDuration(instance.$wrapper) === 0 && getAnimationDuration(instance.$modal) === 0 ) { // Remove event listeners $.each(['$bg', '$overlay', '$wrapper', '$modal'], function(index, elemName) { instance[elemName].off(ANIMATIONSTART_EVENTS + ' ' + ANIMATIONEND_EVENTS); }); doAfterAnimation(); } } /** * Closes immediately * @private * @param {Remodal} instance */ function halt(instance) { if (instance.state === STATES.CLOSED) { return; } $.each(['$bg', '$overlay', '$wrapper', '$modal'], function(index, elemName) { instance[elemName].off(ANIMATIONSTART_EVENTS + ' ' + ANIMATIONEND_EVENTS); }); instance.$bg.removeClass(instance.settings.modifier); instance.$overlay.removeClass(instance.settings.modifier).hide(); instance.$wrapper.hide(); unlockScreen(); setState(instance, STATES.CLOSED, true); } /** * Parses a string with options * @private * @param str * @returns {Object} */ function parseOptions(str) { var obj = {}; var arr; var len; var val; var i; // Remove spaces before and after delimiters str = str.replace(/\s*:\s*/g, ':').replace(/\s*,\s*/g, ','); // Parse a string arr = str.split(','); for (i = 0, len = arr.length; i < len; i++) { arr[i] = arr[i].split(':'); val = arr[i][1]; // Convert a string value if it is like a boolean if (typeof val === 'string' || val instanceof String) { val = val === 'true' || (val === 'false' ? false : val); } // Convert a string value if it is like a number if (typeof val === 'string' || val instanceof String) { val = !isNaN(val) ? +val : val; } obj[arr[i][0]] = val; } return obj; } /** * Generates a string separated by dashes and prefixed with NAMESPACE * @private * @param {...String} * @returns {String} */ function namespacify() { var result = NAMESPACE; for (var i = 0; i < arguments.length; ++i) { result += '-' + arguments[i]; } return result; } /** * Handles the hashchange event * @private * @listens hashchange */ function handleHashChangeEvent() { var id = location.hash.replace('#', ''); var instance; var $elem; if (!id) { // Check if we have currently opened modal and animation was completed if (current && current.state === STATES.OPENED && current.settings.hashTracking) { current.close(); } } else { // Catch syntax error if your hash is bad try { $elem = $( '[data-' + PLUGIN_NAME + '-id="' + id + '"]' ); } catch (err) {} if ($elem && $elem.length) { instance = $[PLUGIN_NAME].lookup[$elem.data(PLUGIN_NAME)]; if (instance && instance.settings.hashTracking) { instance.open(); } } } } /** * Remodal constructor * @constructor * @param {jQuery} $modal * @param {Object} options */ function Remodal($modal, options) { var $body = $(document.body); var remodal = this; remodal.settings = $.extend({}, DEFAULTS, options); remodal.index = $[PLUGIN_NAME].lookup.push(remodal) - 1; remodal.state = STATES.CLOSED; remodal.$overlay = $('.' + namespacify('overlay')); if (!remodal.$overlay.length) { remodal.$overlay = $('<div>').addClass(namespacify('overlay') + ' ' + namespacify('is', STATES.CLOSED)).hide(); $body.append(remodal.$overlay); } remodal.$bg = $('.' + namespacify('bg')).addClass(namespacify('is', STATES.CLOSED)); remodal.$modal = $modal .addClass( NAMESPACE + ' ' + namespacify('is-initialized') + ' ' + remodal.settings.modifier + ' ' + namespacify('is', STATES.CLOSED)) .attr('tabindex', '-1'); remodal.$wrapper = $('<div>') .addClass( namespacify('wrapper') + ' ' + remodal.settings.modifier + ' ' + namespacify('is', STATES.CLOSED)) .hide() .append(remodal.$modal); $body.append(remodal.$wrapper); // Add the event listener for the close button remodal.$wrapper.on('click.' + NAMESPACE, '[data-' + PLUGIN_NAME + '-action="close"]', function(e) { e.preventDefault(); remodal.close(); }); // Add the event listener for the cancel button remodal.$wrapper.on('click.' + NAMESPACE, '[data-' + PLUGIN_NAME + '-action="cancel"]', function(e) { e.preventDefault(); remodal.$modal.trigger(STATE_CHANGE_REASONS.CANCELLATION); if (remodal.settings.closeOnCancel) { remodal.close(STATE_CHANGE_REASONS.CANCELLATION); } }); // Add the event listener for the confirm button remodal.$wrapper.on('click.' + NAMESPACE, '[data-' + PLUGIN_NAME + '-action="confirm"]', function(e) { e.preventDefault(); remodal.$modal.trigger(STATE_CHANGE_REASONS.CONFIRMATION); if (remodal.settings.closeOnConfirm) { remodal.close(STATE_CHANGE_REASONS.CONFIRMATION); } }); // Add the event listener for the overlay remodal.$wrapper.on('click.' + NAMESPACE, function(e) { var $target = $(e.target); if (!$target.hasClass(namespacify('wrapper'))) { return; } if (remodal.settings.closeOnOutsideClick) { remodal.close(); } }); } /** * Opens a modal window * @public */ Remodal.prototype.open = function() { var remodal = this; var id; // Check if the animation was completed if (remodal.state === STATES.OPENING || remodal.state === STATES.CLOSING) { return; } id = remodal.$modal.attr('data-' + PLUGIN_NAME + '-id'); if (id && remodal.settings.hashTracking) { scrollTop = $(window).scrollTop(); location.hash = id; } if (current && current !== remodal) { halt(current); } current = remodal; lockScreen(); remodal.$bg.addClass(remodal.settings.modifier); remodal.$overlay.addClass(remodal.settings.modifier).show(); remodal.$wrapper.show().scrollTop(0); remodal.$modal.focus(); syncWithAnimation( function() { setState(remodal, STATES.OPENING); }, function() { setState(remodal, STATES.OPENED); }, remodal); }; /** * Closes a modal window * @public * @param {String} reason */ Remodal.prototype.close = function(reason) { var remodal = this; // Check if the animation was completed if (remodal.state === STATES.OPENING || remodal.state === STATES.CLOSING) { return; } if ( remodal.settings.hashTracking && remodal.$modal.attr('data-' + PLUGIN_NAME + '-id') === location.hash.substr(1) ) { location.hash = ''; $(window).scrollTop(scrollTop); } syncWithAnimation( function() { setState(remodal, STATES.CLOSING, false, reason); }, function() { remodal.$bg.removeClass(remodal.settings.modifier); remodal.$overlay.removeClass(remodal.settings.modifier).hide(); remodal.$wrapper.hide(); unlockScreen(); setState(remodal, STATES.CLOSED, false, reason); }, remodal); }; /** * Returns a current state of a modal * @public * @returns {STATES} */ Remodal.prototype.getState = function() { return this.state; }; /** * Destroys a modal * @public */ Remodal.prototype.destroy = function() { var lookup = $[PLUGIN_NAME].lookup; var instanceCount; halt(this); this.$wrapper.remove(); delete lookup[this.index]; instanceCount = $.grep(lookup, function(instance) { return !!instance; }).length; if (instanceCount === 0) { this.$overlay.remove(); this.$bg.removeClass( namespacify('is', STATES.CLOSING) + ' ' + namespacify('is', STATES.OPENING) + ' ' + namespacify('is', STATES.CLOSED) + ' ' + namespacify('is', STATES.OPENED)); } }; /** * Special plugin object for instances * @public * @type {Object} */ $[PLUGIN_NAME] = { lookup: [] }; /** * Plugin constructor * @constructor * @param {Object} options * @returns {JQuery} */ $.fn[PLUGIN_NAME] = function(opts) { var instance; var $elem; this.each(function(index, elem) { $elem = $(elem); if ($elem.data(PLUGIN_NAME) == null) { instance = new Remodal($elem, opts); $elem.data(PLUGIN_NAME, instance.index); if ( instance.settings.hashTracking && $elem.attr('data-' + PLUGIN_NAME + '-id') === location.hash.substr(1) ) { instance.open(); } } else { instance = $[PLUGIN_NAME].lookup[$elem.data(PLUGIN_NAME)]; } }); return instance; }; $(document).ready(function() { // data-remodal-target opens a modal window with the special Id $(document).on('click', '[data-' + PLUGIN_NAME + '-target]', function(e) { e.preventDefault(); var elem = e.currentTarget; var id = elem.getAttribute('data-' + PLUGIN_NAME + '-target'); var $target = $('[data-' + PLUGIN_NAME + '-id="' + id + '"]'); $[PLUGIN_NAME].lookup[$target.data(PLUGIN_NAME)].open(); }); // Auto initialization of modal windows // They should have the 'remodal' class attribute // Also you can write the `data-remodal-options` attribute to pass params into the modal $(document).find('.' + NAMESPACE).each(function(i, container) { var $container = $(container); var options = $container.data(PLUGIN_NAME + '-options'); if (!options) { options = {}; } else if (typeof options === 'string' || options instanceof String) { options = parseOptions(options); } $container[PLUGIN_NAME](options); }); // Handles the keydown event $(document).on('keydown.' + NAMESPACE, function(e) { if (current && current.settings.closeOnEscape && current.state === STATES.OPENED && e.keyCode === 27) { current.close(); } }); // Handles the hashchange event $(window).on('hashchange.' + NAMESPACE, handleHashChangeEvent); }); });
// Sticky Plugin v1.0.4 for jQuery // ============= // Author: Anthony Garand // Improvements by German M. Bravo (Kronuz) and Ruud Kamphuis (ruudk) // Improvements by Leonardo C. Daronco (daronco) // Created: 02/14/2011 // Date: 07/20/2015 // Website: http://stickyjs.com/ // Description: Makes an element on the page stick on the screen as you scroll // It will only set the 'top' and 'position' of your element, you // might need to adjust the width in some cases. (function (factory) { if (typeof define === 'function' && define.amd) { // AMD. Register as an anonymous module. define(['jquery'], factory); } else if (typeof module === 'object' && module.exports) { // Node/CommonJS module.exports = factory(require('jquery')); } else { // Browser globals factory(jQuery); } }(function ($) { var slice = Array.prototype.slice; // save ref to original slice() var splice = Array.prototype.splice; // save ref to original slice() var defaults = { topSpacing: 0, bottomSpacing: 0, className: 'is-sticky', wrapperClassName: 'sticky-wrapper', center: false, getWidthFrom: '', widthFromWrapper: true, // works only when .getWidthFrom is empty responsiveWidth: false, zIndex: 'inherit' }, $window = $(window), $document = $(document), sticked = [], windowHeight = $window.height(), scroller = function() { var scrollTop = $window.scrollTop(), documentHeight = $document.height(), dwh = documentHeight - windowHeight, extra = (scrollTop > dwh) ? dwh - scrollTop : 0; for (var i = 0, l = sticked.length; i < l; i++) { var s = sticked[i], elementTop = s.stickyWrapper.offset().top, etse = elementTop - s.topSpacing - extra; //update height in case of dynamic content s.stickyWrapper.css('height', s.stickyElement.outerHeight()); if (scrollTop <= etse) { if (s.currentTop !== null) { s.stickyElement .css({ 'width': '', 'position': '', 'top': '', 'z-index': '' }); s.stickyElement.parent().removeClass(s.className); s.stickyElement.trigger('sticky-end', [s]); s.currentTop = null; } } else { var newTop = documentHeight - s.stickyElement.outerHeight() - s.topSpacing - s.bottomSpacing - scrollTop - extra; if (newTop < 0) { newTop = newTop + s.topSpacing; } else { newTop = s.topSpacing; } if (s.currentTop !== newTop) { var newWidth; if (s.getWidthFrom) { padding = s.stickyElement.innerWidth() - s.stickyElement.width(); newWidth = $(s.getWidthFrom).width() - padding || null; } else if (s.widthFromWrapper) { newWidth = s.stickyWrapper.width(); } if (newWidth == null) { newWidth = s.stickyElement.width(); } s.stickyElement .css('width', newWidth) .css('position', 'fixed') .css('top', newTop) .css('z-index', s.zIndex); s.stickyElement.parent().addClass(s.className); if (s.currentTop === null) { s.stickyElement.trigger('sticky-start', [s]); } else { // sticky is started but it have to be repositioned s.stickyElement.trigger('sticky-update', [s]); } if (s.currentTop === s.topSpacing && s.currentTop > newTop || s.currentTop === null && newTop < s.topSpacing) { // just reached bottom || just started to stick but bottom is already reached s.stickyElement.trigger('sticky-bottom-reached', [s]); } else if(s.currentTop !== null && newTop === s.topSpacing && s.currentTop < newTop) { // sticky is started && sticked at topSpacing && overflowing from top just finished s.stickyElement.trigger('sticky-bottom-unreached', [s]); } s.currentTop = newTop; } // Check if sticky has reached end of container and stop sticking var stickyWrapperContainer = s.stickyWrapper.parent(); var unstick = (s.stickyElement.offset().top + s.stickyElement.outerHeight() >= stickyWrapperContainer.offset().top + stickyWrapperContainer.outerHeight()) && (s.stickyElement.offset().top <= s.topSpacing); if( unstick ) { s.stickyElement .css('position', 'absolute') .css('top', '') .css('bottom', 0) .css('z-index', ''); } else { s.stickyElement .css('position', 'fixed') .css('top', newTop) .css('bottom', '') .css('z-index', s.zIndex); } } } }, resizer = function() { windowHeight = $window.height(); for (var i = 0, l = sticked.length; i < l; i++) { var s = sticked[i]; var newWidth = null; if (s.getWidthFrom) { if (s.responsiveWidth) { newWidth = $(s.getWidthFrom).width(); } } else if(s.widthFromWrapper) { newWidth = s.stickyWrapper.width(); } if (newWidth != null) { s.stickyElement.css('width', newWidth); } } }, methods = { init: function(options) { return this.each(function() { var o = $.extend({}, defaults, options); var stickyElement = $(this); var stickyId = stickyElement.attr('id'); var wrapperId = stickyId ? stickyId + '-' + defaults.wrapperClassName : defaults.wrapperClassName; var wrapper = $('<div></div>') .attr('id', wrapperId) .addClass(o.wrapperClassName); stickyElement.wrapAll(function() { if ($(this).parent("#" + wrapperId).length == 0) { return wrapper; } }); var stickyWrapper = stickyElement.parent(); if (o.center) { stickyWrapper.css({width:stickyElement.outerWidth(),marginLeft:"auto",marginRight:"auto"}); } if (stickyElement.css("float") === "right") { stickyElement.css({"float":"none"}).parent().css({"float":"right"}); } o.stickyElement = stickyElement; o.stickyWrapper = stickyWrapper; o.currentTop = null; sticked.push(o); methods.setWrapperHeight(this); methods.setupChangeListeners(this); }); }, setWrapperHeight: function(stickyElement) { var element = $(stickyElement); var stickyWrapper = element.parent(); if (stickyWrapper) { stickyWrapper.css('height', element.outerHeight()); } }, setupChangeListeners: function(stickyElement) { if (window.MutationObserver) { var mutationObserver = new window.MutationObserver(function(mutations) { if (mutations[0].addedNodes.length || mutations[0].removedNodes.length) { methods.setWrapperHeight(stickyElement); } }); mutationObserver.observe(stickyElement, {subtree: true, childList: true}); } else { if (window.addEventListener) { stickyElement.addEventListener('DOMNodeInserted', function() { methods.setWrapperHeight(stickyElement); }, false); stickyElement.addEventListener('DOMNodeRemoved', function() { methods.setWrapperHeight(stickyElement); }, false); } else if (window.attachEvent) { stickyElement.attachEvent('onDOMNodeInserted', function() { methods.setWrapperHeight(stickyElement); }); stickyElement.attachEvent('onDOMNodeRemoved', function() { methods.setWrapperHeight(stickyElement); }); } } }, update: scroller, unstick: function(options) { return this.each(function() { var that = this; var unstickyElement = $(that); var removeIdx = -1; var i = sticked.length; while (i-- > 0) { if (sticked[i].stickyElement.get(0) === that) { splice.call(sticked,i,1); removeIdx = i; } } if(removeIdx !== -1) { unstickyElement.unwrap(); unstickyElement .css({ 'width': '', 'position': '', 'top': '', 'float': '', 'z-index': '' }) ; } }); } }; // should be more efficient than using $window.scroll(scroller) and $window.resize(resizer): if (window.addEventListener) { window.addEventListener('scroll', scroller, false); window.addEventListener('resize', resizer, false); } else if (window.attachEvent) { window.attachEvent('onscroll', scroller); window.attachEvent('onresize', resizer); } $.fn.sticky = function(method) { if (methods[method]) { return methods[method].apply(this, slice.call(arguments, 1)); } else if (typeof method === 'object' || !method ) { return methods.init.apply( this, arguments ); } else { $.error('Method ' + method + ' does not exist on jQuery.sticky'); } }; $.fn.unstick = function(method) { if (methods[method]) { return methods[method].apply(this, slice.call(arguments, 1)); } else if (typeof method === 'object' || !method ) { return methods.unstick.apply( this, arguments ); } else { $.error('Method ' + method + ' does not exist on jQuery.sticky'); } }; $(function() { setTimeout(scroller, 0); }); }));
/* Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ CKEDITOR.plugins.setLang( 'codemirror', 'sl', { toolbar: 'Izvorna koda', searchCode: 'Search Source', autoFormat: 'Format Selection', commentSelectedRange: 'Comment Selection', uncommentSelectedRange: 'Uncomment Selection', autoCompleteToggle: 'Enable/Disable HTML Tag Autocomplete' });
/** * angular-strap * @version v2.0.0-beta.4 - 2014-01-20 * @link http://mgcrea.github.io/angular-strap * @author Olivier Louvignes <olivier@mg-crea.com> * @license MIT License, http://www.opensource.org/licenses/MIT */ 'use strict'; angular.module('mgcrea.ngStrap.dropdown', ['mgcrea.ngStrap.tooltip']).run([ '$templateCache', function ($templateCache) { var template = '' + '<ul tabindex="-1" class="dropdown-menu" role="menu">' + '<li role="presentation" ng-class="{divider: item.divider}" ng-repeat="item in content" >' + '<a role="menuitem" tabindex="-1" href="{{item.href}}" ng-if="!item.divider" ng-click="$eval(item.click);$hide()" ng-bind="item.text"></a>' + '</li>' + '</ul>'; $templateCache.put('$dropdown', template); } ]).provider('$dropdown', function () { var defaults = this.defaults = { animation: 'animation-fade', prefixClass: 'dropdown', placement: 'bottom-left', template: '$dropdown', trigger: 'click', container: false, keyboard: true, html: false, delay: 0 }; this.$get = [ '$window', '$tooltip', function ($window, $tooltip) { var bodyEl = angular.element($window.document.body); var matchesSelector = Element.prototype.matchesSelector || Element.prototype.webkitMatchesSelector || Element.prototype.mozMatchesSelector || Element.prototype.msMatchesSelector || Element.prototype.oMatchesSelector; function DropdownFactory(element, config) { var $dropdown = {}; var options = angular.extend({}, defaults, config); $dropdown = $tooltip(element, options); $dropdown.$onKeyDown = function (evt) { if (!/(38|40)/.test(evt.keyCode)) return; evt.preventDefault(); evt.stopPropagation(); var items = angular.element($dropdown.$element[0].querySelectorAll('li:not(.divider) a')); if (!items.length) return; var index; angular.forEach(items, function (el, i) { if (matchesSelector && matchesSelector.call(el, ':focus')) index = i; }); if (evt.keyCode === 38 && index > 0) index--; else if (evt.keyCode === 40 && index < items.length - 1) index++; else if (angular.isUndefined(index)) index = 0; items.eq(index)[0].focus(); }; var show = $dropdown.show; $dropdown.show = function () { show(); setTimeout(function () { options.keyboard && $dropdown.$element.on('keydown', $dropdown.$onKeyDown); bodyEl.on('click', onBodyClick); }); }; var hide = $dropdown.hide; $dropdown.hide = function () { options.keyboard && $dropdown.$element.off('keydown', $dropdown.$onKeyDown); bodyEl.off('click', onBodyClick); hide(); }; function onBodyClick(evt) { if (evt.target === element[0]) return; return evt.target !== element[0] && $dropdown.hide(); } return $dropdown; } return DropdownFactory; } ]; }).directive('bsDropdown', [ '$window', '$location', '$sce', '$dropdown', function ($window, $location, $sce, $dropdown) { return { restrict: 'EAC', scope: true, link: function postLink(scope, element, attr, transclusion) { var options = { scope: scope }; angular.forEach([ 'placement', 'container', 'delay', 'trigger', 'keyboard', 'html', 'animation', 'template' ], function (key) { if (angular.isDefined(attr[key])) options[key] = attr[key]; }); attr.bsDropdown && scope.$watch(attr.bsDropdown, function (newValue, oldValue) { scope.content = newValue; }, true); var dropdown = $dropdown(element, options); scope.$on('$destroy', function () { dropdown.destroy(); options = null; dropdown = null; }); } }; } ]);
/* ========================================================== * bootstrap-alert.js v2.2.1 * http://twitter.github.com/bootstrap/javascript.html#alerts * ========================================================== * Copyright 2012 Twitter, 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. * ========================================================== */ !function ($) { "use strict"; // jshint ;_; /* ALERT CLASS DEFINITION * ====================== */ var dismiss = '[data-dismiss="alert"]' , Alert = function (el) { $(el).on('click', dismiss, this.close) } Alert.prototype.close = function (e) { var $this = $(this) , selector = $this.attr('data-target') , $parent if (!selector) { selector = $this.attr('href') selector = selector && selector.replace(/.*(?=#[^\s]*$)/, '') //strip for ie7 } $parent = $(selector) e && e.preventDefault() $parent.length || ($parent = $this.hasClass('alert') ? $this : $this.parent()) $parent.trigger(e = $.Event('close')) if (e.isDefaultPrevented()) return $parent.removeClass('in') function removeElement() { $parent .trigger('closed') .remove() } $.support.transition && $parent.hasClass('fade') ? $parent.on($.support.transition.end, removeElement) : removeElement() } /* ALERT PLUGIN DEFINITION * ======================= */ $.fn.alert = function (option) { return this.each(function () { var $this = $(this) , data = $this.data('alert') if (!data) $this.data('alert', (data = new Alert(this))) if (typeof option == 'string') data[option].call($this) }) } $.fn.alert.Constructor = Alert /* ALERT DATA-API * ============== */ $(document).on('click.alert.data-api', dismiss, Alert.prototype.close) }(window.jQuery);
YUI.add('loader-base', function(Y) { /** * The YUI loader core * @module loader * @submodule loader-base */ if (!YUI.Env[Y.version]) { (function() { var VERSION = Y.version, BUILD = '/build/', ROOT = VERSION + BUILD, CDN_BASE = Y.Env.base, GALLERY_VERSION = 'gallery-2010.10.20-19-33', TNT = '2in3', TNT_VERSION = '4', YUI2_VERSION = '2.8.1', COMBO_BASE = CDN_BASE + 'combo?', META = { version: VERSION, root: ROOT, base: Y.Env.base, comboBase: COMBO_BASE, skin: { defaultSkin: 'sam', base: 'assets/skins/', path: 'skin.css', after: ['cssreset', 'cssfonts', 'cssgrids', 'cssbase', 'cssreset-context', 'cssfonts-context']}, groups: {}, patterns: {} }, groups = META.groups, yui2Update = function(tnt, yui2) { var root = TNT + '.' + (tnt || TNT_VERSION) + '/' + (yui2 || YUI2_VERSION) + BUILD; groups.yui2.base = CDN_BASE + root; groups.yui2.root = root; }, galleryUpdate = function(tag) { var root = (tag || GALLERY_VERSION) + BUILD; groups.gallery.base = CDN_BASE + root; groups.gallery.root = root; }; groups[VERSION] = {}; groups.gallery = { ext: false, combine: true, comboBase: COMBO_BASE, update: galleryUpdate, patterns: { 'gallery-': { }, 'gallerycss-': { type: 'css' } } }; groups.yui2 = { combine: true, ext: false, comboBase: COMBO_BASE, update: yui2Update, patterns: { 'yui2-': { configFn: function(me) { if (/-skin|reset|fonts|grids|base/.test(me.name)) { me.type = 'css'; me.path = me.path.replace(/\.js/, '.css'); // this makes skins in builds earlier than // 2.6.0 work as long as combine is false me.path = me.path.replace(/\/yui2-skin/, '/assets/skins/sam/yui2-skin'); } } } } }; galleryUpdate(); yui2Update(); YUI.Env[VERSION] = META; }()); } /** * Loader dynamically loads script and css files. It includes the dependency * info for the version of the library in use, and will automatically pull in * dependencies for the modules requested. It supports rollup files and will * automatically use these when appropriate in order to minimize the number of * http connections required to load all of the dependencies. It can load the * files from the Yahoo! CDN, and it can utilize the combo service provided on * this network to reduce the number of http connections required to download * YUI files. * * @module loader * @submodule loader-base */ var NOT_FOUND = {}, NO_REQUIREMENTS = [], MAX_URL_LENGTH = (Y.UA.ie) ? 2048 : 8192, GLOBAL_ENV = YUI.Env, GLOBAL_LOADED = GLOBAL_ENV._loaded, CSS = 'css', JS = 'js', INTL = 'intl', VERSION = Y.version, ROOT_LANG = '', YObject = Y.Object, oeach = YObject.each, YArray = Y.Array, _queue = GLOBAL_ENV._loaderQueue, META = GLOBAL_ENV[VERSION], SKIN_PREFIX = 'skin-', L = Y.Lang, ON_PAGE = GLOBAL_ENV.mods, modulekey, cache, _path = function(dir, file, type, nomin) { var path = dir + '/' + file; if (!nomin) { path += '-min'; } path += '.' + (type || CSS); return path; }; /** * The component metadata is stored in Y.Env.meta. * Part of the loader module. * @property Env.meta * @for YUI */ Y.Env.meta = META; /** * Loader dynamically loads script and css files. It includes the dependency * info for the version of the library in use, and will automatically pull in * dependencies for the modules requested. It supports rollup files and will * automatically use these when appropriate in order to minimize the number of * http connections required to load all of the dependencies. It can load the * files from the Yahoo! CDN, and it can utilize the combo service provided on * this network to reduce the number of http connections required to download * YUI files. * * While the loader can be instantiated by the end user, it normally is not. * @see YUI.use for the normal use case. The use function automatically will * pull in missing dependencies. * * @constructor * @class Loader * @param {object} o an optional set of configuration options. Valid options: * <ul> * <li>base: * The base dir</li> * <li>comboBase: * The YUI combo service base dir. Ex: http://yui.yahooapis.com/combo?</li> * <li>root: * The root path to prepend to module names for the combo service. * Ex: 2.5.2/build/</li> * <li>filter:. * * A filter to apply to result urls. This filter will modify the default * path for all modules. The default path for the YUI library is the * minified version of the files (e.g., event-min.js). The filter property * can be a predefined filter or a custom filter. The valid predefined * filters are: * <dl> * <dt>DEBUG</dt> * <dd>Selects the debug versions of the library (e.g., event-debug.js). * This option will automatically include the Logger widget</dd> * <dt>RAW</dt> * <dd>Selects the non-minified version of the library (e.g., event.js). * </dd> * </dl> * You can also define a custom filter, which must be an object literal * containing a search expression and a replace string: * <pre> * myFilter: &#123; * 'searchExp': "-min\\.js", * 'replaceStr': "-debug.js" * &#125; * </pre> * * </li> * <li>filters: per-component filter specification. If specified * for a given component, this overrides the filter config</li> * <li>combine: * Use the YUI combo service to reduce the number of http connections * required to load your dependencies</li> * <li>ignore: * A list of modules that should never be dynamically loaded</li> * <li>force: * A list of modules that should always be loaded when required, even if * already present on the page</li> * <li>insertBefore: * Node or id for a node that should be used as the insertion point for * new nodes</li> * <li>charset: * charset for dynamic nodes (deprecated, use jsAttributes or cssAttributes) * </li> * <li>jsAttributes: object literal containing attributes to add to script * nodes</li> * <li>cssAttributes: object literal containing attributes to add to link * nodes</li> * <li>timeout: * The number of milliseconds before a timeout occurs when dynamically * loading nodes. If not set, there is no timeout</li> * <li>context: * execution context for all callbacks</li> * <li>onSuccess: * callback for the 'success' event</li> * <li>onFailure: callback for the 'failure' event</li> * <li>onCSS: callback for the 'CSSComplete' event. When loading YUI * components with CSS the CSS is loaded first, then the script. This * provides a moment you can tie into to improve * the presentation of the page while the script is loading.</li> * <li>onTimeout: * callback for the 'timeout' event</li> * <li>onProgress: * callback executed each time a script or css file is loaded</li> * <li>modules: * A list of module definitions. See Loader.addModule for the supported * module metadata</li> * <li>groups: * A list of group definitions. Each group can contain specific definitions * for base, comboBase, combine, and accepts a list of modules. See above * for the description of these properties.</li> * <li>2in3: the version of the YUI 2 in 3 wrapper to use. The intrinsic * support for YUI 2 modules in YUI 3 relies on versions of the YUI 2 * components inside YUI 3 module wrappers. These wrappers * change over time to accomodate the issues that arise from running YUI 2 * in a YUI 3 sandbox.</li> * <li>yui2: when using the 2in3 project, you can select the version of * YUI 2 to use. Valid values * are 2.2.2, 2.3.1, 2.4.1, 2.5.2, 2.6.0, * 2.7.0, 2.8.0, and 2.8.1 [default] -- plus all versions of YUI 2 * going forward.</li> * </ul> */ Y.Loader = function(o) { var defaults = META.modules, self = this; modulekey = META.md5; /** * Internal callback to handle multiple internal insert() calls * so that css is inserted prior to js * @property _internalCallback * @private */ // self._internalCallback = null; /** * Callback that will be executed when the loader is finished * with an insert * @method onSuccess * @type function */ // self.onSuccess = null; /** * Callback that will be executed if there is a failure * @method onFailure * @type function */ // self.onFailure = null; /** * Callback for the 'CSSComplete' event. When loading YUI components * with CSS the CSS is loaded first, then the script. This provides * a moment you can tie into to improve the presentation of the page * while the script is loading. * @method onCSS * @type function */ // self.onCSS = null; /** * Callback executed each time a script or css file is loaded * @method onProgress * @type function */ // self.onProgress = null; /** * Callback that will be executed if a timeout occurs * @method onTimeout * @type function */ // self.onTimeout = null; /** * The execution context for all callbacks * @property context * @default {YUI} the YUI instance */ self.context = Y; /** * Data that is passed to all callbacks * @property data */ // self.data = null; /** * Node reference or id where new nodes should be inserted before * @property insertBefore * @type string|HTMLElement */ // self.insertBefore = null; /** * The charset attribute for inserted nodes * @property charset * @type string * @deprecated , use cssAttributes or jsAttributes. */ // self.charset = null; /** * An object literal containing attributes to add to link nodes * @property cssAttributes * @type object */ // self.cssAttributes = null; /** * An object literal containing attributes to add to script nodes * @property jsAttributes * @type object */ // self.jsAttributes = null; /** * The base directory. * @property base * @type string * @default http://yui.yahooapis.com/[YUI VERSION]/build/ */ self.base = Y.Env.meta.base; /** * Base path for the combo service * @property comboBase * @type string * @default http://yui.yahooapis.com/combo? */ self.comboBase = Y.Env.meta.comboBase; /* * Base path for language packs. */ // self.langBase = Y.Env.meta.langBase; // self.lang = ""; /** * If configured, the loader will attempt to use the combo * service for YUI resources and configured external resources. * @property combine * @type boolean * @default true if a base dir isn't in the config */ self.combine = o.base && (o.base.indexOf(self.comboBase.substr(0, 20)) > -1); /** * Max url length for combo urls. The default is 2048 for * internet explorer, and 8192 otherwise. This is the URL * limit for the Yahoo! hosted combo servers. If consuming * a different combo service that has a different URL limit * it is possible to override this default by supplying * the maxURLLength config option. The config option will * only take effect if lower than the default. * * Browsers: * IE: 2048 * Other A-Grade Browsers: Higher that what is typically supported * 'capable' mobile browsers: * * Servers: * Apache: 8192 * * @property maxURLLength * @type int */ self.maxURLLength = MAX_URL_LENGTH; /** * Ignore modules registered on the YUI global * @property ignoreRegistered * @default false */ // self.ignoreRegistered = false; /** * Root path to prepend to module path for the combo * service * @property root * @type string * @default [YUI VERSION]/build/ */ self.root = Y.Env.meta.root; /** * Timeout value in milliseconds. If set, self value will be used by * the get utility. the timeout event will fire if * a timeout occurs. * @property timeout * @type int */ self.timeout = 0; /** * A list of modules that should not be loaded, even if * they turn up in the dependency tree * @property ignore * @type string[] */ // self.ignore = null; /** * A list of modules that should always be loaded, even * if they have already been inserted into the page. * @property force * @type string[] */ // self.force = null; self.forceMap = {}; /** * Should we allow rollups * @property allowRollup * @type boolean * @default true */ self.allowRollup = true; /** * A filter to apply to result urls. This filter will modify the default * path for all modules. The default path for the YUI library is the * minified version of the files (e.g., event-min.js). The filter property * can be a predefined filter or a custom filter. The valid predefined * filters are: * <dl> * <dt>DEBUG</dt> * <dd>Selects the debug versions of the library (e.g., event-debug.js). * This option will automatically include the Logger widget</dd> * <dt>RAW</dt> * <dd>Selects the non-minified version of the library (e.g., event.js). * </dd> * </dl> * You can also define a custom filter, which must be an object literal * containing a search expression and a replace string: * <pre> * myFilter: &#123; * 'searchExp': "-min\\.js", * 'replaceStr': "-debug.js" * &#125; * </pre> * @property filter * @type string| {searchExp: string, replaceStr: string} */ // self.filter = null; /** * per-component filter specification. If specified for a given * component, this overrides the filter config. * @property filters * @type object */ self.filters = {}; /** * The list of requested modules * @property required * @type {string: boolean} */ self.required = {}; /** * If a module name is predefined when requested, it is checked againsts * the patterns provided in this property. If there is a match, the * module is added with the default configuration. * * At the moment only supporting module prefixes, but anticipate * supporting at least regular expressions. * @property patterns * @type Object */ // self.patterns = Y.merge(Y.Env.meta.patterns); self.patterns = {}; /** * The library metadata * @property moduleInfo */ // self.moduleInfo = Y.merge(Y.Env.meta.moduleInfo); self.moduleInfo = {}; self.groups = Y.merge(Y.Env.meta.groups); /** * Provides the information used to skin the skinnable components. * The following skin definition would result in 'skin1' and 'skin2' * being loaded for calendar (if calendar was requested), and * 'sam' for all other skinnable components: * * <code> * skin: { * * // The default skin, which is automatically applied if not * // overriden by a component-specific skin definition. * // Change this in to apply a different skin globally * defaultSkin: 'sam', * * // This is combined with the loader base property to get * // the default root directory for a skin. ex: * // http://yui.yahooapis.com/2.3.0/build/assets/skins/sam/ * base: 'assets/skins/', * * // Any component-specific overrides can be specified here, * // making it possible to load different skins for different * // components. It is possible to load more than one skin * // for a given component as well. * overrides: { * calendar: ['skin1', 'skin2'] * } * } * </code> * @property skin */ self.skin = Y.merge(Y.Env.meta.skin); /* * Map of conditional modules * @since 3.2.0 */ self.conditions = {}; // map of modules with a hash of modules that meet the requirement // self.provides = {}; self.config = o; self._internal = true; cache = GLOBAL_ENV._renderedMods; if (cache) { oeach(cache, function(v, k) { self.moduleInfo[k] = Y.merge(v); }); cache = GLOBAL_ENV._conditions; oeach(cache, function(v, k) { self.conditions[k] = Y.merge(v); }); } else { oeach(defaults, self.addModule, self); } if (!GLOBAL_ENV._renderedMods) { GLOBAL_ENV._renderedMods = Y.merge(self.moduleInfo); GLOBAL_ENV._conditions = Y.merge(self.conditions); } self._inspectPage(); self._internal = false; self._config(o); /** * List of rollup files found in the library metadata * @property rollups */ // self.rollups = null; /** * Whether or not to load optional dependencies for * the requested modules * @property loadOptional * @type boolean * @default false */ // self.loadOptional = false; /** * All of the derived dependencies in sorted order, which * will be populated when either calculate() or insert() * is called * @property sorted * @type string[] */ self.sorted = []; /** * Set when beginning to compute the dependency tree. * Composed of what YUI reports to be loaded combined * with what has been loaded by any instance on the page * with the version number specified in the metadata. * @property loaded * @type {string: boolean} */ self.loaded = GLOBAL_LOADED[VERSION]; /* * A list of modules to attach to the YUI instance when complete. * If not supplied, the sorted list of dependencies are applied. * @property attaching */ // self.attaching = null; /** * Flag to indicate the dependency tree needs to be recomputed * if insert is called again. * @property dirty * @type boolean * @default true */ self.dirty = true; /** * List of modules inserted by the utility * @property inserted * @type {string: boolean} */ self.inserted = {}; /** * List of skipped modules during insert() because the module * was not defined * @property skipped */ self.skipped = {}; // Y.on('yui:load', self.loadNext, self); self.tested = {}; /* * Cached sorted calculate results * @property results * @since 3.2.0 */ //self.results = {}; }; Y.Loader.prototype = { FILTER_DEFS: { RAW: { 'searchExp': '-min\\.js', 'replaceStr': '.js' }, DEBUG: { 'searchExp': '-min\\.js', 'replaceStr': '-debug.js' } }, _inspectPage: function() { oeach(ON_PAGE, function(v, k) { if (v.details) { var m = this.moduleInfo[k], req = v.details.requires, mr = m && m.requires; if (m) { if (!m._inspected && req && mr.length != req.length) { // console.log('deleting ' + m.name); delete m.expanded; } } else { m = this.addModule(v.details, k); } m._inspected = true; } }, this); }, // returns true if b is not loaded, and is required // directly or by means of modules it supersedes. _requires: function(mod1, mod2) { var i, rm, after_map, s, info = this.moduleInfo, m = info[mod1], other = info[mod2]; // key = mod1 + mod2; // if (this.tested[key]) { // return this.tested[key]; // } // if (loaded[mod2] || !m || !other) { if (!m || !other) { return false; } rm = m.expanded_map; after_map = m.after_map; // check if this module should be sorted after the other // do this first to short circut circular deps if (after_map && (mod2 in after_map)) { return true; } after_map = other.after_map; // and vis-versa if (after_map && (mod1 in after_map)) { return false; } // check if this module requires one the other supersedes s = info[mod2] && info[mod2].supersedes; if (s) { for (i = 0; i < s.length; i++) { if (this._requires(mod1, s[i])) { return true; } } } s = info[mod1] && info[mod1].supersedes; if (s) { for (i = 0; i < s.length; i++) { if (this._requires(mod2, s[i])) { return false; } } } // check if this module requires the other directly // if (r && YArray.indexOf(r, mod2) > -1) { if (rm && (mod2 in rm)) { return true; } // external css files should be sorted below yui css if (m.ext && m.type == CSS && !other.ext && other.type == CSS) { return true; } return false; }, _config: function(o) { var i, j, val, f, group, groupName, self = this; // apply config values if (o) { for (i in o) { if (o.hasOwnProperty(i)) { val = o[i]; if (i == 'require') { self.require(val); } else if (i == 'skin') { Y.mix(self.skin, o[i], true); } else if (i == 'groups') { for (j in val) { if (val.hasOwnProperty(j)) { // Y.log('group: ' + j); groupName = j; group = val[j]; self.addGroup(group, groupName); } } } else if (i == 'modules') { // add a hash of module definitions oeach(val, self.addModule, self); } else if (i == 'gallery') { this.groups.gallery.update(val); } else if (i == 'yui2' || i == '2in3') { this.groups.yui2.update(o['2in3'], o.yui2); } else if (i == 'maxURLLength') { self[i] = Math.min(MAX_URL_LENGTH, val); } else { self[i] = val; } } } } // fix filter f = self.filter; if (L.isString(f)) { f = f.toUpperCase(); self.filterName = f; self.filter = self.FILTER_DEFS[f]; if (f == 'DEBUG') { self.require('yui-log', 'dump'); } } }, /** * Returns the skin module name for the specified skin name. If a * module name is supplied, the returned skin module name is * specific to the module passed in. * @method formatSkin * @param {string} skin the name of the skin. * @param {string} mod optional: the name of a module to skin. * @return {string} the full skin module name. */ formatSkin: function(skin, mod) { var s = SKIN_PREFIX + skin; if (mod) { s = s + '-' + mod; } return s; }, /** * Adds the skin def to the module info * @method _addSkin * @param {string} skin the name of the skin. * @param {string} mod the name of the module. * @param {string} parent parent module if this is a skin of a * submodule or plugin. * @return {string} the module name for the skin. * @private */ _addSkin: function(skin, mod, parent) { var mdef, pkg, name, info = this.moduleInfo, sinf = this.skin, ext = info[mod] && info[mod].ext; // Add a module definition for the module-specific skin css if (mod) { name = this.formatSkin(skin, mod); if (!info[name]) { mdef = info[mod]; pkg = mdef.pkg || mod; this.addModule({ name: name, group: mdef.group, type: 'css', after: sinf.after, path: (parent || pkg) + '/' + sinf.base + skin + '/' + mod + '.css', ext: ext }); // Y.log('adding skin ' + name + ', ' // + parent + ', ' + pkg + ', ' + info[name].path); } } return name; }, /** Add a new module group * <dl> * <dt>name:</dt> <dd>required, the group name</dd> * <dt>base:</dt> <dd>The base dir for this module group</dd> * <dt>root:</dt> <dd>The root path to add to each combo * resource path</dd> * <dt>combine:</dt> <dd>combo handle</dd> * <dt>comboBase:</dt> <dd>combo service base path</dd> * <dt>modules:</dt> <dd>the group of modules</dd> * </dl> * @method addGroup * @param {object} o An object containing the module data. * @param {string} name the group name. */ addGroup: function(o, name) { var mods = o.modules, self = this; name = name || o.name; o.name = name; self.groups[name] = o; if (o.patterns) { oeach(o.patterns, function(v, k) { v.group = name; self.patterns[k] = v; }); } if (mods) { oeach(mods, function(v, k) { v.group = name; self.addModule(v, k); }, self); } }, /** Add a new module to the component metadata. * <dl> * <dt>name:</dt> <dd>required, the component name</dd> * <dt>type:</dt> <dd>required, the component type (js or css) * </dd> * <dt>path:</dt> <dd>required, the path to the script from * "base"</dd> * <dt>requires:</dt> <dd>array of modules required by this * component</dd> * <dt>optional:</dt> <dd>array of optional modules for this * component</dd> * <dt>supersedes:</dt> <dd>array of the modules this component * replaces</dd> * <dt>after:</dt> <dd>array of modules the components which, if * present, should be sorted above this one</dd> * <dt>after_map:</dt> <dd>faster alternative to 'after' -- supply * a hash instead of an array</dd> * <dt>rollup:</dt> <dd>the number of superseded modules required * for automatic rollup</dd> * <dt>fullpath:</dt> <dd>If fullpath is specified, this is used * instead of the configured base + path</dd> * <dt>skinnable:</dt> <dd>flag to determine if skin assets should * automatically be pulled in</dd> * <dt>submodules:</dt> <dd>a hash of submodules</dd> * <dt>group:</dt> <dd>The group the module belongs to -- this * is set automatically when it is added as part of a group * configuration.</dd> * <dt>lang:</dt> * <dd>array of BCP 47 language tags of languages for which this * module has localized resource bundles, * e.g., ["en-GB","zh-Hans-CN"]</dd> * <dt>condition:</dt> * <dd>Specifies that the module should be loaded automatically if * a condition is met. This is an object with two fields: * [trigger] - the name of a module that can trigger the auto-load * [test] - a function that returns true when the module is to be * loaded. * </dd> * </dl> * @method addModule * @param {object} o An object containing the module data. * @param {string} name the module name (optional), required if not * in the module data. * @return {object} the module definition or null if * the object passed in did not provide all required attributes. */ addModule: function(o, name) { name = name || o.name; o.name = name; if (!o || !o.name) { return null; } if (!o.type) { o.type = JS; } if (!o.path && !o.fullpath) { o.path = _path(name, name, o.type); } o.supersedes = o.supersedes || o.use; o.ext = ('ext' in o) ? o.ext : (this._internal) ? false : true; o.requires = o.requires || []; // Handle submodule logic var subs = o.submodules, i, l, sup, s, smod, plugins, plug, j, langs, packName, supName, flatSup, flatLang, lang, ret, overrides, skinname, conditions = this.conditions, trigger; // , existing = this.moduleInfo[name], newr; this.moduleInfo[name] = o; if (!o.langPack && o.lang) { langs = YArray(o.lang); for (j = 0; j < langs.length; j++) { lang = langs[j]; packName = this.getLangPackName(lang, name); smod = this.moduleInfo[packName]; if (!smod) { smod = this._addLangPack(lang, o, packName); } } } if (subs) { sup = o.supersedes || []; l = 0; for (i in subs) { if (subs.hasOwnProperty(i)) { s = subs[i]; s.path = s.path || _path(name, i, o.type); s.pkg = name; s.group = o.group; if (s.supersedes) { sup = sup.concat(s.supersedes); } smod = this.addModule(s, i); sup.push(i); if (smod.skinnable) { o.skinnable = true; overrides = this.skin.overrides; if (overrides && overrides[i]) { for (j = 0; j < overrides[i].length; j++) { skinname = this._addSkin(overrides[i][j], i, name); sup.push(skinname); } } skinname = this._addSkin(this.skin.defaultSkin, i, name); sup.push(skinname); } // looks like we are expected to work out the metadata // for the parent module language packs from what is // specified in the child modules. if (s.lang && s.lang.length) { langs = YArray(s.lang); for (j = 0; j < langs.length; j++) { lang = langs[j]; packName = this.getLangPackName(lang, name); supName = this.getLangPackName(lang, i); smod = this.moduleInfo[packName]; if (!smod) { smod = this._addLangPack(lang, o, packName); } flatSup = flatSup || YArray.hash(smod.supersedes); if (!(supName in flatSup)) { smod.supersedes.push(supName); } o.lang = o.lang || []; flatLang = flatLang || YArray.hash(o.lang); if (!(lang in flatLang)) { o.lang.push(lang); } // Y.log('pack ' + packName + ' should supersede ' + supName); // Add rollup file, need to add to supersedes list too } } l++; } } o.supersedes = YObject.keys(YArray.hash(sup)); o.rollup = (l < 4) ? l : Math.min(l - 1, 4); } plugins = o.plugins; if (plugins) { for (i in plugins) { if (plugins.hasOwnProperty(i)) { plug = plugins[i]; plug.pkg = name; plug.path = plug.path || _path(name, i, o.type); plug.requires = plug.requires || []; plug.group = o.group; // plug.requires.push(name); this.addModule(plug, i); if (o.skinnable) { this._addSkin(this.skin.defaultSkin, i, name); } } } } if (o.condition) { trigger = o.condition.trigger; conditions[trigger] = conditions[trigger] || {}; conditions[trigger][name] = o.condition; o.after = o.after || []; o.after.push(trigger); } if (o.after) { o.after_map = YArray.hash(o.after); } // this.dirty = true; if (o.configFn) { ret = o.configFn(o); if (ret === false) { delete this.moduleInfo[name]; o = null; } } return o; }, /** * Add a requirement for one or more module * @method require * @param {string[] | string*} what the modules to load. */ require: function(what) { var a = (typeof what === 'string') ? arguments : what; this.dirty = true; Y.mix(this.required, YArray.hash(a)); }, /** * Returns an object containing properties for all modules required * in order to load the requested module * @method getRequires * @param {object} mod The module definition from moduleInfo. * @return {array} the expanded requirement list. */ getRequires: function(mod) { // if (mod.name == 'node-base') { // eval('debugger;'); // } if (!mod || mod._parsed) { // Y.log('returning no reqs for ' + mod.name); return NO_REQUIREMENTS; } var i, m, j, add, packName, lang, name = mod.name, cond, go, adddef = ON_PAGE[name] && ON_PAGE[name].details, d, r, old_mod, o, skinmod, skindef, intl = mod.lang || mod.intl, info = this.moduleInfo, hash; // pattern match leaves module stub that needs to be filled out if (mod.temp && adddef) { old_mod = mod; mod = this.addModule(adddef, name); mod.group = old_mod.group; mod.pkg = old_mod.pkg; delete mod.expanded; } if (mod.expanded && (!mod.langCache || mod.langCache == this.lang)) { // Y.log('already expanded ' + name + ', ' + mod.expanded); return mod.expanded; } d = []; hash = {}; r = mod.requires; o = mod.optional; // Y.log("getRequires: " + name + " (dirty:" + this.dirty + // ", expanded:" + mod.expanded + ")"); mod._parsed = true; for (i = 0; i < r.length; i++) { // Y.log(name + ' requiring ' + r[i]); if (!hash[r[i]]) { d.push(r[i]); hash[r[i]] = true; m = this.getModule(r[i]); if (m) { add = this.getRequires(m); intl = intl || (m.expanded_map && (INTL in m.expanded_map)); for (j = 0; j < add.length; j++) { d.push(add[j]); } } } } // get the requirements from superseded modules, if any r = mod.supersedes; if (r) { for (i = 0; i < r.length; i++) { if (!hash[r[i]]) { // if this module has submodules, the requirements list is // expanded to include the submodules. This is so we can // prevent dups when a submodule is already loaded and the // parent is requested. if (mod.submodules) { d.push(r[i]); } hash[r[i]] = true; m = this.getModule(r[i]); if (m) { add = this.getRequires(m); intl = intl || (m.expanded_map && (INTL in m.expanded_map)); for (j = 0; j < add.length; j++) { d.push(add[j]); } } } } } if (o && this.loadOptional) { for (i = 0; i < o.length; i++) { if (!hash[o[i]]) { d.push(o[i]); hash[o[i]] = true; m = info[o[i]]; if (m) { add = this.getRequires(m); intl = intl || (m.expanded_map && (INTL in m.expanded_map)); for (j = 0; j < add.length; j++) { d.push(add[j]); } } } } } cond = this.conditions[name]; if (cond) { oeach(cond, function(def, condmod) { if (!hash[condmod]) { go = def && ((def.ua && Y.UA[def.ua]) || (def.test && def.test(Y, r))); if (go) { hash[condmod] = true; d.push(condmod); m = this.getModule(condmod); // console.log('conditional', m); if (m) { add = this.getRequires(m); for (j = 0; j < add.length; j++) { d.push(add[j]); } } } } }, this); } // Create skin modules if (mod.skinnable) { skindef = this.skin.overrides; if (skindef && skindef[name]) { for (i = 0; i < skindef[name].length; i++) { skinmod = this._addSkin(skindef[name][i], name); d.push(skinmod); } } else { skinmod = this._addSkin(this.skin.defaultSkin, name); d.push(skinmod); } } mod._parsed = false; if (intl) { if (mod.lang && !mod.langPack && Y.Intl) { lang = Y.Intl.lookupBestLang(this.lang || ROOT_LANG, mod.lang); // Y.log('Best lang: ' + lang + ', this.lang: ' + // this.lang + ', mod.lang: ' + mod.lang); mod.langCache = this.lang; packName = this.getLangPackName(lang, name); if (packName) { d.unshift(packName); } } d.unshift(INTL); } mod.expanded_map = YArray.hash(d); mod.expanded = YObject.keys(mod.expanded_map); return mod.expanded; }, /** * Returns a hash of module names the supplied module satisfies. * @method getProvides * @param {string} name The name of the module. * @return {object} what this module provides. */ getProvides: function(name) { var m = this.getModule(name), o, s; // supmap = this.provides; if (!m) { return NOT_FOUND; } if (m && !m.provides) { o = {}; s = m.supersedes; if (s) { YArray.each(s, function(v) { Y.mix(o, this.getProvides(v)); }, this); } o[name] = true; m.provides = o; } return m.provides; }, // checkConditions: function() { // var self = this, // conds = self.conditions; // Y.Object.each(self.required, function(mod, name) { // var cond = conds[name]; // Y.Object.each(cond, function(def, condmod) { // if (def) { // var go = def.result || ((def.ua && Y.UA[def.ua]) || // (def.test && def.test(Y))); // def.result = go; // if (go) { // self.required[condmod] = true; // } // } // }); // }); // }, /** * Calculates the dependency tree, the result is stored in the sorted * property. * @method calculate * @param {object} o optional options object. * @param {string} type optional argument to prune modules. */ calculate: function(o, type) { if (o || type || this.dirty) { if (o) { this._config(o); } if (!this._init) { this._setup(); } this._explode(); // this.checkConditions(); if (this.allowRollup) { this._rollup(); } this._reduce(); this._sort(); } }, _addLangPack: function(lang, m, packName) { var name = m.name, packPath, existing = this.moduleInfo[packName]; if (!existing) { packPath = _path((m.pkg || name), packName, JS, true); this.addModule({ path: packPath, intl: true, langPack: true, ext: m.ext, group: m.group, supersedes: [] }, packName, true); if (lang) { Y.Env.lang = Y.Env.lang || {}; Y.Env.lang[lang] = Y.Env.lang[lang] || {}; Y.Env.lang[lang][name] = true; } } return this.moduleInfo[packName]; }, /** * Investigates the current YUI configuration on the page. By default, * modules already detected will not be loaded again unless a force * option is encountered. Called by calculate() * @method _setup * @private */ _setup: function() { var info = this.moduleInfo, name, i, j, m, l, packName; for (name in info) { if (info.hasOwnProperty(name)) { m = info[name]; if (m) { // remove dups m.requires = YObject.keys(YArray.hash(m.requires)); // Create lang pack modules if (m.lang && m.lang.length) { // Setup root package if the module has lang defined, // it needs to provide a root language pack packName = this.getLangPackName(ROOT_LANG, name); this._addLangPack(null, m, packName); } } } } //l = Y.merge(this.inserted); l = {}; // available modules if (!this.ignoreRegistered) { Y.mix(l, GLOBAL_ENV.mods); } // add the ignore list to the list of loaded packages if (this.ignore) { Y.mix(l, YArray.hash(this.ignore)); } // expand the list to include superseded modules for (j in l) { if (l.hasOwnProperty(j)) { Y.mix(l, this.getProvides(j)); } } // remove modules on the force list from the loaded list if (this.force) { for (i = 0; i < this.force.length; i++) { if (this.force[i] in l) { delete l[this.force[i]]; } } } Y.mix(this.loaded, l); this._init = true; }, /** * Builds a module name for a language pack * @method getLangPackName * @param {string} lang the language code. * @param {string} mname the module to build it for. * @return {string} the language pack module name. */ getLangPackName: function(lang, mname) { return ('lang/' + mname + ((lang) ? '_' + lang : '')); }, /** * Inspects the required modules list looking for additional * dependencies. Expands the required list to include all * required modules. Called by calculate() * @method _explode * @private */ _explode: function() { var r = this.required, m, reqs, done = {}, self = this; // the setup phase is over, all modules have been created self.dirty = false; oeach(r, function(v, name) { if (!done[name]) { done[name] = true; m = self.getModule(name); if (m) { var expound = m.expound; if (expound) { r[expound] = self.getModule(expound); reqs = self.getRequires(r[expound]); Y.mix(r, YArray.hash(reqs)); } reqs = self.getRequires(m); Y.mix(r, YArray.hash(reqs)); // sups = m.supersedes; // if (sups) { // YArray.each(sups, function(sup) { // if (sup in self.loaded) { // delete r[name]; // } // // if (sup in self.conditions) { // r[sup] = true; // //} // }); // } // remove the definition for a rollup with // submodules -- getRequires() includes the // submodules. Removing the parent makes // it possible to prevent submodule duplication // if the parent is requested after a submodule // has been loaded. // if (m.submodules) { // delete r[name]; // } } } }); // Y.log('After explode: ' + YObject.keys(r)); }, getModule: function(mname) { //TODO: Remove name check - it's a quick hack to fix pattern WIP if (!mname) { return null; } var p, found, pname, m = this.moduleInfo[mname], patterns = this.patterns; // check the patterns library to see if we should automatically add // the module with defaults if (!m) { // Y.log('testing patterns ' + YObject.keys(patterns)); for (pname in patterns) { if (patterns.hasOwnProperty(pname)) { // Y.log('testing pattern ' + i); p = patterns[pname]; // use the metadata supplied for the pattern // as the module definition. if (mname.indexOf(pname) > -1) { found = p; break; } } } if (found) { if (p.action) { // Y.log('executing pattern action: ' + pname); p.action.call(this, mname, pname); } else { Y.log('Undefined module: ' + mname + ', matched a pattern: ' + pname, 'info', 'loader'); // ext true or false? m = this.addModule(Y.merge(found), mname); m.temp = true; } } } return m; }, // impl in rollup submodule _rollup: function() { }, /** * Remove superceded modules and loaded modules. Called by * calculate() after we have the mega list of all dependencies * @method _reduce * @return {object} the reduced dependency hash. * @private */ _reduce: function(r) { r = r || this.required; var i, j, s, m, type = this.loadType; for (i in r) { if (r.hasOwnProperty(i)) { m = this.getModule(i); // remove if already loaded if (((this.loaded[i] || ON_PAGE[i]) && !this.forceMap[i] && !this.ignoreRegistered) || (type && m && m.type != type)) { delete r[i]; } // remove anything this module supersedes s = m && m.supersedes; if (s) { for (j = 0; j < s.length; j++) { if (s[j] in r) { delete r[s[j]]; } } } } } // Y.log('required now: ' + YObject.keys(r)); return r; }, _finish: function(msg, success) { Y.log('loader finishing: ' + msg + ', ' + Y.id + ', ' + this.data, 'info', 'loader'); _queue.running = false; var onEnd = this.onEnd; if (onEnd) { onEnd.call(this.context, { msg: msg, data: this.data, success: success }); } this._continue(); }, _onSuccess: function() { // Y.log('loader _onSuccess, skipping: ' + // Y.Object.keys(this.skipped), "info", "loader"); var skipped = Y.merge(this.skipped), fn; oeach(skipped, function(k) { delete this.inserted[k]; }, this); this.skipped = {}; // Y.mix(this.loaded, this.inserted); oeach(this.inserted, function(v, k) { Y.mix(this.loaded, this.getProvides(k)); }, this); fn = this.onSuccess; if (fn) { fn.call(this.context, { msg: 'success', data: this.data, success: true, skipped: skipped }); } this._finish('success', true); }, _onFailure: function(o) { Y.log('load error: ' + o.msg + ', ' + Y.id, 'error', 'loader'); var f = this.onFailure, msg = 'failure: ' + o.msg; if (f) { f.call(this.context, { msg: msg, data: this.data, success: false }); } this._finish(msg, false); }, _onTimeout: function() { Y.log('loader timeout: ' + Y.id, 'error', 'loader'); var f = this.onTimeout; if (f) { f.call(this.context, { msg: 'timeout', data: this.data, success: false }); } this._finish('timeout', false); }, /** * Sorts the dependency tree. The last step of calculate() * @method _sort * @private */ _sort: function() { // create an indexed list var s = YObject.keys(this.required), // loaded = this.loaded, done = {}, p = 0, l, a, b, j, k, moved, doneKey; // keep going until we make a pass without moving anything for (;;) { l = s.length; moved = false; // start the loop after items that are already sorted for (j = p; j < l; j++) { // check the next module on the list to see if its // dependencies have been met a = s[j]; // check everything below current item and move if we // find a requirement for the current item for (k = j + 1; k < l; k++) { doneKey = a + s[k]; if (!done[doneKey] && this._requires(a, s[k])) { // extract the dependency so we can move it up b = s.splice(k, 1); // insert the dependency above the item that // requires it s.splice(j, 0, b[0]); // only swap two dependencies once to short circut // circular dependencies done[doneKey] = true; // keep working moved = true; break; } } // jump out of loop if we moved something if (moved) { break; // this item is sorted, move our pointer and keep going } else { p++; } } // when we make it here and moved is false, we are // finished sorting if (!moved) { break; } } this.sorted = s; }, // _get: function(js, css) { // } // _combo: function(js, css) { // } // _insert: function(source, o, type) { // if (source) { // this._config(source); // } // var js = [], // css = [], // mod, // sorted = this.sorted, // i = 0, // l = sorted.length, // combine = this.combine; // for (; i < l; i++) { // mod = this.getModule(sorted[i]); // if (mod.type = CSS && type != JS) { // css.push(mod); // } else if (type != CSS) { // js.push(mod); // } // } // if (this.combine) { // this._combo(js, css); // } else { // this._get(js, css); // } // }, partial: function(partial, o, type) { this.sorted = partial; this.insert(o, type, true); }, _insert: function(source, o, type, skipcalc) { // Y.log('private _insert() ' + (type || '') + ', ' + Y.id, "info", "loader"); // restore the state at the time of the request if (source) { this._config(source); } // build the dependency list // don't include type so we can process CSS and script in // one pass when the type is not specified. if (!skipcalc) { this.calculate(o); } this.loadType = type; if (!type) { var self = this; // Y.log("trying to load css first"); this._internalCallback = function() { var f = self.onCSS, n, p, sib; // IE hack for style overrides that are not being applied if (this.insertBefore && Y.UA.ie) { n = Y.config.doc.getElementById(this.insertBefore); p = n.parentNode; sib = n.nextSibling; p.removeChild(n); if (sib) { p.insertBefore(n, sib); } else { p.appendChild(n); } } if (f) { f.call(self.context, Y); } self._internalCallback = null; self._insert(null, null, JS); }; this._insert(null, null, CSS); return; } // set a flag to indicate the load has started this._loading = true; // flag to indicate we are done with the combo service // and any additional files will need to be loaded // individually this._combineComplete = {}; // start the load this.loadNext(); }, // Once a loader operation is completely finished, process // any additional queued items. _continue: function() { if (!(_queue.running) && _queue.size() > 0) { _queue.running = true; _queue.next()(); } }, /** * inserts the requested modules and their dependencies. * <code>type</code> can be "js" or "css". Both script and * css are inserted if type is not provided. * @method insert * @param {object} o optional options object. * @param {string} type the type of dependency to insert. */ insert: function(o, type, skipsort) { // Y.log('public insert() ' + (type || '') + ', ' + // Y.Object.keys(this.required), "info", "loader"); var self = this, copy = Y.merge(this); delete copy.require; delete copy.dirty; _queue.add(function() { self._insert(copy, o, type, skipsort); }); this._continue(); }, /** * Executed every time a module is loaded, and if we are in a load * cycle, we attempt to load the next script. Public so that it * is possible to call this if using a method other than * Y.register to determine when scripts are fully loaded * @method loadNext * @param {string} mname optional the name of the module that has * been loaded (which is usually why it is time to load the next * one). */ loadNext: function(mname) { // It is possible that this function is executed due to something // else one the page loading a YUI module. Only react when we // are actively loading something if (!this._loading) { return; } var s, len, i, m, url, fn, msg, attr, group, groupName, j, frag, comboSource, comboSources, mods, combining, urls, comboBase, // provided, self = this, type = this.loadType, handleSuccess = function(o) { self.loadNext(o.data); }, handleCombo = function(o) { self._combineComplete[type] = true; var i, len = combining.length; for (i = 0; i < len; i++) { self.inserted[combining[i]] = true; } handleSuccess(o); }; if (this.combine && (!this._combineComplete[type])) { combining = []; this._combining = combining; s = this.sorted; len = s.length; // the default combo base comboBase = this.comboBase; url = comboBase; urls = []; comboSources = {}; for (i = 0; i < len; i++) { comboSource = comboBase; m = this.getModule(s[i]); groupName = m && m.group; if (groupName) { group = this.groups[groupName]; if (!group.combine) { m.combine = false; continue; } m.combine = true; if (group.comboBase) { comboSource = group.comboBase; } if (group.root) { m.root = group.root; } } comboSources[comboSource] = comboSources[comboSource] || []; comboSources[comboSource].push(m); } for (j in comboSources) { if (comboSources.hasOwnProperty(j)) { url = j; mods = comboSources[j]; len = mods.length; for (i = 0; i < len; i++) { // m = this.getModule(s[i]); m = mods[i]; // Do not try to combine non-yui JS unless combo def // is found if (m && (m.type === type) && (m.combine || !m.ext)) { frag = (m.root || this.root) + m.path; if ((url !== j) && (i < (len - 1)) && ((frag.length + url.length) > this.maxURLLength)) { urls.push(this._filter(url)); url = j; } url += frag; if (i < (len - 1)) { url += '&'; } combining.push(m.name); } } if (combining.length && (url != j)) { urls.push(this._filter(url)); } } } if (combining.length) { Y.log('Attempting to use combo: ' + combining, 'info', 'loader'); // if (m.type === CSS) { if (type === CSS) { fn = Y.Get.css; attr = this.cssAttributes; } else { fn = Y.Get.script; attr = this.jsAttributes; } fn(urls, { data: this._loading, onSuccess: handleCombo, onFailure: this._onFailure, onTimeout: this._onTimeout, insertBefore: this.insertBefore, charset: this.charset, attributes: attr, timeout: this.timeout, autopurge: false, context: this }); return; } else { this._combineComplete[type] = true; } } if (mname) { // if the module that was just loaded isn't what we were expecting, // continue to wait if (mname !== this._loading) { return; } // Y.log("loadNext executing, just loaded " + mname + ", " + // Y.id, "info", "loader"); // The global handler that is called when each module is loaded // will pass that module name to this function. Storing this // data to avoid loading the same module multiple times // centralize this in the callback this.inserted[mname] = true; // this.loaded[mname] = true; // provided = this.getProvides(mname); // Y.mix(this.loaded, provided); // Y.mix(this.inserted, provided); if (this.onProgress) { this.onProgress.call(this.context, { name: mname, data: this.data }); } } s = this.sorted; len = s.length; for (i = 0; i < len; i = i + 1) { // this.inserted keeps track of what the loader has loaded. // move on if this item is done. if (s[i] in this.inserted) { continue; } // Because rollups will cause multiple load notifications // from Y, loadNext may be called multiple times for // the same module when loading a rollup. We can safely // skip the subsequent requests if (s[i] === this._loading) { Y.log('still loading ' + s[i] + ', waiting', 'info', 'loader'); return; } // log("inserting " + s[i]); m = this.getModule(s[i]); if (!m) { msg = 'Undefined module ' + s[i] + ' skipped'; Y.log(msg, 'warn', 'loader'); // this.inserted[s[i]] = true; this.skipped[s[i]] = true; continue; } group = (m.group && this.groups[m.group]) || NOT_FOUND; // The load type is stored to offer the possibility to load // the css separately from the script. if (!type || type === m.type) { this._loading = s[i]; Y.log('attempting to load ' + s[i] + ', ' + this.base, 'info', 'loader'); if (m.type === CSS) { fn = Y.Get.css; attr = this.cssAttributes; } else { fn = Y.Get.script; attr = this.jsAttributes; } url = (m.fullpath) ? this._filter(m.fullpath, s[i]) : this._url(m.path, s[i], group.base || m.base); fn(url, { data: s[i], onSuccess: handleSuccess, insertBefore: this.insertBefore, charset: this.charset, attributes: attr, onFailure: this._onFailure, onTimeout: this._onTimeout, timeout: this.timeout, autopurge: false, context: self }); return; } } // we are finished this._loading = null; fn = this._internalCallback; // internal callback for loading css first if (fn) { // Y.log('loader internal'); this._internalCallback = null; fn.call(this); } else { // Y.log('loader complete'); this._onSuccess(); } }, /** * Apply filter defined for this instance to a url/path * method _filter * @param {string} u the string to filter. * @param {string} name the name of the module, if we are processing * a single module as opposed to a combined url. * @return {string} the filtered string. * @private */ _filter: function(u, name) { var f = this.filter, hasFilter = name && (name in this.filters), modFilter = hasFilter && this.filters[name]; if (u) { if (hasFilter) { f = (L.isString(modFilter)) ? this.FILTER_DEFS[modFilter.toUpperCase()] || null : modFilter; } if (f) { u = u.replace(new RegExp(f.searchExp, 'g'), f.replaceStr); } } return u; }, /** * Generates the full url for a module * method _url * @param {string} path the path fragment. * @return {string} the full url. * @private */ _url: function(path, name, base) { return this._filter((base || this.base || '') + path, name); } }; }, '@VERSION@' ,{requires:['get']}); YUI.add('loader-rollup', function(Y) { /** * Optional automatic rollup logic for reducing http connections * when not using a combo service. * @module loader * @submodule rollup */ /** * Look for rollup packages to determine if all of the modules a * rollup supersedes are required. If so, include the rollup to * help reduce the total number of connections required. Called * by calculate(). This is an optional feature, and requires the * appropriate submodule to function. * @method _rollup * @for Loader * @private */ Y.Loader.prototype._rollup = function() { var i, j, m, s, r = this.required, roll, info = this.moduleInfo, rolled, c, smod; // find and cache rollup modules if (this.dirty || !this.rollups) { this.rollups = {}; for (i in info) { if (info.hasOwnProperty(i)) { m = this.getModule(i); // if (m && m.rollup && m.supersedes) { if (m && m.rollup) { this.rollups[i] = m; } } } this.forceMap = (this.force) ? Y.Array.hash(this.force) : {}; } // make as many passes as needed to pick up rollup rollups for (;;) { rolled = false; // go through the rollup candidates for (i in this.rollups) { if (this.rollups.hasOwnProperty(i)) { // there can be only one, unless forced if (!r[i] && ((!this.loaded[i]) || this.forceMap[i])) { m = this.getModule(i); s = m.supersedes || []; roll = false; // @TODO remove continue if (!m.rollup) { continue; } c = 0; // check the threshold for (j = 0; j < s.length; j++) { smod = info[s[j]]; // if the superseded module is loaded, we can't // load the rollup unless it has been forced. if (this.loaded[s[j]] && !this.forceMap[s[j]]) { roll = false; break; // increment the counter if this module is required. // if we are beyond the rollup threshold, we will // use the rollup module } else if (r[s[j]] && m.type == smod.type) { c++; // Y.log("adding to thresh: " + c + ", " + s[j]); roll = (c >= m.rollup); if (roll) { // Y.log("over thresh " + c + ", " + s[j]); break; } } } if (roll) { // Y.log("adding rollup: " + i); // add the rollup r[i] = true; rolled = true; // expand the rollup's dependencies this.getRequires(m); } } } } // if we made it here w/o rolling up something, we are done if (!rolled) { break; } } }; }, '@VERSION@' ,{requires:['loader-base']}); YUI.add('loader-yui3', function(Y) { /* This file is auto-generated by src/loader/meta_join.py */ /** * YUI 3 module metadata * @module loader * @submodule yui3 */ YUI.Env[Y.version].modules = YUI.Env[Y.version].modules || { "anim": { "submodules": { "anim-base": { "requires": [ "base-base", "node-style" ] }, "anim-color": { "requires": [ "anim-base" ] }, "anim-curve": { "requires": [ "anim-xy" ] }, "anim-easing": { "requires": [ "anim-base" ] }, "anim-node-plugin": { "requires": [ "node-pluginhost", "anim-base" ] }, "anim-scroll": { "requires": [ "anim-base" ] }, "anim-xy": { "requires": [ "anim-base", "node-screen" ] } } }, "arraysort": {}, "async-queue": { "requires": [ "event-custom" ] }, "attribute": { "submodules": { "attribute-base": { "requires": [ "event-custom" ] }, "attribute-complex": { "requires": [ "attribute-base" ] } } }, "autocomplete": { "submodules": { "autocomplete-base": { "optional": [ "jsonp", "yql" ], "plugins": { "autocomplete-filters": { "path": "autocomplete/autocomplete-filters-min.js", "requires": [ "array-extras", "unicode-wordbreak" ] }, "autocomplete-filters-accentfold": { "path": "autocomplete/autocomplete-filters-accentfold-min.js", "requires": [ "array-extras", "unicode-accentfold", "unicode-wordbreak" ] }, "autocomplete-highlighters": { "path": "autocomplete/autocomplete-highlighters-min.js", "requires": [ "array-extras", "highlight-base" ] }, "autocomplete-highlighters-accentfold": { "path": "autocomplete/autocomplete-highlighters-accentfold-min.js", "requires": [ "array-extras", "highlight-accentfold" ] } }, "requires": [ "array-extras", "base-build", "event-valuechange", "node-base" ] }, "autocomplete-list": { "lang": [ "en" ], "plugins": { "autocomplete-list-keys": { "condition": { "test": function (Y) { // Only add keyboard support to autocomplete-list if this doesn't appear to // be an iOS or Android-based mobile device. // // There's currently no feasible way to actually detect whether a device has // a hardware keyboard, so this sniff will have to do. It can easily be // overridden by manually loading the autocomplete-list-keys module. // // Worth noting: even though iOS supports bluetooth keyboards, Mobile Safari // doesn't fire the keyboard events used by AutoCompleteList, so there's // no point loading the -keys module even when a bluetooth keyboard may be // available. return !(Y.UA.ios || Y.UA.android); }, "trigger": "autocomplete-list" }, "path": "autocomplete/autocomplete-list-keys-min.js", "requires": [ "autocomplete-list", "base-build" ] }, "autocomplete-plugin": { "path": "autocomplete/autocomplete-plugin-min.js", "requires": [ "autocomplete-list", "node-pluginhost" ] } }, "requires": [ "autocomplete-base", "widget", "widget-position", "widget-position-align", "widget-stack" ], "skinnable": true } } }, "base": { "submodules": { "base-base": { "after": [ "attribute-complex" ], "requires": [ "attribute-base" ] }, "base-build": { "requires": [ "base-base" ] }, "base-pluginhost": { "requires": [ "base-base", "pluginhost" ] } } }, "cache": { "submodules": { "cache-base": { "requires": [ "base" ] }, "cache-offline": { "requires": [ "cache-base", "json" ] } } }, "classnamemanager": { "requires": [ "yui-base" ] }, "collection": { "submodules": { "array-extras": {}, "array-invoke": {}, "arraylist": {}, "arraylist-add": { "requires": [ "arraylist" ] }, "arraylist-filter": { "requires": [ "arraylist" ] } } }, "compat": { "requires": [ "event-base", "dom", "dump", "substitute" ] }, "console": { "lang": [ "en", "es" ], "plugins": { "console-filters": { "requires": [ "plugin", "console" ], "skinnable": true } }, "requires": [ "yui-log", "widget", "substitute" ], "skinnable": true }, "cookie": { "requires": [ "yui-base" ] }, "cssbase": { "after": [ "cssreset", "cssfonts", "cssgrids", "cssreset-context", "cssfonts-context", "cssgrids-context" ], "path": "cssbase/base-min.css", "type": "css" }, "cssbase-context": { "after": [ "cssreset", "cssfonts", "cssgrids", "cssreset-context", "cssfonts-context", "cssgrids-context" ], "path": "cssbase/base-context-min.css", "type": "css" }, "cssfonts": { "path": "cssfonts/fonts-min.css", "type": "css" }, "cssfonts-context": { "path": "cssfonts/fonts-context-min.css", "type": "css" }, "cssgrids": { "optional": [ "cssreset", "cssfonts" ], "path": "cssgrids/grids-min.css", "type": "css" }, "cssgrids-context-deprecated": { "optional": [ "cssreset-context" ], "path": "cssgrids-deprecated/grids-context-min.css", "requires": [ "cssfonts-context" ], "type": "css" }, "cssgrids-deprecated": { "optional": [ "cssreset" ], "path": "cssgrids-deprecated/grids-min.css", "requires": [ "cssfonts" ], "type": "css" }, "cssreset": { "path": "cssreset/reset-min.css", "type": "css" }, "cssreset-context": { "path": "cssreset/reset-context-min.css", "type": "css" }, "dataschema": { "submodules": { "dataschema-array": { "requires": [ "dataschema-base" ] }, "dataschema-base": { "requires": [ "base" ] }, "dataschema-json": { "requires": [ "dataschema-base", "json" ] }, "dataschema-text": { "requires": [ "dataschema-base" ] }, "dataschema-xml": { "requires": [ "dataschema-base" ] } } }, "datasource": { "submodules": { "datasource-arrayschema": { "requires": [ "datasource-local", "plugin", "dataschema-array" ] }, "datasource-cache": { "requires": [ "datasource-local", "cache-base" ] }, "datasource-function": { "requires": [ "datasource-local" ] }, "datasource-get": { "requires": [ "datasource-local", "get" ] }, "datasource-io": { "requires": [ "datasource-local", "io-base" ] }, "datasource-jsonschema": { "requires": [ "datasource-local", "plugin", "dataschema-json" ] }, "datasource-local": { "requires": [ "base" ] }, "datasource-polling": { "requires": [ "datasource-local" ] }, "datasource-textschema": { "requires": [ "datasource-local", "plugin", "dataschema-text" ] }, "datasource-xmlschema": { "requires": [ "datasource-local", "plugin", "dataschema-xml" ] } } }, "datatable": { "submodules": { "datatable-base": { "requires": [ "recordset-base", "widget", "intl", "substitute", "event-mouseenter" ], "skinnable": true }, "datatable-scroll": { "requires": [ "datatable-base", "plugin", "stylesheet" ] }, "datatable-sort": { "requires": [ "datatable-base", "plugin", "recordset-sort" ] } } }, "datatype": { "submodules": { "datatype-date": { "lang": [ "ar", "ar-JO", "ca", "ca-ES", "da", "da-DK", "de", "de-AT", "de-DE", "el", "el-GR", "en", "en-AU", "en-CA", "en-GB", "en-IE", "en-IN", "en-JO", "en-MY", "en-NZ", "en-PH", "en-SG", "en-US", "es", "es-AR", "es-BO", "es-CL", "es-CO", "es-EC", "es-ES", "es-MX", "es-PE", "es-PY", "es-US", "es-UY", "es-VE", "fi", "fi-FI", "fr", "fr-BE", "fr-CA", "fr-FR", "hi", "hi-IN", "id", "id-ID", "it", "it-IT", "ja", "ja-JP", "ko", "ko-KR", "ms", "ms-MY", "nb", "nb-NO", "nl", "nl-BE", "nl-NL", "pl", "pl-PL", "pt", "pt-BR", "ro", "ro-RO", "ru", "ru-RU", "sv", "sv-SE", "th", "th-TH", "tr", "tr-TR", "vi", "vi-VN", "zh-Hans", "zh-Hans-CN", "zh-Hant", "zh-Hant-HK", "zh-Hant-TW" ], "requires": [ "yui-base" ], "supersedes": [ "datatype-date-format" ] }, "datatype-number": { "requires": [ "yui-base" ] }, "datatype-xml": { "requires": [ "yui-base" ] } } }, "datatype-date-format": { "path": "datatype/datatype-date-format-min.js" }, "dd": { "plugins": { "dd-drop-plugin": { "requires": [ "dd-drop" ] }, "dd-gestures": { "condition": { "test": function(Y) { return (Y.config.win && ('ontouchstart' in Y.config.win && !Y.UA.chrome)); }, "trigger": "dd-drag" }, "requires": [ "dd-drag", "event-move" ] }, "dd-plugin": { "optional": [ "dd-constrain", "dd-proxy" ], "requires": [ "dd-drag" ] } }, "submodules": { "dd-constrain": { "requires": [ "dd-drag" ] }, "dd-ddm": { "requires": [ "dd-ddm-base", "event-resize" ] }, "dd-ddm-base": { "requires": [ "node", "base", "yui-throttle", "classnamemanager" ] }, "dd-ddm-drop": { "requires": [ "dd-ddm" ] }, "dd-delegate": { "requires": [ "dd-drag", "dd-drop-plugin", "event-mouseenter" ] }, "dd-drag": { "requires": [ "dd-ddm-base" ] }, "dd-drop": { "requires": [ "dd-ddm-drop" ] }, "dd-proxy": { "requires": [ "dd-drag" ] }, "dd-scroll": { "requires": [ "dd-drag" ] } } }, "dial": { "requires": [ "widget", "dd-drag", "substitute", "event-mouseenter", "transition" ], "skinnable": true }, "dom": { "plugins": { "dom-deprecated": { "requires": [ "dom-base" ] }, "dom-style-ie": { "condition": { "trigger": "dom-style", "ua": "ie" }, "requires": [ "dom-style" ] }, "selector-css3": { "requires": [ "selector-css2" ] } }, "requires": [ "oop" ], "submodules": { "dom-base": { "requires": [ "oop" ] }, "dom-screen": { "requires": [ "dom-base", "dom-style" ] }, "dom-style": { "requires": [ "dom-base" ] }, "selector": { "requires": [ "dom-base" ] }, "selector-css2": { "requires": [ "selector-native" ] }, "selector-native": { "requires": [ "dom-base" ] } } }, "dump": { "requires": [ "yui-base" ] }, "editor": { "submodules": { "createlink-base": { "requires": [ "editor-base" ] }, "editor-base": { "requires": [ "base", "frame", "node", "exec-command", "selection", "editor-para" ] }, "editor-bidi": { "requires": [ "editor-base" ] }, "editor-lists": { "requires": [ "editor-base" ] }, "editor-para": { "requires": [ "node" ] }, "exec-command": { "requires": [ "frame" ] }, "frame": { "requires": [ "base", "node", "selector-css3", "substitute" ] }, "selection": { "requires": [ "node" ] } } }, "escape": {}, "event": { "after": "node-base", "plugins": { "event-base-ie": { "after": [ "event-base" ], "condition": { "trigger": "node-base", "ua": "ie" }, "requires": [ "node-base" ] }, "event-touch": { "requires": [ "node-base" ] } }, "submodules": { "event-base": { "after": "node-base", "requires": [ "event-custom-base" ] }, "event-delegate": { "requires": [ "node-base" ] }, "event-focus": { "requires": [ "event-synthetic" ] }, "event-key": { "requires": [ "event-synthetic" ] }, "event-mouseenter": { "requires": [ "event-synthetic" ] }, "event-mousewheel": { "requires": [ "event-synthetic" ] }, "event-resize": { "requires": [ "event-synthetic" ] }, "event-synthetic": { "requires": [ "node-base", "event-custom-complex" ] } } }, "event-custom": { "submodules": { "event-custom-base": { "requires": [ "oop" ] }, "event-custom-complex": { "requires": [ "event-custom-base" ] } } }, "event-gestures": { "submodules": { "event-flick": { "requires": [ "node-base", "event-touch", "event-synthetic" ] }, "event-move": { "requires": [ "node-base", "event-touch", "event-synthetic" ] } } }, "event-simulate": { "requires": [ "event-base" ] }, "event-valuechange": { "requires": [ "event-focus", "event-synthetic" ] }, "highlight": { "submodules": { "highlight-accentfold": { "requires": [ "highlight-base", "unicode-accentfold" ] }, "highlight-base": { "requires": [ "array-extras", "escape", "unicode-wordbreak" ] } } }, "history": { "plugins": { "history-hash-ie": { "condition": { "test": function (Y) { var docMode = Y.config.doc.documentMode; return Y.UA.ie && (!('onhashchange' in Y.config.win) || !docMode || docMode < 8); }, "trigger": "history-hash" }, "requires": [ "history-hash", "node-base" ] } }, "submodules": { "history-base": { "after": [ "history-deprecated" ], "requires": [ "event-custom-complex" ] }, "history-hash": { "after": [ "history-html5" ], "requires": [ "event-synthetic", "history-base", "yui-later" ] }, "history-html5": { "optional": [ "json" ], "requires": [ "event-base", "history-base", "node-base" ] } } }, "history-deprecated": { "requires": [ "node" ] }, "imageloader": { "requires": [ "base-base", "node-style", "node-screen" ] }, "intl": { "requires": [ "intl-base", "event-custom" ] }, "io": { "submodules": { "io-base": { "optional": [ "querystring-stringify-simple" ], "requires": [ "event-custom-base" ] }, "io-form": { "requires": [ "io-base", "node-base", "node-style" ] }, "io-queue": { "requires": [ "io-base", "queue-promote" ] }, "io-upload-iframe": { "requires": [ "io-base", "node-base" ] }, "io-xdr": { "requires": [ "io-base", "datatype-xml" ] } } }, "json": { "submodules": { "json-parse": { "requires": [ "yui-base" ] }, "json-stringify": { "requires": [ "yui-base" ] } } }, "jsonp": { "plugins": { "jsonp-url": { "requires": [ "jsonp" ] } }, "requires": [ "get", "oop" ] }, "node": { "plugins": { "align-plugin": { "requires": [ "node-screen", "node-pluginhost" ] }, "node-deprecated": { "requires": [ "node-base" ] }, "node-event-simulate": { "requires": [ "node-base", "event-simulate" ] }, "node-load": { "requires": [ "node-base", "io-base" ] }, "shim-plugin": { "requires": [ "node-style", "node-pluginhost" ] }, "transition": { "requires": [ "transition-native", "node-style" ] }, "transition-native": { "requires": [ "node-base" ] } }, "submodules": { "node-base": { "requires": [ "dom-base", "selector-css2", "event-base" ] }, "node-event-delegate": { "requires": [ "node-base", "event-delegate" ] }, "node-pluginhost": { "requires": [ "node-base", "pluginhost" ] }, "node-screen": { "requires": [ "dom-screen", "node-base" ] }, "node-style": { "requires": [ "dom-style", "node-base" ] } } }, "node-flick": { "requires": [ "classnamemanager", "transition", "event-flick", "plugin" ], "skinnable": true }, "node-focusmanager": { "requires": [ "attribute", "node", "plugin", "node-event-simulate", "event-key", "event-focus" ] }, "node-menunav": { "requires": [ "node", "classnamemanager", "plugin", "node-focusmanager" ], "skinnable": true }, "node-tokeninput": { "requires": [ "array-extras", "classnamemanager", "event-focus", "event-valuechange", "node-event-delegate", "node-pluginhost", "node-style", "plugin" ], "skinnable": true }, "oop": { "requires": [ "yui-base" ] }, "overlay": { "requires": [ "widget", "widget-stdmod", "widget-position", "widget-position-align", "widget-stack", "widget-position-constrain" ], "skinnable": true }, "plugin": { "requires": [ "base-base" ] }, "pluginhost": { "submodules": { "pluginhost-base": { "requires": [ "yui-base" ] }, "pluginhost-config": { "requires": [ "pluginhost-base" ] } } }, "profiler": { "requires": [ "yui-base" ] }, "querystring": { "submodules": { "querystring-parse": { "requires": [ "yui-base", "array-extras" ] }, "querystring-stringify": { "requires": [ "yui-base" ] } } }, "querystring-parse-simple": { "path": "querystring/querystring-parse-simple-min.js", "requires": [ "yui-base" ] }, "querystring-stringify-simple": { "path": "querystring/querystring-stringify-simple-min.js", "requires": [ "yui-base" ] }, "queue-promote": { "requires": [ "yui-base" ] }, "queue-run": { "path": "async-queue/async-queue-min.js", "requires": [ "event-custom" ] }, "recordset": { "submodules": { "recordset-base": { "requires": [ "base", "arraylist" ] }, "recordset-filter": { "requires": [ "recordset-base", "array-extras" ] }, "recordset-indexer": { "requires": [ "recordset-base", "plugin" ] }, "recordset-sort": { "requires": [ "arraysort", "recordset-base" ] } } }, "resize": { "submodules": { "resize-base": { "requires": [ "widget", "substitute", "event", "oop", "dd-drag", "dd-delegate", "dd-drop" ], "skinnable": true }, "resize-constrain": { "requires": [ "plugin", "resize-base" ] }, "resize-proxy": { "requires": [ "plugin", "resize-base" ] } } }, "scrollview": { "plugins": { "scrollview-base": { "path": "scrollview/scrollview-base-min.js", "requires": [ "widget", "event-gestures", "transition" ], "skinnable": true }, "scrollview-base-ie": { "condition": { "trigger": "scrollview-base", "ua": "ie" }, "requires": [ "scrollview-base" ] }, "scrollview-paginator": { "path": "scrollview/scrollview-paginator-min.js", "requires": [ "plugin" ], "skinnable": true }, "scrollview-scrollbars": { "path": "scrollview/scrollview-scrollbars-min.js", "requires": [ "plugin" ], "skinnable": true } }, "requires": [ "scrollview-base", "scrollview-scrollbars" ] }, "slider": { "submodules": { "clickable-rail": { "requires": [ "slider-base" ] }, "range-slider": { "requires": [ "slider-base", "slider-value-range", "clickable-rail" ] }, "slider-base": { "requires": [ "widget", "dd-constrain", "substitute" ], "skinnable": true }, "slider-value-range": { "requires": [ "slider-base" ] } } }, "sortable": { "plugins": { "sortable-scroll": { "requires": [ "dd-scroll" ] } }, "requires": [ "dd-delegate", "dd-drop-plugin", "dd-proxy" ] }, "stylesheet": { "requires": [ "yui-base" ] }, "substitute": { "optional": [ "dump" ] }, "swf": { "requires": [ "event-custom", "node", "swfdetect" ] }, "swfdetect": {}, "tabview": { "plugins": { "tabview-base": { "requires": [ "node-event-delegate", "classnamemanager", "skin-sam-tabview" ] }, "tabview-plugin": { "requires": [ "tabview-base" ] } }, "requires": [ "widget", "widget-parent", "widget-child", "tabview-base", "node-pluginhost", "node-focusmanager" ], "skinnable": true }, "test": { "requires": [ "substitute", "node", "json", "event-simulate" ], "skinnable": true }, "transition": { "submodules": { "transition-native": { "requires": [ "node-base" ] }, "transition-timer": { "requires": [ "transition-native", "node-style" ] } } }, "unicode": { "submodules": { "unicode-accentfold": { "requires": [ "array-extras", "unicode-data-accentfold" ] }, "unicode-data-accentfold": {}, "unicode-data-wordbreak": {}, "unicode-wordbreak": { "requires": [ "array-extras", "unicode-data-wordbreak" ] } } }, "uploader": { "requires": [ "event-custom", "node", "base", "swf" ] }, "widget": { "plugins": { "widget-base-ie": { "condition": { "trigger": "widget-base", "ua": "ie" }, "requires": [ "widget-base" ] }, "widget-child": { "requires": [ "base-build", "widget" ] }, "widget-parent": { "requires": [ "base-build", "arraylist", "widget" ] }, "widget-position": { "requires": [ "base-build", "node-screen", "widget" ] }, "widget-position-align": { "requires": [ "widget-position" ] }, "widget-position-constrain": { "requires": [ "widget-position" ] }, "widget-stack": { "requires": [ "base-build", "widget" ], "skinnable": true }, "widget-stdmod": { "requires": [ "base-build", "widget" ] } }, "skinnable": true, "submodules": { "widget-base": { "requires": [ "attribute", "event-focus", "base-base", "base-pluginhost", "node-base", "node-style", "classnamemanager" ] }, "widget-htmlparser": { "requires": [ "widget-base" ] }, "widget-skin": { "requires": [ "widget-base" ] }, "widget-uievents": { "requires": [ "widget-base", "node-event-delegate" ] } } }, "widget-anim": { "requires": [ "plugin", "anim-base", "widget" ] }, "widget-locale": { "path": "widget/widget-locale-min.js", "requires": [ "widget-base" ] }, "yql": { "requires": [ "jsonp", "jsonp-url" ] }, "yui": { "submodules": { "features": { "requires": [ "yui-base" ] }, "get": { "requires": [ "yui-base" ] }, "intl-base": { "requires": [ "yui-base" ] }, "rls": { "requires": [ "get", "features" ] }, "yui-base": {}, "yui-later": { "requires": [ "yui-base" ] }, "yui-log": { "requires": [ "yui-base" ] }, "yui-throttle": { "requires": [ "yui-base" ] } } } }; YUI.Env[Y.version].md5 = '987a1c6c1d18f2a6e22ac810354b8ec9'; }, '@VERSION@' ,{requires:['loader-base']}); YUI.add('loader', function(Y){}, '@VERSION@' ,{use:['loader-base', 'loader-rollup', 'loader-yui3' ]});
/** * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/> * Build: `lodash modularize modern exports="node" -o ./modern/` * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/> * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE> * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors * Available under MIT license <http://lodash.com/license> */ /** Used to determine if values are of the language type Object */ var objectTypes = { 'boolean': false, 'function': true, 'object': true, 'number': false, 'string': false, 'undefined': false }; module.exports = objectTypes;
define(function() { var theme = { backgroundColor: '#F2F2E6', // 默认色板 color: [ '#44B7D3','#E42B6D','#F4E24E','#FE9616','#8AED35', '#ff69b4','#ba55d3','#cd5c5c','#ffa500','#40e0d0', '#E95569','#ff6347','#7b68ee','#00fa9a','#ffd700', '#6699FF','#ff6666','#3cb371','#b8860b','#30e0e0' ], // 图表标题 title: { backgroundColor: '#F2F2E6', itemGap: 10, // 主副标题纵向间隔,单位px,默认为10, textStyle: { color: '#8A826D' // 主标题文字颜色 }, subtextStyle: { color: '#E877A3' // 副标题文字颜色 } }, // 值域 dataRange: { x:'right', y:'center', itemWidth: 5, itemHeight:25, color:['#E42B6D','#F9AD96'], text:['高','低'], // 文本,默认为数值文本 textStyle: { color: '#8A826D' // 值域文字颜色 } }, toolbox: { color : ['#E95569','#E95569','#E95569','#E95569'], effectiveColor : '#ff4500', itemGap: 8 }, // 提示框 tooltip: { backgroundColor: 'rgba(138,130,109,0.7)', // 提示背景颜色,默认为透明度为0.7的黑色 axisPointer : { // 坐标轴指示器,坐标轴触发有效 type : 'line', // 默认为直线,可选为:'line' | 'shadow' lineStyle : { // 直线指示器样式设置 color: '#6B6455', type: 'dashed' }, crossStyle: { //十字准星指示器 color: '#A6A299' }, shadowStyle : { // 阴影指示器样式设置 color: 'rgba(200,200,200,0.3)' } } }, // 区域缩放控制器 dataZoom: { dataBackgroundColor: 'rgba(130,197,209,0.6)', // 数据背景颜色 fillerColor: 'rgba(233,84,105,0.1)', // 填充颜色 handleColor: 'rgba(107,99,84,0.8)' // 手柄颜色 }, // 网格 grid: { borderWidth:0 }, // 类目轴 categoryAxis: { axisLine: { // 坐标轴线 lineStyle: { // 属性lineStyle控制线条样式 color: '#6B6455' } }, splitLine: { // 分隔线 show: false } }, // 数值型坐标轴默认参数 valueAxis: { axisLine: { // 坐标轴线 show: false }, splitArea : { show: false }, splitLine: { // 分隔线 lineStyle: { // 属性lineStyle(详见lineStyle)控制线条样式 color: ['#FFF'], type: 'dashed' } } }, polar : { axisLine: { // 坐标轴线 lineStyle: { // 属性lineStyle控制线条样式 color: '#ddd' } }, splitArea : { show : true, areaStyle : { color: ['rgba(250,250,250,0.2)','rgba(200,200,200,0.2)'] } }, splitLine : { lineStyle : { color : '#ddd' } } }, timeline : { lineStyle : { color : '#6B6455' }, controlStyle : { normal : { color : '#6B6455'}, emphasis : { color : '#6B6455'} }, symbol : 'emptyCircle', symbolSize : 3 }, // 柱形图默认参数 bar: { itemStyle: { normal: { barBorderRadius: 0 }, emphasis: { barBorderRadius: 0 } } }, // 折线图默认参数 line: { smooth : true, symbol: 'emptyCircle', // 拐点图形类型 symbolSize: 3 // 拐点图形大小 }, // K线图默认参数 k: { itemStyle: { normal: { color: '#E42B6D', // 阳线填充颜色 color0: '#44B7D3', // 阴线填充颜色 lineStyle: { width: 1, color: '#E42B6D', // 阳线边框颜色 color0: '#44B7D3' // 阴线边框颜色 } } } }, // 散点图默认参数 scatter: { itemStyle: { normal: { borderWidth:1, borderColor:'rgba(200,200,200,0.5)' }, emphasis: { borderWidth:0 } }, symbol: 'circle', // 图形类型 symbolSize: 4 // 图形大小,半宽(半径)参数,当图形为方向或菱形则总宽度为symbolSize * 2 }, // 雷达图默认参数 radar : { symbol: 'emptyCircle', // 图形类型 symbolSize:3 //symbol: null, // 拐点图形类型 //symbolRotate : null, // 图形旋转控制 }, map: { itemStyle: { normal: { areaStyle: { color: '#ddd' }, label: { textStyle: { color: '#E42B6D' } } }, emphasis: { // 也是选中样式 areaStyle: { color: '#fe994e' }, label: { textStyle: { color: 'rgb(100,0,0)' } } } } }, force : { itemStyle: { normal: { nodeStyle : { borderColor : 'rgba(0,0,0,0)' }, linkStyle : { color : '#6B6455' } } } }, chord : { itemStyle : { normal : { chordStyle : { lineStyle : { width : 0, color : 'rgba(128, 128, 128, 0.5)' } } }, emphasis : { chordStyle : { lineStyle : { width : 1, color : 'rgba(128, 128, 128, 0.5)' } } } } }, gauge : { // 仪表盘 center:['50%','80%'], radius:'100%', startAngle: 180, endAngle : 0, axisLine: { // 坐标轴线 show: true, // 默认显示,属性show控制显示与否 lineStyle: { // 属性lineStyle控制线条样式 color: [[0.2, '#44B7D3'],[0.8, '#6B6455'],[1, '#E42B6D']], width: '40%' } }, axisTick: { // 坐标轴小标记 splitNumber: 2, // 每份split细分多少段 length: 5, // 属性length控制线长 lineStyle: { // 属性lineStyle控制线条样式 color: '#fff' } }, axisLabel: { // 坐标轴文本标签,详见axis.axisLabel textStyle: { // 其余属性默认使用全局文本样式,详见TEXTSTYLE color: '#fff', fontWeight:'bolder' } }, splitLine: { // 分隔线 length: '5%', // 属性length控制线长 lineStyle: { // 属性lineStyle(详见lineStyle)控制线条样式 color: '#fff' } }, pointer : { width : '40%', length: '80%', color: '#fff' }, title : { offsetCenter: [0, -20], // x, y,单位px textStyle: { // 其余属性默认使用全局文本样式,详见TEXTSTYLE color: 'auto', fontSize: 20 } }, detail : { offsetCenter: [0, 0], // x, y,单位px textStyle: { // 其余属性默认使用全局文本样式,详见TEXTSTYLE color: 'auto', fontSize: 40 } } }, textStyle: { fontFamily: '微软雅黑, Arial, Verdana, sans-serif' } }; return theme; });
define([ "./core", "./var/strundefined", "./var/concat", "./var/push", "./var/deletedIds", "./core/access", "./manipulation/var/rcheckableType", "./manipulation/support", "./core/init", "./data/accepts", "./traversing", "./selector", "./event" ], function( jQuery, strundefined, concat, push, deletedIds, access, rcheckableType, support ) { function createSafeFragment( document ) { var list = nodeNames.split( "|" ), safeFrag = document.createDocumentFragment(); if ( safeFrag.createElement ) { while ( list.length ) { safeFrag.createElement( list.pop() ); } } return safeFrag; } var nodeNames = "abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|" + "header|hgroup|mark|meter|nav|output|progress|section|summary|time|video", rinlinejQuery = / jQuery\d+="(?:null|\d+)"/g, rnoshimcache = new RegExp("<(?:" + nodeNames + ")[\\s/>]", "i"), rleadingWhitespace = /^\s+/, rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi, rtagName = /<([\w:]+)/, rtbody = /<tbody/i, rhtml = /<|&#?\w+;/, rnoInnerhtml = /<(?:script|style|link)/i, // checked="checked" or checked rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i, rscriptType = /^$|\/(?:java|ecma)script/i, rscriptTypeMasked = /^true\/(.*)/, rcleanScript = /^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g, // We have to close these tags to support XHTML (#13200) wrapMap = { option: [ 1, "<select multiple='multiple'>", "</select>" ], legend: [ 1, "<fieldset>", "</fieldset>" ], area: [ 1, "<map>", "</map>" ], param: [ 1, "<object>", "</object>" ], thead: [ 1, "<table>", "</table>" ], tr: [ 2, "<table><tbody>", "</tbody></table>" ], col: [ 2, "<table><tbody></tbody><colgroup>", "</colgroup></table>" ], td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ], // IE6-8 can't serialize link, script, style, or any html5 (NoScope) tags, // unless wrapped in a div with non-breaking characters in front of it. _default: support.htmlSerialize ? [ 0, "", "" ] : [ 1, "X<div>", "</div>" ] }, safeFragment = createSafeFragment( document ), fragmentDiv = safeFragment.appendChild( document.createElement("div") ); wrapMap.optgroup = wrapMap.option; wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; wrapMap.th = wrapMap.td; function getAll( context, tag ) { var elems, elem, i = 0, found = typeof context.getElementsByTagName !== strundefined ? context.getElementsByTagName( tag || "*" ) : typeof context.querySelectorAll !== strundefined ? context.querySelectorAll( tag || "*" ) : undefined; if ( !found ) { for ( found = [], elems = context.childNodes || context; (elem = elems[i]) != null; i++ ) { if ( !tag || jQuery.nodeName( elem, tag ) ) { found.push( elem ); } else { jQuery.merge( found, getAll( elem, tag ) ); } } } return tag === undefined || tag && jQuery.nodeName( context, tag ) ? jQuery.merge( [ context ], found ) : found; } // Used in buildFragment, fixes the defaultChecked property function fixDefaultChecked( elem ) { if ( rcheckableType.test( elem.type ) ) { elem.defaultChecked = elem.checked; } } // Support: IE<8 // Manipulating tables requires a tbody function manipulationTarget( elem, content ) { return jQuery.nodeName( elem, "table" ) && jQuery.nodeName( content.nodeType !== 11 ? content : content.firstChild, "tr" ) ? elem.getElementsByTagName("tbody")[0] || elem.appendChild( elem.ownerDocument.createElement("tbody") ) : elem; } // Replace/restore the type attribute of script elements for safe DOM manipulation function disableScript( elem ) { elem.type = (jQuery.find.attr( elem, "type" ) !== null) + "/" + elem.type; return elem; } function restoreScript( elem ) { var match = rscriptTypeMasked.exec( elem.type ); if ( match ) { elem.type = match[1]; } else { elem.removeAttribute("type"); } return elem; } // Mark scripts as having already been evaluated function setGlobalEval( elems, refElements ) { var elem, i = 0; for ( ; (elem = elems[i]) != null; i++ ) { jQuery._data( elem, "globalEval", !refElements || jQuery._data( refElements[i], "globalEval" ) ); } } function cloneCopyEvent( src, dest ) { if ( dest.nodeType !== 1 || !jQuery.hasData( src ) ) { return; } var type, i, l, oldData = jQuery._data( src ), curData = jQuery._data( dest, oldData ), events = oldData.events; if ( events ) { delete curData.handle; curData.events = {}; for ( type in events ) { for ( i = 0, l = events[ type ].length; i < l; i++ ) { jQuery.event.add( dest, type, events[ type ][ i ] ); } } } // make the cloned public data object a copy from the original if ( curData.data ) { curData.data = jQuery.extend( {}, curData.data ); } } function fixCloneNodeIssues( src, dest ) { var nodeName, e, data; // We do not need to do anything for non-Elements if ( dest.nodeType !== 1 ) { return; } nodeName = dest.nodeName.toLowerCase(); // IE6-8 copies events bound via attachEvent when using cloneNode. if ( !support.noCloneEvent && dest[ jQuery.expando ] ) { data = jQuery._data( dest ); for ( e in data.events ) { jQuery.removeEvent( dest, e, data.handle ); } // Event data gets referenced instead of copied if the expando gets copied too dest.removeAttribute( jQuery.expando ); } // IE blanks contents when cloning scripts, and tries to evaluate newly-set text if ( nodeName === "script" && dest.text !== src.text ) { disableScript( dest ).text = src.text; restoreScript( dest ); // IE6-10 improperly clones children of object elements using classid. // IE10 throws NoModificationAllowedError if parent is null, #12132. } else if ( nodeName === "object" ) { if ( dest.parentNode ) { dest.outerHTML = src.outerHTML; } // This path appears unavoidable for IE9. When cloning an object // element in IE9, the outerHTML strategy above is not sufficient. // If the src has innerHTML and the destination does not, // copy the src.innerHTML into the dest.innerHTML. #10324 if ( support.html5Clone && ( src.innerHTML && !jQuery.trim(dest.innerHTML) ) ) { dest.innerHTML = src.innerHTML; } } else if ( nodeName === "input" && rcheckableType.test( src.type ) ) { // IE6-8 fails to persist the checked state of a cloned checkbox // or radio button. Worse, IE6-7 fail to give the cloned element // a checked appearance if the defaultChecked value isn't also set dest.defaultChecked = dest.checked = src.checked; // IE6-7 get confused and end up setting the value of a cloned // checkbox/radio button to an empty string instead of "on" if ( dest.value !== src.value ) { dest.value = src.value; } // IE6-8 fails to return the selected option to the default selected // state when cloning options } else if ( nodeName === "option" ) { dest.defaultSelected = dest.selected = src.defaultSelected; // IE6-8 fails to set the defaultValue to the correct value when // cloning other types of input fields } else if ( nodeName === "input" || nodeName === "textarea" ) { dest.defaultValue = src.defaultValue; } } jQuery.extend({ clone: function( elem, dataAndEvents, deepDataAndEvents ) { var destElements, node, clone, i, srcElements, inPage = jQuery.contains( elem.ownerDocument, elem ); if ( support.html5Clone || jQuery.isXMLDoc(elem) || !rnoshimcache.test( "<" + elem.nodeName + ">" ) ) { clone = elem.cloneNode( true ); // IE<=8 does not properly clone detached, unknown element nodes } else { fragmentDiv.innerHTML = elem.outerHTML; fragmentDiv.removeChild( clone = fragmentDiv.firstChild ); } if ( (!support.noCloneEvent || !support.noCloneChecked) && (elem.nodeType === 1 || elem.nodeType === 11) && !jQuery.isXMLDoc(elem) ) { // We eschew Sizzle here for performance reasons: http://jsperf.com/getall-vs-sizzle/2 destElements = getAll( clone ); srcElements = getAll( elem ); // Fix all IE cloning issues for ( i = 0; (node = srcElements[i]) != null; ++i ) { // Ensure that the destination node is not null; Fixes #9587 if ( destElements[i] ) { fixCloneNodeIssues( node, destElements[i] ); } } } // Copy the events from the original to the clone if ( dataAndEvents ) { if ( deepDataAndEvents ) { srcElements = srcElements || getAll( elem ); destElements = destElements || getAll( clone ); for ( i = 0; (node = srcElements[i]) != null; i++ ) { cloneCopyEvent( node, destElements[i] ); } } else { cloneCopyEvent( elem, clone ); } } // Preserve script evaluation history destElements = getAll( clone, "script" ); if ( destElements.length > 0 ) { setGlobalEval( destElements, !inPage && getAll( elem, "script" ) ); } destElements = srcElements = node = null; // Return the cloned set return clone; }, buildFragment: function( elems, context, scripts, selection ) { var j, elem, contains, tmp, tag, tbody, wrap, l = elems.length, // Ensure a safe fragment safe = createSafeFragment( context ), nodes = [], i = 0; for ( ; i < l; i++ ) { elem = elems[ i ]; if ( elem || elem === 0 ) { // Add nodes directly if ( jQuery.type( elem ) === "object" ) { jQuery.merge( nodes, elem.nodeType ? [ elem ] : elem ); // Convert non-html into a text node } else if ( !rhtml.test( elem ) ) { nodes.push( context.createTextNode( elem ) ); // Convert html into DOM nodes } else { tmp = tmp || safe.appendChild( context.createElement("div") ); // Deserialize a standard representation tag = (rtagName.exec( elem ) || [ "", "" ])[ 1 ].toLowerCase(); wrap = wrapMap[ tag ] || wrapMap._default; tmp.innerHTML = wrap[1] + elem.replace( rxhtmlTag, "<$1></$2>" ) + wrap[2]; // Descend through wrappers to the right content j = wrap[0]; while ( j-- ) { tmp = tmp.lastChild; } // Manually add leading whitespace removed by IE if ( !support.leadingWhitespace && rleadingWhitespace.test( elem ) ) { nodes.push( context.createTextNode( rleadingWhitespace.exec( elem )[0] ) ); } // Remove IE's autoinserted <tbody> from table fragments if ( !support.tbody ) { // String was a <table>, *may* have spurious <tbody> elem = tag === "table" && !rtbody.test( elem ) ? tmp.firstChild : // String was a bare <thead> or <tfoot> wrap[1] === "<table>" && !rtbody.test( elem ) ? tmp : 0; j = elem && elem.childNodes.length; while ( j-- ) { if ( jQuery.nodeName( (tbody = elem.childNodes[j]), "tbody" ) && !tbody.childNodes.length ) { elem.removeChild( tbody ); } } } jQuery.merge( nodes, tmp.childNodes ); // Fix #12392 for WebKit and IE > 9 tmp.textContent = ""; // Fix #12392 for oldIE while ( tmp.firstChild ) { tmp.removeChild( tmp.firstChild ); } // Remember the top-level container for proper cleanup tmp = safe.lastChild; } } } // Fix #11356: Clear elements from fragment if ( tmp ) { safe.removeChild( tmp ); } // Reset defaultChecked for any radios and checkboxes // about to be appended to the DOM in IE 6/7 (#8060) if ( !support.appendChecked ) { jQuery.grep( getAll( nodes, "input" ), fixDefaultChecked ); } i = 0; while ( (elem = nodes[ i++ ]) ) { // #4087 - If origin and destination elements are the same, and this is // that element, do not do anything if ( selection && jQuery.inArray( elem, selection ) !== -1 ) { continue; } contains = jQuery.contains( elem.ownerDocument, elem ); // Append to fragment tmp = getAll( safe.appendChild( elem ), "script" ); // Preserve script evaluation history if ( contains ) { setGlobalEval( tmp ); } // Capture executables if ( scripts ) { j = 0; while ( (elem = tmp[ j++ ]) ) { if ( rscriptType.test( elem.type || "" ) ) { scripts.push( elem ); } } } } tmp = null; return safe; }, cleanData: function( elems, /* internal */ acceptData ) { var elem, type, id, data, i = 0, internalKey = jQuery.expando, cache = jQuery.cache, deleteExpando = support.deleteExpando, special = jQuery.event.special; for ( ; (elem = elems[i]) != null; i++ ) { if ( acceptData || jQuery.acceptData( elem ) ) { id = elem[ internalKey ]; data = id && cache[ id ]; if ( data ) { if ( data.events ) { for ( type in data.events ) { if ( special[ type ] ) { jQuery.event.remove( elem, type ); // This is a shortcut to avoid jQuery.event.remove's overhead } else { jQuery.removeEvent( elem, type, data.handle ); } } } // Remove cache only if it was not already removed by jQuery.event.remove if ( cache[ id ] ) { delete cache[ id ]; // IE does not allow us to delete expando properties from nodes, // nor does it have a removeAttribute function on Document nodes; // we must handle all of these cases if ( deleteExpando ) { delete elem[ internalKey ]; } else if ( typeof elem.removeAttribute !== strundefined ) { elem.removeAttribute( internalKey ); } else { elem[ internalKey ] = null; } deletedIds.push( id ); } } } } } }); jQuery.fn.extend({ text: function( value ) { return access( this, function( value ) { return value === undefined ? jQuery.text( this ) : this.empty().append( ( this[0] && this[0].ownerDocument || document ).createTextNode( value ) ); }, null, value, arguments.length ); }, append: function() { return this.domManip( arguments, function( elem ) { if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { var target = manipulationTarget( this, elem ); target.appendChild( elem ); } }); }, prepend: function() { return this.domManip( arguments, function( elem ) { if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { var target = manipulationTarget( this, elem ); target.insertBefore( elem, target.firstChild ); } }); }, before: function() { return this.domManip( arguments, function( elem ) { if ( this.parentNode ) { this.parentNode.insertBefore( elem, this ); } }); }, after: function() { return this.domManip( arguments, function( elem ) { if ( this.parentNode ) { this.parentNode.insertBefore( elem, this.nextSibling ); } }); }, remove: function( selector, keepData /* Internal Use Only */ ) { var elem, elems = selector ? jQuery.filter( selector, this ) : this, i = 0; for ( ; (elem = elems[i]) != null; i++ ) { if ( !keepData && elem.nodeType === 1 ) { jQuery.cleanData( getAll( elem ) ); } if ( elem.parentNode ) { if ( keepData && jQuery.contains( elem.ownerDocument, elem ) ) { setGlobalEval( getAll( elem, "script" ) ); } elem.parentNode.removeChild( elem ); } } return this; }, empty: function() { var elem, i = 0; for ( ; (elem = this[i]) != null; i++ ) { // Remove element nodes and prevent memory leaks if ( elem.nodeType === 1 ) { jQuery.cleanData( getAll( elem, false ) ); } // Remove any remaining nodes while ( elem.firstChild ) { elem.removeChild( elem.firstChild ); } // If this is a select, ensure that it displays empty (#12336) // Support: IE<9 if ( elem.options && jQuery.nodeName( elem, "select" ) ) { elem.options.length = 0; } } return this; }, clone: function( dataAndEvents, deepDataAndEvents ) { dataAndEvents = dataAndEvents == null ? false : dataAndEvents; deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents; return this.map(function() { return jQuery.clone( this, dataAndEvents, deepDataAndEvents ); }); }, html: function( value ) { return access( this, function( value ) { var elem = this[ 0 ] || {}, i = 0, l = this.length; if ( value === undefined ) { return elem.nodeType === 1 ? elem.innerHTML.replace( rinlinejQuery, "" ) : undefined; } // See if we can take a shortcut and just use innerHTML if ( typeof value === "string" && !rnoInnerhtml.test( value ) && ( support.htmlSerialize || !rnoshimcache.test( value ) ) && ( support.leadingWhitespace || !rleadingWhitespace.test( value ) ) && !wrapMap[ (rtagName.exec( value ) || [ "", "" ])[ 1 ].toLowerCase() ] ) { value = value.replace( rxhtmlTag, "<$1></$2>" ); try { for (; i < l; i++ ) { // Remove element nodes and prevent memory leaks elem = this[i] || {}; if ( elem.nodeType === 1 ) { jQuery.cleanData( getAll( elem, false ) ); elem.innerHTML = value; } } elem = 0; // If using innerHTML throws an exception, use the fallback method } catch(e) {} } if ( elem ) { this.empty().append( value ); } }, null, value, arguments.length ); }, replaceWith: function() { var arg = arguments[ 0 ]; // Make the changes, replacing each context element with the new content this.domManip( arguments, function( elem ) { arg = this.parentNode; jQuery.cleanData( getAll( this ) ); if ( arg ) { arg.replaceChild( elem, this ); } }); // Force removal if there was no new content (e.g., from empty arguments) return arg && (arg.length || arg.nodeType) ? this : this.remove(); }, detach: function( selector ) { return this.remove( selector, true ); }, domManip: function( args, callback ) { // Flatten any nested arrays args = concat.apply( [], args ); var first, node, hasScripts, scripts, doc, fragment, i = 0, l = this.length, set = this, iNoClone = l - 1, value = args[0], isFunction = jQuery.isFunction( value ); // We can't cloneNode fragments that contain checked, in WebKit if ( isFunction || ( l > 1 && typeof value === "string" && !support.checkClone && rchecked.test( value ) ) ) { return this.each(function( index ) { var self = set.eq( index ); if ( isFunction ) { args[0] = value.call( this, index, self.html() ); } self.domManip( args, callback ); }); } if ( l ) { fragment = jQuery.buildFragment( args, this[ 0 ].ownerDocument, false, this ); first = fragment.firstChild; if ( fragment.childNodes.length === 1 ) { fragment = first; } if ( first ) { scripts = jQuery.map( getAll( fragment, "script" ), disableScript ); hasScripts = scripts.length; // Use the original fragment for the last item instead of the first because it can end up // being emptied incorrectly in certain situations (#8070). for ( ; i < l; i++ ) { node = fragment; if ( i !== iNoClone ) { node = jQuery.clone( node, true, true ); // Keep references to cloned scripts for later restoration if ( hasScripts ) { jQuery.merge( scripts, getAll( node, "script" ) ); } } callback.call( this[i], node, i ); } if ( hasScripts ) { doc = scripts[ scripts.length - 1 ].ownerDocument; // Reenable scripts jQuery.map( scripts, restoreScript ); // Evaluate executable scripts on first document insertion for ( i = 0; i < hasScripts; i++ ) { node = scripts[ i ]; if ( rscriptType.test( node.type || "" ) && !jQuery._data( node, "globalEval" ) && jQuery.contains( doc, node ) ) { if ( node.src ) { // Optional AJAX dependency, but won't run scripts if not present if ( jQuery._evalUrl ) { jQuery._evalUrl( node.src ); } } else { jQuery.globalEval( ( node.text || node.textContent || node.innerHTML || "" ).replace( rcleanScript, "" ) ); } } } } // Fix #11809: Avoid leaking memory fragment = first = null; } } return this; } }); jQuery.each({ appendTo: "append", prependTo: "prepend", insertBefore: "before", insertAfter: "after", replaceAll: "replaceWith" }, function( name, original ) { jQuery.fn[ name ] = function( selector ) { var elems, i = 0, ret = [], insert = jQuery( selector ), last = insert.length - 1; for ( ; i <= last; i++ ) { elems = i === last ? this : this.clone(true); jQuery( insert[i] )[ original ]( elems ); // Modern browsers can apply jQuery collections as arrays, but oldIE needs a .get() push.apply( ret, elems.get() ); } return this.pushStack( ret ); }; }); return jQuery; });
/** * @license AngularJS v1.2.3 * (c) 2010-2014 Google, Inc. http://angularjs.org * License: MIT */ (function(window, angular, undefined) {'use strict'; var $sanitizeMinErr = angular.$$minErr('$sanitize'); /** * @ngdoc overview * @name ngSanitize * @description * * # ngSanitize * * The `ngSanitize` module provides functionality to sanitize HTML. * * {@installModule sanitize} * * <div doc-module-components="ngSanitize"></div> * * See {@link ngSanitize.$sanitize `$sanitize`} for usage. */ /* * HTML Parser By Misko Hevery (misko@hevery.com) * based on: HTML Parser By John Resig (ejohn.org) * Original code by Erik Arvidsson, Mozilla Public License * http://erik.eae.net/simplehtmlparser/simplehtmlparser.js * * // Use like so: * htmlParser(htmlString, { * start: function(tag, attrs, unary) {}, * end: function(tag) {}, * chars: function(text) {}, * comment: function(text) {} * }); * */ /** * @ngdoc service * @name ngSanitize.$sanitize * @function * * @description * The input is sanitized by parsing the html into tokens. All safe tokens (from a whitelist) are * then serialized back to properly escaped html string. This means that no unsafe input can make * it into the returned string, however, since our parser is more strict than a typical browser * parser, it's possible that some obscure input, which would be recognized as valid HTML by a * browser, won't make it through the sanitizer. * The whitelist is configured using the functions `aHrefSanitizationWhitelist` and * `imgSrcSanitizationWhitelist` of {@link ng.$compileProvider `$compileProvider`}. * * @param {string} html Html input. * @returns {string} Sanitized html. * * @example <doc:example module="ngSanitize"> <doc:source> <script> function Ctrl($scope, $sce) { $scope.snippet = '<p style="color:blue">an html\n' + '<em onmouseover="this.textContent=\'PWN3D!\'">click here</em>\n' + 'snippet</p>'; $scope.deliberatelyTrustDangerousSnippet = function() { return $sce.trustAsHtml($scope.snippet); }; } </script> <div ng-controller="Ctrl"> Snippet: <textarea ng-model="snippet" cols="60" rows="3"></textarea> <table> <tr> <td>Directive</td> <td>How</td> <td>Source</td> <td>Rendered</td> </tr> <tr id="bind-html-with-sanitize"> <td>ng-bind-html</td> <td>Automatically uses $sanitize</td> <td><pre>&lt;div ng-bind-html="snippet"&gt;<br/>&lt;/div&gt;</pre></td> <td><div ng-bind-html="snippet"></div></td> </tr> <tr id="bind-html-with-trust"> <td>ng-bind-html</td> <td>Bypass $sanitize by explicitly trusting the dangerous value</td> <td> <pre>&lt;div ng-bind-html="deliberatelyTrustDangerousSnippet()"&gt; &lt;/div&gt;</pre> </td> <td><div ng-bind-html="deliberatelyTrustDangerousSnippet()"></div></td> </tr> <tr id="bind-default"> <td>ng-bind</td> <td>Automatically escapes</td> <td><pre>&lt;div ng-bind="snippet"&gt;<br/>&lt;/div&gt;</pre></td> <td><div ng-bind="snippet"></div></td> </tr> </table> </div> </doc:source> <doc:scenario> it('should sanitize the html snippet by default', function() { expect(using('#bind-html-with-sanitize').element('div').html()). toBe('<p>an html\n<em>click here</em>\nsnippet</p>'); }); it('should inline raw snippet if bound to a trusted value', function() { expect(using('#bind-html-with-trust').element("div").html()). toBe("<p style=\"color:blue\">an html\n" + "<em onmouseover=\"this.textContent='PWN3D!'\">click here</em>\n" + "snippet</p>"); }); it('should escape snippet without any filter', function() { expect(using('#bind-default').element('div').html()). toBe("&lt;p style=\"color:blue\"&gt;an html\n" + "&lt;em onmouseover=\"this.textContent='PWN3D!'\"&gt;click here&lt;/em&gt;\n" + "snippet&lt;/p&gt;"); }); it('should update', function() { input('snippet').enter('new <b onclick="alert(1)">text</b>'); expect(using('#bind-html-with-sanitize').element('div').html()).toBe('new <b>text</b>'); expect(using('#bind-html-with-trust').element('div').html()).toBe( 'new <b onclick="alert(1)">text</b>'); expect(using('#bind-default').element('div').html()).toBe( "new &lt;b onclick=\"alert(1)\"&gt;text&lt;/b&gt;"); }); </doc:scenario> </doc:example> */ function $SanitizeProvider() { this.$get = ['$$sanitizeUri', function($$sanitizeUri) { return function(html) { var buf = []; htmlParser(html, htmlSanitizeWriter(buf, function(uri, isImage) { return !/^unsafe/.test($$sanitizeUri(uri, isImage)); })); return buf.join(''); }; }]; } function sanitizeText(chars) { var buf = []; var writer = htmlSanitizeWriter(buf, angular.noop); writer.chars(chars); return buf.join(''); } // Regular Expressions for parsing tags and attributes var START_TAG_REGEXP = /^<\s*([\w:-]+)((?:\s+[\w:-]+(?:\s*=\s*(?:(?:"[^"]*")|(?:'[^']*')|[^>\s]+))?)*)\s*(\/?)\s*>/, END_TAG_REGEXP = /^<\s*\/\s*([\w:-]+)[^>]*>/, ATTR_REGEXP = /([\w:-]+)(?:\s*=\s*(?:(?:"((?:[^"])*)")|(?:'((?:[^'])*)')|([^>\s]+)))?/g, BEGIN_TAG_REGEXP = /^</, BEGING_END_TAGE_REGEXP = /^<\s*\//, COMMENT_REGEXP = /<!--(.*?)-->/g, DOCTYPE_REGEXP = /<!DOCTYPE([^>]*?)>/i, CDATA_REGEXP = /<!\[CDATA\[(.*?)]]>/g, // Match everything outside of normal chars and " (quote character) NON_ALPHANUMERIC_REGEXP = /([^\#-~| |!])/g; // Good source of info about elements and attributes // http://dev.w3.org/html5/spec/Overview.html#semantics // http://simon.html5.org/html-elements // Safe Void Elements - HTML5 // http://dev.w3.org/html5/spec/Overview.html#void-elements var voidElements = makeMap("area,br,col,hr,img,wbr"); // Elements that you can, intentionally, leave open (and which close themselves) // http://dev.w3.org/html5/spec/Overview.html#optional-tags var optionalEndTagBlockElements = makeMap("colgroup,dd,dt,li,p,tbody,td,tfoot,th,thead,tr"), optionalEndTagInlineElements = makeMap("rp,rt"), optionalEndTagElements = angular.extend({}, optionalEndTagInlineElements, optionalEndTagBlockElements); // Safe Block Elements - HTML5 var blockElements = angular.extend({}, optionalEndTagBlockElements, makeMap("address,article," + "aside,blockquote,caption,center,del,dir,div,dl,figure,figcaption,footer,h1,h2,h3,h4,h5," + "h6,header,hgroup,hr,ins,map,menu,nav,ol,pre,script,section,table,ul")); // Inline Elements - HTML5 var inlineElements = angular.extend({}, optionalEndTagInlineElements, makeMap("a,abbr,acronym,b," + "bdi,bdo,big,br,cite,code,del,dfn,em,font,i,img,ins,kbd,label,map,mark,q,ruby,rp,rt,s," + "samp,small,span,strike,strong,sub,sup,time,tt,u,var")); // Special Elements (can contain anything) var specialElements = makeMap("script,style"); var validElements = angular.extend({}, voidElements, blockElements, inlineElements, optionalEndTagElements); //Attributes that have href and hence need to be sanitized var uriAttrs = makeMap("background,cite,href,longdesc,src,usemap"); var validAttrs = angular.extend({}, uriAttrs, makeMap( 'abbr,align,alt,axis,bgcolor,border,cellpadding,cellspacing,class,clear,'+ 'color,cols,colspan,compact,coords,dir,face,headers,height,hreflang,hspace,'+ 'ismap,lang,language,nohref,nowrap,rel,rev,rows,rowspan,rules,'+ 'scope,scrolling,shape,span,start,summary,target,title,type,'+ 'valign,value,vspace,width')); function makeMap(str) { var obj = {}, items = str.split(','), i; for (i = 0; i < items.length; i++) obj[items[i]] = true; return obj; } /** * @example * htmlParser(htmlString, { * start: function(tag, attrs, unary) {}, * end: function(tag) {}, * chars: function(text) {}, * comment: function(text) {} * }); * * @param {string} html string * @param {object} handler */ function htmlParser( html, handler ) { var index, chars, match, stack = [], last = html; stack.last = function() { return stack[ stack.length - 1 ]; }; while ( html ) { chars = true; // Make sure we're not in a script or style element if ( !stack.last() || !specialElements[ stack.last() ] ) { // Comment if ( html.indexOf("<!--") === 0 ) { // comments containing -- are not allowed unless they terminate the comment index = html.indexOf("--", 4); if ( index >= 0 && html.lastIndexOf("-->", index) === index) { if (handler.comment) handler.comment( html.substring( 4, index ) ); html = html.substring( index + 3 ); chars = false; } // DOCTYPE } else if ( DOCTYPE_REGEXP.test(html) ) { match = html.match( DOCTYPE_REGEXP ); if ( match ) { html = html.replace( match[0] , ''); chars = false; } // end tag } else if ( BEGING_END_TAGE_REGEXP.test(html) ) { match = html.match( END_TAG_REGEXP ); if ( match ) { html = html.substring( match[0].length ); match[0].replace( END_TAG_REGEXP, parseEndTag ); chars = false; } // start tag } else if ( BEGIN_TAG_REGEXP.test(html) ) { match = html.match( START_TAG_REGEXP ); if ( match ) { html = html.substring( match[0].length ); match[0].replace( START_TAG_REGEXP, parseStartTag ); chars = false; } } if ( chars ) { index = html.indexOf("<"); var text = index < 0 ? html : html.substring( 0, index ); html = index < 0 ? "" : html.substring( index ); if (handler.chars) handler.chars( decodeEntities(text) ); } } else { html = html.replace(new RegExp("(.*)<\\s*\\/\\s*" + stack.last() + "[^>]*>", 'i'), function(all, text){ text = text.replace(COMMENT_REGEXP, "$1").replace(CDATA_REGEXP, "$1"); if (handler.chars) handler.chars( decodeEntities(text) ); return ""; }); parseEndTag( "", stack.last() ); } if ( html == last ) { throw $sanitizeMinErr('badparse', "The sanitizer was unable to parse the following block " + "of html: {0}", html); } last = html; } // Clean up any remaining tags parseEndTag(); function parseStartTag( tag, tagName, rest, unary ) { tagName = angular.lowercase(tagName); if ( blockElements[ tagName ] ) { while ( stack.last() && inlineElements[ stack.last() ] ) { parseEndTag( "", stack.last() ); } } if ( optionalEndTagElements[ tagName ] && stack.last() == tagName ) { parseEndTag( "", tagName ); } unary = voidElements[ tagName ] || !!unary; if ( !unary ) stack.push( tagName ); var attrs = {}; rest.replace(ATTR_REGEXP, function(match, name, doubleQuotedValue, singleQuotedValue, unquotedValue) { var value = doubleQuotedValue || singleQuotedValue || unquotedValue || ''; attrs[name] = decodeEntities(value); }); if (handler.start) handler.start( tagName, attrs, unary ); } function parseEndTag( tag, tagName ) { var pos = 0, i; tagName = angular.lowercase(tagName); if ( tagName ) // Find the closest opened tag of the same type for ( pos = stack.length - 1; pos >= 0; pos-- ) if ( stack[ pos ] == tagName ) break; if ( pos >= 0 ) { // Close all the open elements, up the stack for ( i = stack.length - 1; i >= pos; i-- ) if (handler.end) handler.end( stack[ i ] ); // Remove the open elements from the stack stack.length = pos; } } } /** * decodes all entities into regular string * @param value * @returns {string} A string with decoded entities. */ var hiddenPre=document.createElement("pre"); function decodeEntities(value) { if (!value) { return ''; } // Note: IE8 does not preserve spaces at the start/end of innerHTML var spaceRe = /^(\s*)([\s\S]*?)(\s*)$/; var parts = spaceRe.exec(value); parts[0] = ''; if (parts[2]) { hiddenPre.innerHTML=parts[2].replace(/</g,"&lt;"); parts[2] = hiddenPre.innerText || hiddenPre.textContent; } return parts.join(''); } /** * Escapes all potentially dangerous characters, so that the * resulting string can be safely inserted into attribute or * element text. * @param value * @returns escaped text */ function encodeEntities(value) { return value. replace(/&/g, '&amp;'). replace(NON_ALPHANUMERIC_REGEXP, function(value){ return '&#' + value.charCodeAt(0) + ';'; }). replace(/</g, '&lt;'). replace(/>/g, '&gt;'); } /** * create an HTML/XML writer which writes to buffer * @param {Array} buf use buf.jain('') to get out sanitized html string * @returns {object} in the form of { * start: function(tag, attrs, unary) {}, * end: function(tag) {}, * chars: function(text) {}, * comment: function(text) {} * } */ function htmlSanitizeWriter(buf, uriValidator){ var ignore = false; var out = angular.bind(buf, buf.push); return { start: function(tag, attrs, unary){ tag = angular.lowercase(tag); if (!ignore && specialElements[tag]) { ignore = tag; } if (!ignore && validElements[tag] === true) { out('<'); out(tag); angular.forEach(attrs, function(value, key){ var lkey=angular.lowercase(key); var isImage = (tag === 'img' && lkey === 'src') || (lkey === 'background'); if (validAttrs[lkey] === true && (uriAttrs[lkey] !== true || uriValidator(value, isImage))) { out(' '); out(key); out('="'); out(encodeEntities(value)); out('"'); } }); out(unary ? '/>' : '>'); } }, end: function(tag){ tag = angular.lowercase(tag); if (!ignore && validElements[tag] === true) { out('</'); out(tag); out('>'); } if (tag == ignore) { ignore = false; } }, chars: function(chars){ if (!ignore) { out(encodeEntities(chars)); } } }; } // define ngSanitize module and register $sanitize service angular.module('ngSanitize', []).provider('$sanitize', $SanitizeProvider); /* global sanitizeText: false */ /** * @ngdoc filter * @name ngSanitize.filter:linky * @function * * @description * Finds links in text input and turns them into html links. Supports http/https/ftp/mailto and * plain email address links. * * Requires the {@link ngSanitize `ngSanitize`} module to be installed. * * @param {string} text Input text. * @param {string} target Window (_blank|_self|_parent|_top) or named frame to open links in. * @returns {string} Html-linkified text. * * @usage <span ng-bind-html="linky_expression | linky"></span> * * @example <doc:example module="ngSanitize"> <doc:source> <script> function Ctrl($scope) { $scope.snippet = 'Pretty text with some links:\n'+ 'http://angularjs.org/,\n'+ 'mailto:us@somewhere.org,\n'+ 'another@somewhere.org,\n'+ 'and one more: ftp://127.0.0.1/.'; $scope.snippetWithTarget = 'http://angularjs.org/'; } </script> <div ng-controller="Ctrl"> Snippet: <textarea ng-model="snippet" cols="60" rows="3"></textarea> <table> <tr> <td>Filter</td> <td>Source</td> <td>Rendered</td> </tr> <tr id="linky-filter"> <td>linky filter</td> <td> <pre>&lt;div ng-bind-html="snippet | linky"&gt;<br>&lt;/div&gt;</pre> </td> <td> <div ng-bind-html="snippet | linky"></div> </td> </tr> <tr id="linky-target"> <td>linky target</td> <td> <pre>&lt;div ng-bind-html="snippetWithTarget | linky:'_blank'"&gt;<br>&lt;/div&gt;</pre> </td> <td> <div ng-bind-html="snippetWithTarget | linky:'_blank'"></div> </td> </tr> <tr id="escaped-html"> <td>no filter</td> <td><pre>&lt;div ng-bind="snippet"&gt;<br>&lt;/div&gt;</pre></td> <td><div ng-bind="snippet"></div></td> </tr> </table> </doc:source> <doc:scenario> it('should linkify the snippet with urls', function() { expect(using('#linky-filter').binding('snippet | linky')). toBe('Pretty text with some links:&#10;' + '<a href="http://angularjs.org/">http://angularjs.org/</a>,&#10;' + '<a href="mailto:us@somewhere.org">us@somewhere.org</a>,&#10;' + '<a href="mailto:another@somewhere.org">another@somewhere.org</a>,&#10;' + 'and one more: <a href="ftp://127.0.0.1/">ftp://127.0.0.1/</a>.'); }); it ('should not linkify snippet without the linky filter', function() { expect(using('#escaped-html').binding('snippet')). toBe("Pretty text with some links:\n" + "http://angularjs.org/,\n" + "mailto:us@somewhere.org,\n" + "another@somewhere.org,\n" + "and one more: ftp://127.0.0.1/."); }); it('should update', function() { input('snippet').enter('new http://link.'); expect(using('#linky-filter').binding('snippet | linky')). toBe('new <a href="http://link">http://link</a>.'); expect(using('#escaped-html').binding('snippet')).toBe('new http://link.'); }); it('should work with the target property', function() { expect(using('#linky-target').binding("snippetWithTarget | linky:'_blank'")). toBe('<a target="_blank" href="http://angularjs.org/">http://angularjs.org/</a>'); }); </doc:scenario> </doc:example> */ angular.module('ngSanitize').filter('linky', ['$sanitize', function($sanitize) { var LINKY_URL_REGEXP = /((ftp|https?):\/\/|(mailto:)?[A-Za-z0-9._%+-]+@)\S*[^\s.;,(){}<>]/, MAILTO_REGEXP = /^mailto:/; return function(text, target) { if (!text) return text; var match; var raw = text; var html = []; var url; var i; while ((match = raw.match(LINKY_URL_REGEXP))) { // We can not end in these as they are sometimes found at the end of the sentence url = match[0]; // if we did not match ftp/http/mailto then assume mailto if (match[2] == match[3]) url = 'mailto:' + url; i = match.index; addText(raw.substr(0, i)); addLink(url, match[0].replace(MAILTO_REGEXP, '')); raw = raw.substring(i + match[0].length); } addText(raw); return $sanitize(html.join('')); function addText(text) { if (!text) { return; } html.push(sanitizeText(text)); } function addLink(url, text) { html.push('<a '); if (angular.isDefined(target)) { html.push('target="'); html.push(target); html.push('" '); } html.push('href="'); html.push(url); html.push('">'); addText(text); html.push('</a>'); } }; }]); })(window, window.angular);
// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // a passthrough stream. // basically just the most minimal sort of Transform stream. // Every written chunk gets output as-is. module.exports = PassThrough; var Transform = require('./transform.js'); var inherits = require('inherits'); inherits(PassThrough, Transform); function PassThrough(options) { if (!(this instanceof PassThrough)) return new PassThrough(options); Transform.call(this, options); } PassThrough.prototype._transform = function(chunk, encoding, cb) { cb(null, chunk); };
"use strict"; module.exports = function(Chart) { Chart.PolarArea = function(context, config) { config.type = 'polarArea'; return new Chart(context, config); }; };
!function(t){"use strict";t.fn.select2.locales.az={formatMatches:function(t){return t+" nəticə mövcuddur, hərəkət etdirmək üçün yuxarı və aşağı düymələrindən istifadə edin."},formatNoMatches:function(){return"Nəticə tapılmadı"},formatInputTooShort:function(t,n){var r=n-t.length;return r+" simvol daxil edin"},formatInputTooLong:function(t,n){var r=t.length-n;return r+" simvol silin"},formatSelectionTooBig:function(t){return"Sadəcə "+t+" element seçə bilərsiniz"},formatLoadMore:function(){return"Daha çox nəticə yüklənir…"},formatSearching:function(){return"Axtarılır…"}},t.extend(t.fn.select2.defaults,t.fn.select2.locales.az)}(jQuery);
var common = require('./common'); var os = require('os'); var fs = require('fs'); // Returns false if 'dir' is not a writeable directory, 'dir' otherwise function writeableDir(dir) { if (!dir || !fs.existsSync(dir)) return false; if (!fs.statSync(dir).isDirectory()) return false; var testFile = dir+'/'+common.randomFileName(); try { fs.writeFileSync(testFile, ' '); common.unlinkSync(testFile); return dir; } catch (e) { return false; } } //@ //@ ### tempdir() //@ //@ Examples: //@ //@ ```javascript //@ var tmp = tempdir(); // "/tmp" for most *nix platforms //@ ``` //@ //@ Searches and returns string containing a writeable, platform-dependent temporary directory. //@ Follows Python's [tempfile algorithm](http://docs.python.org/library/tempfile.html#tempfile.tempdir). function _tempDir() { var state = common.state; if (state.tempDir) return state.tempDir; // from cache state.tempDir = writeableDir(os.tmpdir && os.tmpdir()) || // node 0.10+ writeableDir(os.tmpDir && os.tmpDir()) || // node 0.8+ writeableDir(process.env['TMPDIR']) || writeableDir(process.env['TEMP']) || writeableDir(process.env['TMP']) || writeableDir(process.env['Wimp$ScrapDir']) || // RiscOS writeableDir('C:\\TEMP') || // Windows writeableDir('C:\\TMP') || // Windows writeableDir('\\TEMP') || // Windows writeableDir('\\TMP') || // Windows writeableDir('/tmp') || writeableDir('/var/tmp') || writeableDir('/usr/tmp') || writeableDir('.'); // last resort return state.tempDir; } module.exports = _tempDir;
/* Translators (2009 onwards): * - Malafaya */ /** * @requires OpenLayers/Lang.js */ /** * Namespace: OpenLayers.Lang["io"] * Dictionary for Ido. 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["io"] = OpenLayers.Util.applyDefaults({ 'scale': "Skalo = 1 : ${scaleDenom}" });
var okcoinExchange = { name: 'OKCoin', products: { quarterlies: 'Quarterlies', biWeeklies: 'Bi-Weeklies', weeklies: 'Weeklies' } }, channelToProduct = { this_week: okcoinExchange.products.weeklies, next_week: okcoinExchange.products.biWeeklies, quarter: okcoinExchange.products.quarterlies } function startOKCoinWebSocket() { new OKCoin('wss://real.okex.com:10441/websocket') .addChannelHandler('ok_sub_futureusd_btc_index', handleIndex) .addChannelHandler('ok_sub_futureusd_btc_trade_this_week', handleTrade) .addChannelHandler('ok_sub_futureusd_btc_trade_next_week', handleTrade) .addChannelHandler('ok_sub_futureusd_btc_trade_quarter', handleTrade) .addChannelHandler('ok_sub_futureusd_btc_ticker_this_week', handleTicker) .addChannelHandler('ok_sub_futureusd_btc_ticker_next_week', handleTicker) .addChannelHandler('ok_sub_futureusd_btc_ticker_quarter', handleTicker) .start() } // Index data function handleIndex(message) { view.updateIndex(okcoinExchange.name, message.data.futureIndex) } // Last trade data function handleTrade(message) { message.data.forEach(function (trade) { view.update(okcoinExchange.name, getProduct(message.channel), 'price', parseFloat(trade[1])) }) } // Volume data function handleTicker(message) { var volume = parseFloat(message.data.vol) / 10 // in k$ view.updateVolume(okcoinExchange.name, getProduct(message.channel), volume) } function getProduct(channel) { var product forEach(channelToProduct, function (key, value) { if (channel.match(new RegExp(key))) { product = value } }) if (product !== undefined) { return product } else { console.log('Unknown channel: ' + channel) } }
// TODO: description var MOUSE_OVER_EVENTS = 'mousemove touchmove', SCROLL_SPEED = 200, BOUNDS_HEIGHT_KOEFF = 0.33; // TODO: properly polyfill // var requestAnimationFrame = window.requestAnimationFrame; function dragScrollDirective( draggingIndicator ){ return { restrict : 'A', scope: { dragScroll : '=' }, link: function( scope, element, attrs ){ 'use strict'; var SCROLL_STATE = { UP : 1, NONE : 0, DOWN: -1 }; var $window = $(window), state = SCROLL_STATE.NONE; scope.$watch( function(){ return draggingIndicator.value; } , function( newValue, oldValue ){ if (newValue === oldValue){ return; } if ( newValue ){ bind(); } else { unbind(); } } ); function bind(){ state = SCROLL_STATE.NONE; $window.on( MOUSE_OVER_EVENTS, handler ); } function unbind(){ state = SCROLL_STATE.NONE; $window.off( MOUSE_OVER_EVENTS, handler ); } function handler( event ){ var clientY, // TODO: rename instance = scope.dragScroll; // get clientY from the hammer event, depending on if its mouse or touch if ( event.type === 'mousemove' ){ clientY = event.clientY; } else { clientY = event.originalEvent.touches[ 0 ].clientY; } // if event.y near cutting edges of the current directive element, // scroll down/up var delta = 0, elementHeight = $window.outerHeight(), // TODO: save this value till window resizes // TODO: count scrolling pane height out of initial height elementHolderHeight = elementHeight * BOUNDS_HEIGHT_KOEFF; // MOUSE/TOUCH Y POSITION BASED BEHAVIOR: // // @ top -- start scroll // @ top && scrolling and already toppest -- stop scroll // // @ middle -- stop scroll // // @ bottom -- start scroll // @ bottom && scrolling and already bottom pos -- stop scroll var canScrollDown, canScrollUp, needScrollUp = clientY < elementHolderHeight, needScrollDown = elementHeight - clientY < elementHolderHeight, noneedToScroll = !needScrollUp && !needScrollDown; function updateStatuses(){ canScrollDown = instance.y > instance.maxScrollY; canScrollUp = instance.y < 0; } function scroll( direction ){ var delta; state = direction; if ( state === SCROLL_STATE.DOWN ){ delta = - SCROLL_SPEED; } else { delta = SCROLL_SPEED; } var prevAnimationFrameTime; ( function scrolling( time ){ var timeDelta, scrollDelta; // TODO: reconsider // if its first animation frame -- do not scroll // and call next anim frame if ( prevAnimationFrameTime === undefined ){ prevAnimationFrameTime = time; return requestAnimationFrame( scrolling ); } timeDelta = time - prevAnimationFrameTime; scrollDelta = timeDelta * delta / 1000; // do the scroll job, babe instance.scrollBy( 0, scrollDelta); // update statuses if we can scroll updateStatuses(); if ( state === SCROLL_STATE.DOWN && canScrollDown || state === SCROLL_STATE.UP && canScrollUp ){ requestAnimationFrame( scrolling ); prevAnimationFrameTime = time; } else { prevAnimationFrameTime = undefined; stopScroll(); } }()); } function stopScroll(){ state = SCROLL_STATE.NONE; } function scrollUp( ){ scroll( SCROLL_STATE.UP ); } function scrollDown( ){ scroll( SCROLL_STATE.DOWN ); } if (state === SCROLL_STATE.NONE){ updateStatuses(); if ( needScrollUp && canScrollUp ){ scrollUp(); } if ( needScrollDown && canScrollDown ){ scrollDown(); } } else { if ( noneedToScroll ){ stopScroll(); } } } } }; } angular .module( 'app' ) .directive( 'dragScroll', dragScrollDirective );
'use strict' const Observable = require('vigour-observable') const clearKeys = Observable.prototype.clearKeys module.exports = new Observable({ type: 'property', inject: require('../subscribe'), properties: { storeContextKey: true }, Child: 'Constructor', defaultSubscription: true, define: { clearKeys (target) { this._staticProps = void 0 clearKeys.apply(this, arguments) } } }, false)
var ruleTestBase = require('../rule-test-base'); var rule = require('../../../dist/rules/no-scenario-outlines-without-examples.js'); var runTest = ruleTestBase.createRuleTest(rule, 'Scenario Outline does not have any Examples'); describe('No scenario outlines without examples rule', function() { it('doesn\'t raise errors when there are no violations', function() { return runTest('no-scenario-outlines-without-examples/NoViolations.feature', {}, []); }); it('detects errors for scenario outlines that are missing the "Examples" keyword completely', function() { return runTest('no-scenario-outlines-without-examples/ViolationsNoExamples.feature', {}, [ {line: 3} ]); }); it('detects errors for scenario outlines that have empty "Examples"', function() { return runTest('no-scenario-outlines-without-examples/ViolationsEmptyExamples.feature', {}, [ {line: 3} ]); }); it('detects errors for scenario outlines that define variable names but don\'t have any values to iterate over', function() { return runTest('no-scenario-outlines-without-examples/ViolationsNoExamplesBody.feature', {}, [ {line: 3} ]); }); });
'use strict'; //Require the encryption modules const RSA = require('simple-encryption').RSA; const AES = require('simple-encryption').AES; //Error handler const errorHandler = require('../error/errorHandler.js'); const errorList = require('../error/errorList.js'); //Export main function module.exports = function(socket, serverPublicKey, callback) { //Generate a session key const sessionKey = AES.generateKey(); //Encrypt it with the serverPublicKey let encrypted; //Attempt to encrypt, otherwise error to user try { encrypted = RSA.encrypt(serverPublicKey, JSON.stringify({key: sessionKey})); } catch(e) { //Return to user return callback(new errorList.SecurityEncryptionFailure()); } //Listen only once socket.onmessage = function(event) { const message = JSON.parse(event.data); if(message.error) { //Error has occured return callback(errorHandler.createError(message.error)); } const payload = message.payload; const tag = message.tag; const iv = message.iv; //Try to decrypt let decrypted; try { decrypted = JSON.parse(AES.decrypt(sessionKey, iv, tag, payload)); } catch(e) { return callback(new errorList.SecurityDecryptionFailure()); } //Tag wasn't correct if(decrypted == null) { return callback(new errorList.HandshakeGeneric()); } //Callback to the caller with the challenge, sessionKey, and no error callback(null, decrypted, sessionKey); }; //Send a message try { socket.send(JSON.stringify({type: 'handshake', payload: encrypted})); } catch(e) { //Destroy socket socket.close(); return; } };
/** * controls what is shown on the canvas * @class Camera */ var Camera = Shade.extend({ /** * @member {string} Camera.prototype.name - the unique name necessary for proto's inheritance */ _protosName: 'camera', _zoom: 1, /** * @member {boolean} Camera.prototype.scrolling - use to turn off scrolling if other camera moves needed */ _scrolling: true, init: function() { this.$shade.init.apply(this, arguments); this.width(config.width); this.height(config.height); }, /** * @method Camera.prototype.zoom */ zoom: function(n) { if (n) { this._zoom = n; return this; } else { return this._zoom; } }, scroll: function(trigger, base, regions) { if (!this._scrolling) { return false; } this.vx(0); this.vy(0); if (trigger.vx() < 0 && trigger.x() < regions.left && base.x() < 0) { this.vx( (trigger.vx()) ); } if (trigger.vx() > 0 && trigger.x() + trigger.width() > regions.right && base.x() > this.width() - base.width()) { this.vx( (trigger.vx()) ); } if (trigger.vy() < 0 && trigger.y() < regions.top && base.y() < 0) { this.vy( (trigger.vy()) ); } if (trigger.vy() > 0 && trigger.y() + trigger.height() > regions.bottom && base.y() > this.height() - base.height()) { this.vy( (trigger.vy()) ); } }, contain : function(player) { var position = {}; if (player.x() < 0) { player.x(0); } else if (player.x() + player.width() > this.width()) { player.x(this.width() - player.width()); } if (player.y() < 0) { player.y(0); } else if (player.y() + player.height() > this.height()) { player.y(this.height() - player.height()); } } });
var ffi = require('ffi'), ref = require('ref'), RefArray = require('ref-array'), Struct = require('ref-struct'), Union = require('ref-union'), _library = require('./../../'); loadDependentSymbols(); _library._preload['php_load_extension'] = [function () { _library.php_load_extension = ['int', [ref.refType('char'), 'int', 'int']]; _library._functions['php_load_extension'] = _library.php_load_extension; }]; _library._preload['php_dl'] = ['zval', function () { _library.php_dl = ['void', [ref.refType('char'), 'int', ref.refType(_library.zval), 'int']]; _library._functions['php_dl'] = _library.php_dl; }]; _library._preload['zif_dl'] = ['zval', 'pointer', 'zval', function () { _library.zif_dl = ['void', ['int', ref.refType(_library.zval), ref.refType(ref.refType(_library.zval)), ref.refType(_library.zval), 'int']]; _library._functions['zif_dl'] = _library.zif_dl; }]; function loadDependentSymbols() { require('./../../Zend/zend.js'); require('./../../Zend/zend_API.js'); require('./../../Zend/zend_ast.js'); require('./../../Zend/zend_compile.js'); require('./../../Zend/zend_hash.js'); require('./../../Zend/zend_ini.js'); require('./../../Zend/zend_iterators.js'); require('./../../Zend/zend_modules.js'); require('./../../Zend/zend_object_handlers.js'); require('./../../Zend/zend_types.js'); }
/*jslint browser: true*/ /*globals window, define, Class*/ /** * @module yaga-layer */ define('yaga-layer', ['yaga', 'yaga-map'], function (Yaga, Map) { 'use strict'; var Layer; /** * @name Layer * @augments Yaga * @alias yaga-layer * @type {Class} */ Layer = new Class({ Extends: Yaga, initialize: function (opts) { Layer.init.call(this, opts); }, /** * Get attribution of a layer * returns {string} */ getAttribution: function () { throw new Error('not implemented'); }, /** * Set attribution of a layer * @param {string} value * @returns {Layer} */ setAttribution: function (value) { throw new Error('not implemented'); }, getCaption: function () { throw new Error('not implemented'); }, setCaption: function () { throw new Error('not implemented'); }, getContainer: function () { throw new Error('not implemented'); }, redraw: function () { throw new Error('not implemented'); }, getProjection: function () { throw new Error('not implemented'); }, setProjection: function () { throw new Error('not implemented'); }, getTitle: function () { throw new Error('not implemented'); }, setTitle: function () { throw new Error('not implemented'); }, getZIndex: function () { throw new Error('not implemented'); }, setZIndex: function () { throw new Error('not implemented'); }, getOpacity: function () { throw new Error('not implemented'); }, setOpacity: function () { throw new Error('not implemented'); }, show: function (map) { map = map || Map.activeMap; this.emit('show', map); if (!map) { throw new Error('No map to show layer'); } this.getLeafletElement().addTo(map.getLeafletElement()); }, hide: function (map) { map = map || Map.activeMap; this.emit('hide', map); if (!map) { throw new Error('No map to hide layer from'); } map.getLeafletElement().removeLayer(this.getLeafletElement()); }, getLeafletElement: function () { throw new Error('not implemented'); } }); Layer.init = function YagaLayer(opts) { var title, caption; opts = opts || {}; Yaga.init.call(this, opts); this.getTitle = function () { return title; }; this.setTitle = function (value) { this.emit('setTitle'); title = value; return this; }; this.getCaption = function () { return caption; }; this.setCaption = function (value) { this.emit('setCaption'); caption = value; return this; }; if (opts.caption) { this.setCaption(opts.caption); } if (opts.title) { this.setTitle(opts.title); } }; Layer.assume = function () { throw new Error('not implemented'); }; Layer.types = {}; Layer.registerType = function (name, layerType) { Layer.types[name] = layerType; }; Layer.create = function (opts) { opts = opts || {}; if (opts.type && Layer.types[opts.type]) { return Layer.types[opts.type].create(opts); } return new Layer(opts); }; return Layer; });