code
stringlengths
2
1.05M
"use strict"; function foo() { var _this = this; arr.map((function (x) { babelHelpers.newArrowCheck(this, _this); return x * x; }).bind(this)); var f = (function (x, y) { babelHelpers.newArrowCheck(this, _this); return x * y; }).bind(this); (function () { var _this2 = this; return (function () { babelHelpers.newArrowCheck(this, _this2); return this; }).bind(this); })(); }
/** * API Bound Models for AngularJS * @version v0.5.4 - 2013-11-08 * @link https://github.com/angular-platanus/restmod * @author Ignacio Baixas <iobaixas@gmai.com> * @license MIT License, http://www.opensource.org/licenses/MIT */ (function(angular, undefined) { 'use strict'; /** * @namespace constants * * @description Constants and utilities exposed by the library. */ /** * @namespace providers * * @description Angular providers provided by the library. */ /** * @namespace services * * @description Angular services provided by the library. */ angular.module('plRestmod', ['ng']); /** * @class Utils * @memberOf constants * * @description Various utilities used across * the library * * This utilities are available as the `Utils` constant when restmod is included. */ var Utils = { /** * @memberof constants.Utils * * @description Transforms a string to it's camelcase representation * * TODO: handle diacritics * * @param {string} _string Original string * @return {string} Camelcased string */ camelcase: function(_string) { if (typeof _string !== 'string') return _string; return _string.replace(/_[\w\d]/g, function (match, index, string) { return index === 0 ? match : string.charAt(index + 1).toUpperCase(); }); }, /** * @memberof constants.Utils * * @description Transforms a string to it's snakecase representation * * TODO: handle diacritics * * @param {string} _string Original string * @param {string} _sep Case separator, defaults to '_' * @return {string} Camelcased string */ snakecase: function(_string, _sep) { if (typeof _string !== 'string') return _string; return _string.replace(/[A-Z]/g, function (match, index) { return index === 0 ? match : (_sep || '_') + match.toLowerCase(); }); }, /** * @memberof constants.Utils * * @description Chains to filtering functions together * * @param {function} _first original function * @param {function} _fun function to call on the original function result * @return {mixed} value returned by the last function call */ chain: function(_first, _fun) { if(!_first) return _fun; return function(_value) { return _fun.call(this, _first.call(this, _value)); }; }, /** * @memberof constants.Utils * * @description Override a property value, making overriden function available as this.$super * * @param {function} _super Original value * @param {mixed} _fun New property value * @return {mixed} Value returned by new function */ override: function(_super, _fun) { if(!_super || typeof _fun !== 'function') return _fun; return function() { var oldSuper = this.$super; try { this.$super = _super; return _fun.apply(this, arguments); } finally { this.$super = oldSuper; } }; }, /** * @memberof constants.Utils * * @description Extend an object using `Utils.override` instead of just replacing the functions. * * @param {object} _target Object to be extended * @param {object} _other Source object */ extendOverriden: function(_target, _other) { for(var key in _other) { if(_other.hasOwnProperty(key)) { _target[key] = Utils.override(_target[key], _other[key]); } } } }; // make this available as a restmod constant angular.module('plRestmod').constant('Utils', Utils); /** * @class SyncMask * @memberOf constants * * @description The object property synchronization mask. */ var SyncMask = { NONE: 0x00, ALL: 0xFFFF, DECODE_CREATE: 0x0001, DECODE_UPDATE: 0x0002, DECODE_USER: 0x0004, DECODE_SAVE: 0x0003, ENCODE_CREATE: 0x0100, ENCODE_UPDATE: 0x0200, ENCODE_USER: 0x0400, ENCODE_SAVE: 0x0300, // Compound masks DECODE: 0x00FF, ENCODE: 0xFF00, CREATE: 0x0101, UPDATE: 0x0202, USER: 0x0404, SAVE: 0x0303 }; // Cache some angular stuff var bind = angular.bind, forEach = angular.forEach, extend = angular.extend, isObject = angular.isObject, isArray = angular.isArray, isFunction = angular.isFunction, arraySlice = Array.prototype.slice; /** * @class $restmodProvider * @memberOf providers * * @description * * The $restmodProvider exposes $restmod configuration methods */ angular.module('plRestmod').provider('$restmod', function() { var BASE_CHAIN = []; // The base mixin chain return { /** * @memberof providers.$restmodProvider * * @description * Adds mixins to the base model chain. * * Non abstract models should NOT be added to this chain. * * Base model chain is by default empty, all mixins added to the chain are * prepended to every generated model. * * Usage: * * ```javascript * $provider.pushModelBase('ChangeModel', 'LazyRelations', 'ThrottledModel') * `` */ pushModelBase: function(/* mixins */) { Array.prototype.push.apply(BASE_CHAIN, arguments); return this; }, /** * @class $restmod * @memberOf services * * @description The restmod service provides the `model` and `mixin` factories. */ $get: ['$http', '$q', '$injector', '$parse', '$filter', function($http, $q, $injector, $parse, $filter) { return { /** * @function model * @memberOf services.$restmod# * * @description * * The model factory is used to generate mode types using a rich building DSL provided * by the {@link restmod.class:ModelBuilder ModelBuilder}. * * For more information about model generation see {@link Building a Model} */ model: function(_urlParams/* , _mix */) { var masks = { $partial: SyncMask.ALL, $context: SyncMask.ALL, $promise: SyncMask.ALL, $pending: SyncMask.ALL, $error: SyncMask.ALL }, defaults = [], decoders = {}, encoders = {}, callbacks = {}, nameDecoder = Utils.camelcase, nameEncoder = Utils.snakecase, urlBuilder; // runs all callbacks associated with a given hook. function callback(_hook, _ctx /*, args */) { var cbs = callbacks[_hook]; if(cbs) { var i = 0, args = arraySlice.call(arguments, 2), cb; while((cb = cbs[i++])) { // execute callback cb.apply(_ctx, args); } } } // common http behavior, used both in collections and model instances. function send(_target, _config, _success, _error) { // IDEA: comm queuing, never allow two simultaneous requests. // if(this.$pending) { // this.$promise.then(function() { // this.$send(_config, _success, _error); // }); // } _target.$pending = true; _target.$error = false; _target.$promise = $http(_config).then(function(_response) { // IDEA: a response interceptor could add additional error states based on returned data, // this could allow for additional error state behaviours (for example, an interceptor // could watch for rails validation errors and store them in the model, then return false // to trigger a promise queue error). _target.$pending = false; if(_success) _success.call(_target, _response); return _target; }, function(_response) { _target.$pending = false; _target.$error = true; if(_error) _error.call(_target, _response); return $q.reject(_target); }); } /** * @class Model * * @property {string} $partial The model partial url, relative to the context. * @property {ModelCollection|Model} $context The model context (parent). * @property {promise} $promise The last request promise, returns the model. * @property {boolean} $pending The last request status. * @property {string} $error The last request error, if any. * * @description * * The base model type, this is the starting point for every model generated by $restmod. * * Inherits all static methods from {@link ModelCollection}. * * #### About object creation * * Direct construction of object instances using `new` is not recommended. A collection of * static methods are available to generate new instances of an model, for more information * go check the {@link ModelCollection} documentation. */ var Model = function(_init, _url, _context) { this.$pending = false; this.$partial = _url; this.$context = _context; var tmp; // apply defaults for(var i = 0; (tmp = defaults[i]); i++) { this[tmp[0]] = (typeof tmp[1] === 'function') ? tmp[1].apply(this) : tmp[1]; } if(_init) { // copy initial values (if given) for(tmp in _init) { if (_init.hasOwnProperty(tmp)) { this[tmp] = _init[tmp]; } } } }; Model.prototype = { /** * @memberof Model# * * @description Returns the url this object is bound to. * * @param {object} _opt Options to be passed to the url builder. * @return {string} bound url. */ $url: function(_opt) { return urlBuilder.resourceUrl(this, _opt); }, /** * @memberof Model# * * @description Allows calling custom hooks, usefull when implementing custom actions. * * Passes through every additional arguments to registered hooks. * Hooks are registered using the ModelBuilder.on method. * * @param {string} _hook hook name * @return {Model} self */ $callback: function(_hook /*, args */) { callback(this, _hook, arraySlice.call(arguments, 1)); return this; }, /** * @memberof Model# * * @description Low level communication method, wraps the $http api. * * @param {object} _options $http options * @param {function} _success sucess callback (sync) * @param {function} _error error callback (sync) * @return {Model} self */ $send: function(_options, _success, _error) { send(this, _options, _success, _error); return this; }, /** * @memberof Model# * * @description Promise chaining method, keeps the model instance as the chain context. * * Usage: col.$fetch().$then(function() { }); * * @param {function} _success success callback * @param {function} _error error callback * @return {Model} self */ $then: function(_success, _error) { this.$promise = this.$promise.then(_success, _error); return this; }, /** * @memberof Model# * * @description Feed raw data to this instance. * * @param {object} _raw Raw data to be fed * @param {string} _action Action that originated the fetch * @return {Model} this */ $decode: function(_raw, _mask) { if(!_mask) _mask = SyncMask.DECODE_USER; // TODO: does undefined & 1 evaluates to 0 in every browser? var key, decodedName, decoder, value, original = {}; for(key in _raw) { if(_raw.hasOwnProperty(key) && !((masks[key] || 0) & _mask)) { decodedName = nameDecoder ? nameDecoder(key) : key; decoder = decoders[decodedName]; value = decoder ? decoder.call(this, _raw[key]) : _raw[key]; if(value !== undefined) { original[decodedName] = this[decodedName] = value; } } } callback('after_feed', this, original, _raw); return this; }, /** * @memberof Model# * * @description Generate data to be sent to the server when creating/updating the resource. * * @param {string} _action Action that originated the render * @return {Model} this */ $encode: function(_mask) { if(!_mask) _mask = SyncMask.ENCODE_USER; var key, encodedName, encoder, raw = {}; for(key in this) { if(this.hasOwnProperty(key) && !((masks[key] || 0) & _mask)) { encodedName = nameEncoder ? nameEncoder(key) : key; encoder = encoders[key]; raw[encodedName] = encoder ? encoder.call(this, this[key]) : this[key]; } } callback('before_render', this, raw); return raw; }, /** * @memberof Model# * * @description Begin a server request for updated resource data. * * The request's promise is provided as the $promise property. * * @return {Model} this */ $fetch: function() { // verify that instance has a bound url if(!this.$url()) throw Error('Cannot fetch an unbound resource'); return this.$send({ method: 'GET', url: this.$url(), feed: true }, function(_response) { var data = _response.data; if (!data || isArray(data)) { throw Error('Expected object while feeding resource'); } this.$decode(data); }); }, /** * @memberof Model# * * @description Begin a server request to create/update resource. * * The request's promise is provided as the $promise property. * * @return {Model} this */ $save: function() { var url; if(this.$url()) { // If bound, update url = urlBuilder.updateUrl(this); if(!url) throw Error('Update is not supported by this resource'); callback('before_update', this); callback('before_save', this); return this.$send({ method: 'PUT', url: url, data: this.$encode(SyncMask.ENCODE_CREATE) }, function(_response) { // IDEA: maybe this should be a method call (like $feedCreate), this would allow // a user to override the feed logic for each action... On the other hand, allowing // this breaks the extend-using-hooks convention. var data = _response.data; if (data && !isArray(data)) this.$decode(data, SyncMask.DECODE_UPDATE); callback('after_update', this); callback('after_save', this); }); } else { // If not bound create. url = urlBuilder.createUrl(this); if(!url) throw Error('Create is not supported by this resource'); callback('before_save', this); callback('before_create', this); return this.$send({ method: 'POST', url: url, data: this.$encode(SyncMask.ENCODE_UPDATE) }, function(_response) { var data = _response.data; if (data && !isArray(data)) this.$decode(data, SyncMask.DECODE_CREATE); callback('after_create', this); callback('after_save', this); }); } }, /** * @memberof Model# * * @description Begin a server request to destroy the resource. * * The request's promise is provided as the $promise property. * * @return {Model} this */ $destroy: function() { var url = urlBuilder.destroyUrl(this); if(!url) throw Error('Destroy is not supported by this resource'); callback('before_destroy', this); return this.$send({ method: 'DELETE', url: url }, function() { callback('after_destroy', this); }); } }; /** * @class ModelCollection * * @description * * Collections are sets of model instances bound to a given api resource. When a model * class is generated, the corresponding collection class is also generated. */ var Collection = { /** * @memberof ModelCollection# * * @description Returns the url this collection is bound to. * * @param {object} _opt Options to be passed to the url builder. * @return {string} bound url. */ $url: function(_opt) { return urlBuilder.collectionUrl(this, _opt); }, /** * @memberof ModelCollection# * * @description Builds a new instance of this model * * If `_init` is not an object, then its treated as a primary key. * * @param {object} _init Initial values * @return {Model} model instance */ $build: function(_init) { var init, keyName; if(!isObject(_init)) { init = {}; keyName = urlBuilder.inferKey(this); if(!keyName) throw Error('Cannot infer key, use explicit mode'); init[keyName] = _init; } else init = _init; var obj = new Model(init, null, this); if(this.$isCollection) this.push(obj); // on collection, push new object return obj; }, /** * @memberof ModelCollection# * * @description Builds a new instance of this model using undecoded data * * @param {object} _raw Undecoded data * @return {Model} model instance */ $buildRaw: function(_raw) { return this.$build(null).$decode(_raw); }, /** * @memberof ModelCollection# * * @description Builds and saves a new instance of this model * * @param {object} _attr Data to be saved * @return {Model} model instance */ $create: function(_attr) { return this.$build(_attr).$save(); }, /** * @memberof ModelCollection# * * @description Attempts to resolve a resource using provided data * * If `_init` is not an object, then its treated as a primary key. * * @param {object} _init Data to provide * @return {Model} model instance */ $find: function(_init) { var init, keyName; if(!isObject(_init)) { init = {}; keyName = urlBuilder.inferKey(this); if(!keyName) throw Error('Cannot infer key, use explicit mode'); init[keyName] = _init; } else init = _init; // dont use $build, find does not push into current collection. return (new Model(init, null, this)).$fetch(); }, /** * @memberof ModelCollection# * * @description Builds a new Model collection * * Collections are bound to an api resource. * * @param {object} _params Additional query string parameters * @param {string} _url Optional collection URL (relative to context) * @param {object} _context Collection context override * @return {Collection} Model Collection */ $collection: function(_params, _url, _context) { _params = this.$params ? extend({}, this.$params, _params) : _params; var col = []; // Since Array cannot be extended, use method injection // TODO: try to find a faster alternative, use for loop instead for example. for(var key in Collection) { if(this.hasOwnProperty(key)) col[key] = this[key]; } col.$partial = _url || this.$partial; col.$context = _context || this.$context; col.$isCollection = true; col.$params = _params; col.$pending = false; col.$resolved = false; return col; }, /** * @memberof ModelCollection# * * @description Generates a new collection bound to this context and url and calls $fetch on it. * * @param {object} _params Collection parameters * @return {Collection} Model collection */ $search: function(_params) { return this.$collection(_params).$fetch(); }, // Collection exclusive methods /** * @memberof ModelCollection# * * @description Promise chaining method, keeps the collection instance as the chain context. * * This method is for use in collections only. * * Usage: col.$fetch().$then(function() { }); * * @param {function} _success success callback * @param {function} _error error callback * @return {Collection} self */ $then: function(_success, _error) { if(!this.$isCollection) throw Error('$then is only supported by collections'); this.$promise = this.$promise.then(_success, _error); return this; }, /** * @memberof ModelCollection# * * @description Resets the collection's contents, marks collection as not $resolved * * This method is for use in collections only. * * @return {Collection} self */ $reset: function() { if(!this.$isCollection) throw Error('$reset is only supported by collections'); this.$resolved = false; this.length = 0; return this; }, /** * @memberof ModelCollection# * * @description Feeds raw collection data into the collection, marks collection as $resolved * * This method is for use in collections only. * * @param {array} _raw Data to add * @return {Collection} self */ $feed: function(_raw) { if(!this.$isCollection) throw Error('$feed is only supported by collections'); forEach(_raw, this.$buildRaw, this); this.$resolved = true; return this; }, /** * @memberof ModelCollection# * * @description Begin a server request to populate collection. * * This method is for use in collections only. * * TODO: support POST data queries (complex queries scenarios) * * @param {object} _params Additional request parameters, these parameters are not stored in collection. * @return {Collection} self */ $fetch: function(_params) { if(!this.$isCollection) throw Error('$fetch is only supported by collections'); var params = _params ? extend({}, this.$params || {}, _params) : this.$params; // TODO: check that collection is bound. send(this, { method: 'GET', url: this.$url(), params: params }, function(_response) { var data = _response.data; if(!data || !isArray(data)) { throw Error('Error in resource {0} configuration. Expected response to be array'); } // reset and feed retrieved data. this.$reset().$feed(data); // execute callback callback('after_collection_fetch', this, _response); }); return this; } // IDEA: $fetchMore, $push, $remove, etc }; // Model customization phase: // - Generate the model builder DSL // - Process metadata from base chain // - Process metadata from arguments // Available mappings. var mappings = { init: ['attrDefault'], ignore: ['attrIgnored'], decode: ['attrDecoder', 'param', 'chain'], encode: ['attrEncoder', 'param', 'chain'], serialize: ['attrSerializer'], hasMany: ['hasMany', 'alias'], hasOne: ['hasOne', 'alias'] }, urlBuilderFactory; /** * @class ModelBuilder * * @description * * Provides the DSL for model generation. * * ### About model descriptions * * This class is also responsible for parsing **model description objects** passed to * the mixin chain. * * Example of description: * * ```javascript * $restmod.model('', { * propWithDefault: { init: 20 }, * propWithDecoder: { decode: 'date', chain: true }, * relation: { hasMany: 'Other' }, * }); * ``` * * The descriptions are processed by the `describe` method and mapped to builder attribute methods. * * The following built in property modifiers are provided (see each method docs for usage information): * * * `init` maps to {@link ModelBuilder#attrDefault} * * `ignore` maps to {@link ModelBuilder#attrIgnored} * * `decode` maps to {@link ModelBuilder#attrDecoder} * * `encode` maps to {@link ModelBuilder#attrEncoder} * * `serialize` maps to {@link ModelBuilder#attrSerializer} * * `hasMany` maps to {@link ModelBuilder#hasMany} * * `hasOne` maps to {@link ModelBuilder#hasOne} * * Mapping a *primitive* to a property is the same as using the `init` modifier. * Mapping a *function* to a property calls {@link ModelBuilder#define} on the function. * */ var Builder = { setHttpOptions: function(_options) { // TODO. }, /** * @memberof ModelBuilder# * * @description Change the default url builder. * * The provided factory will be called to provide an url builder * for implement a `get` method that receives the resource baseUrl * and returns an url builder. * * TODO: describe url builder interface * * @param {function} _factory Url builder factory function. */ setUrlBuilderFactory: function(_factory) { urlBuilderFactory = _factory; return this; }, /** * @memberof ModelBuilder# * * @description Changes the way restmod renames attributes every time a server resource is decoded. * * This is intended to be used as a way of keeping property naming style consistent accross * languajes. By default, property naming in js should use camelcase and property naming * in JSON api should use snake case with underscores. * * If `false` is given, then renaming is disabled * * @param {function|false} _value decoding function * @return {ModelBuilder} self */ setNameDecoder: function(_decoder) { nameDecoder = _decoder; return this; }, /** * @memberof ModelBuilder# * * @description Changes the way restmod renames attributes every time a local resource is encoded to be sent. * * This is intended to be used as a way of keeping property naming style consistent accross * languajes. By default, property naming in js should use camelcase and property naming * in JSON api should use snake case with underscores. * * If `false` is given, then renaming is disabled * * @param {function|false} _value encoding function * @return {ModelBuilder} self */ setNameEncoder: function(_encoder) { nameEncoder = _encoder; return this; }, /** * @memberof ModelBuilder# * * @description Disables renaming alltogether * * @return {ModelBuilder} self */ disableRenaming: function() { return this .setNameDecoder(false) .setNameEncoder(false); }, /** * @memberof ModelBuilder# * * @description Extends the builder DSL * * Adds a function to de builder and alternatively maps the function to an * attribute definition keyword that can be later used when calling * `define` or `attribute`. * * Mapping works as following: * * // Given the following call * builder.extend('testAttr', function(_attr, _test, _param1, param2) { * // wharever.. * }, ['test', 'testP1', 'testP2']); * * // A call to * builder.attribute('chapter', { test: 'hello', testP1: 'world' }); * * // Its equivalent to * builder.testAttr('chapter', 'hello', 'world'); * * The method can also be passed an object with various methods to be added. * * @param {string|object} _name function name or object to merge * @param {function} _fun function * @param {array} _mapping function mapping definition * @return {ModelBuilder} self */ extend: function(_name, _fun, _mapping) { if(typeof _name === 'string') { this[_name] = Utils.override(this[name], _fun); if(_mapping) { mappings[_mapping[0]] = _mapping; _mapping[0] = _name; } } else Utils.extendOverriden(this, _name); return this; }, /** * @memberof ModelBuilder# * * @description Parses a description object, calls the proper builder method depending * on each property description type. * * @param {object} _description The description object * @return {ModelBuilder} self */ describe: function(_description) { forEach(_description, function(_desc, _attr) { if(isObject(_desc)) this.attribute(_attr, _desc); else if(isFunction(_desc)) this.define(_attr, _desc); else this.attrDefault(_attr, _desc); }, this); return this; }, /** * @memberof ModelBuilder# * * @description Sets an attribute properties. * * This method uses the attribute modifiers mapping to call proper * modifiers on the argument. * * For example, using the following description on the createdAt attribute * * { decode: 'date', param; 'YY-mm-dd' } * * Is the same as calling * * builder.attrDecoder('createdAt', 'date', 'YY-mm-dd') * * @param {string} _name Attribute name * @param {object} _description Description object * @return {ModelBuilder} self */ attribute: function(_name, _description) { var key, map, args, i; for(key in _description) { if(_description.hasOwnProperty(key)) { map = mappings[key]; if(map) { args = [_name, _description[key]]; for(i = 1; i < map.length; i++) { args.push(_description[map[i]]); } args.push(_description); this[map[0]].apply(this, args); } } } return this; }, /** * @memberof ModelBuilder# * * @description Sets the default value for an attribute. * * Defaults values are set only on object construction phase. * * if `_init` is a function, then its evaluated every time the * default value is required. * * @param {string} _attr Attribute name * @param {mixed} _init Defaulf value / iniline function * @return {ModelBuilder} self */ attrDefault: function(_attr, _init) { // IDEA: maybe fixed defaults could be added to Model prototype... defaults.push([_attr, _init]); return this; }, /** * @memberof ModelBuilder# * * @description Ignores/un-ignores an attribute. * * This method changes the attribute masmask * * @param {string} _attr Attribute name * @param {boolean|integer} _mask Ignore mask. * @param {boolean} _reset If set to true, old mask is reset. * @return {ModelBuilder} self */ attrIgnored: function(_attr, _mask, _reset) { if(_mask === true) { masks[_attr] = SyncMask.ALL; } else if(_mask === false) { delete masks[_attr]; } else if(_reset) { masks[_attr] = _mask; } else { masks[_attr] |= _mask; } return this; }, /** * @memberof ModelBuilder# * * @description Assigns a serializer to a given attribute. * * A _serializer is: * * an object that defines both a `decode` and a `encode` method * * a function that when called returns an object that matches the above description. * * a string that represents an injectable that matches any of the above descriptions. * * @param {string} _name Attribute name * @param {string|object|function} _serializer The serializer * @return {ModelBuilder} self */ attrSerializer: function(_name, _serializer, _opt) { if(typeof _serializer === 'string') { _serializer = $injector.get(Utils.camelcase(_serializer) + 'Serializer') } // TODO: if(!_serializer) throw $setupError if(isFunction(_serializer)) _serializer = _serializer(_opt); if(_serializer.decode) this.attrDecoder(_name, bind(_serializer, _serializer.decode)); if(_serializer.encode) this.attrEncoder(_name, bind(_serializer, _serializer.encode)); return this; }, /** * @memberof ModelBuilder# * * @description Assigns a decoding function/filter to a given attribute. * * @param {string} _name Attribute name * @param {string|function} _filter filter or function to register * @param {mixed} _filterParam Misc filter parameter * @param {boolean} _chain If true, filter is chained to the current attribute filter. * @return {ModelBuilder} self */ attrDecoder: function(_name, _filter, _filterParam, _chain) { if(typeof _filter === 'string') { var filter = $filter(_filter); // TODO: if(!_filter) throw $setupError _filter = function(_value) { return filter(_value, _filterParam); }; } decoders[_name] = _chain ? chain(decoders[_name], _filter) : _filter; return this; }, /** * @memberof ModelBuilder# * * @description Assigns a encoding function/filter to a given attribute. * * @param {string} _name Attribute name * @param {string|function} _filter filter or function to register * @param {mixed} _filterParam Misc filter parameter * @param {boolean} _chain If true, filter is chained to the current attribute filter. * @return {ModelBuilder} self */ attrEncoder: function(_name, _filter, _filterParam, _chain) { if(typeof _filter === 'string') { var filter = $filter(_filter); // TODO: if(!_filter) throw $setupError _filter = function(_value) { return filter(_value, _filterParam); }; } encoders[_name] = _chain ? chain(encoders[_name], _filter) : _filter; return this; }, /** * @memberof ModelBuilder# * * @description Registers a model hasMany relation * * The `_model` attribute supports both a string (using injector) o * a direct restmod Model type reference. * * @param {string} _name Attribute name * @param {string|object} _model Other model * @param {string} _url Partial url * @return {ModelBuilder} self */ hasMany: function(_name, _model, _alias) { return this.attrDefault(_name, function() { if(typeof _model === 'string') _model = $injector.get(_model); // inject type (only the first time...) return _model.$collection(null, _alias || Utils.snakecase(_name, '-'), this); // TODO: put snakecase transformation in URLBuilder }).attrDecoder(_name, function(_raw) { this[_name].$feed(_raw); }); }, /** * @memberof ModelBuilder# * * @description Registers a model hasOne relation * * The `_model` attribute supports both a string (using injector) o * a direct restmod Model type reference. * * @param {string} _name Attribute name * @param {string|object} _model Other model * @param {string} _url Partial url * @return {ModelBuilder} self */ hasOne: function(_name, _model, _partial) { return this.attrDefault(_name, function() { if(typeof _model === 'string') _model = $injector.get(_model); // inject type (only the first time...) return new _model(null, _partial || Utils.snakecase(_name, '-'), this); // TODO: put snakecase transformation in URLBuilder }).attrDecoder(_name, function(_raw) { this[_name].$decode(_raw); }); }, /** * @memberof ModelBuilder# * * @description Registers an instance method * * Usage: * builder.define(function(_super) { * return $fetch() * }); * * It is posible to override an existing method using define, * if overriden, the old method can be called using `this.$super` * inside de new method. * * @param {string} _name Method name * @param {function} _fun Function to define * @return {ModelBuilder} self */ define: function(_name, _fun) { if(typeof _name === 'string') { Model.prototype[_name] = Utils.override(Model.prototype[_name], _fun); } else { Utils.extendOverriden(Model.prototype, _name); } return this; }, /** * @memberof ModelBuilder# * * @description Registers a class method * * It is posible to override an existing method using define, * if overriden, the old method can be called using `this.$super` * inside de new method. * * @param {string} _name Method name * @param {function} _fun Function to define * @return {ModelBuilder} self */ classDefine: function(_name, _fun) { if(typeof _name === 'string') { Collection[_name] = Utils.override(Collection[_name], _fun); } else { Utils.extendOverriden(Collection, _name); } return this; }, /** * @memberof ModelBuilder# * * @description Adds an event hook * * Hooks are used to extend or modify the model behavior, and are not * designed to be used as an event listening system. * * The given function is executed in the hook's context, different hooks * make different parameters available to callbacks. * * @param {string} _hook The hook name, refer to restmod docs for builtin hooks. * @param {function} _do function to be executed * @return {ModelBuilder} self */ on: function(_hook, _do) { var cbs = callbacks[_hook]; if(!cbs) cbs = callbacks[_hook] = []; cbs.push(_do); return this; }, beforeSave: function(_do) { return this.on('before_save', _do); }, beforeCreate: function(_do) { return this.on('before_create', _do); }, afterCreate: function(_do) { return this.on('after_create', _do); }, beforeUpdate: function(_do) { return this.on('before_update', _do); }, afterUpdate: function(_do) { return this.on('after_update', _do); }, afterSave: function(_do) { return this.on('after_save', _do); }, beforeDestroy: function(_do) { return this.on('before_destroy', _do); }, afterDestroy: function(_do) { return this.on('after_destroy', _do); }, afterFeed: function(_do) { return this.on('after_feed', _do); }, beforeRender: function(_do) { return this.on('before_render', _do); }, /// Experimental modifiers /** * @memberof ModelBuilder# * * @description Volatile attributes are reset after being rendered. * * @param {string} _name Attribute name * @param {boolean} _isVolatile Default/Reset value * @return {ModelBuilder} self */ attrVolatile: function(_attr, _init) { return this.attrDefault(_attr, _init).attrEncoder(_attr, function(_value) { // Not sure about modifying object during encoding this[_attr] = isFunction(_init) ? _init.call(this) : _init; return _value; }, null, true); }, /** * @memberof ModelBuilder# * * @description Expression attributes are evaluated every time new data is fed to the model. * * @param {string} _name Attribute name * @param {string} _expr Angular expression to evaluate * @return {ModelBuilder} self */ attrExpression: function(_name, _expr) { var filter = $parse(_expr); this.on('after_feed', function() { this[_name] = filter(this); }); } }; // use the builder to process a mixin chain function loadMixinChain(_chain) { for(var i = 0, l = _chain.length; i < l; i++) { loadMixin(_chain[i]); } } // use the builder to process a single mixin function loadMixin(_mix) { if(_mix.$chain) { loadMixinChain(_mix.$chain); } else if(typeof _mix === 'string') { loadMixin($injector.get(_mix)); } else if(isArray(_mix) || isFunction(_mix)) { // TODO: maybe invoke should only be called for BASE_CHAIN functions $injector.invoke(_mix, Builder, { $builder: Builder }); } else Builder.describe(_mix); } loadMixinChain(BASE_CHAIN); loadMixinChain(Model.$chain = arraySlice.call(arguments, 1)); /* * Mixin post-processing phase */ // by default use the restUrlBuilder urlBuilder = (urlBuilderFactory || $injector.get('restUrlBuilderFactory')())(_urlParams); // TODO postprocessing of collection prototype. extend(Model, Collection); return Model; }, /** * @method mixin * @memberOf services.$restmod# * * @description * * The mixin factory * * A mixin is just a metadata container that can be included in a mixin chain. * * @return {object} The abstract model */ mixin: function(/* mixins */) { return { $isAbstract: true, $chain: arraySlice.call(arguments, 0) }; } }; }] }; }) .factory('model', ['$restmod', function($restmod) { return $restmod.model; }]) .factory('mixin', ['$restmod', function($restmod) { return $restmod.mixin; }]) // make SyncMask available as constant .constant('SyncMask', SyncMask); /** * @method restUrlBuilderFactory * @memberOf constants * * @description This will no longer be provided as a constant. */ angular.module('plRestmod') .constant('restUrlBuilderFactory', (function() { // Url join function function joinUrl(_base/*, parts */) { var i = 1, url = (_base + '').replace(/\/$/, ''), partial; while((partial = arguments[i++]) !== undefined) { url += '/' + (partial + '').replace(/(\/$|^\/)/g, ''); } return url; } return function(_options) { _options = _options || {}; var primary = _options.primary || 'id'; /** * @class RestUrlBuilder * * @description The default url builder implementation * * Instances of RestUrlBuilder are generated using the restUrlBuilderFactory. * The restUrlBuilderFactory is provided as constant and is actually a factory factory. * * Factory usage: * * ```javascript * return $restmod(function() { * var builderFactory = restUrlBuilderFactory({ options }); // restUrlBuilderFactory injection not shown. * this.setUrlBuilderFactory(builderFactory); * // or using the provided helper. * this.setRestUrlOptions({ options }); * }); * ``` * */ return function(_resUrl) { if(_options.baseUrl) _resUrl = joinUrl(_options.baseUrl, _resUrl); // gives the finishing touches to an url before returning function prepareUrl(_url, _opt) { if(_url) { _url = _url.replace(/\/$/, ''); // always remove trailing slash var ext = (_opt && _opt.extension !== undefined) ? _opt.extension : _options.extension; if(ext) { _url += ext[0] !== '.' ? '.' + ext : ext; } } return _url; } return { /** * @method * @memberOf RestUrlBuilder# * * @description Called to provide a resource's primary key given a resource. * * IDEA: replace this by something like extractKey? */ inferKey: function(/* _res */) { return primary; }, /** * @method * @memberOf RestUrlBuilder# * * @description Called to provide a resource's url. * * The resource url is used to fetch resource contents and to provide * a base url for children. * * IDEA: merge resourceUrl and collectionUrl code? * * @param {Model} _res target resource * @param {mixed} _opt options passed to the $url() function. * @return {string} The resource url, null if anonymous */ resourceUrl: function(_res, _opt) { var partial = _res.$partial, pk = _res[primary]; // TODO: prefer object 'url' property before anything // prefer baseUrl + pk => $context + partial => $context + pk => partial // TODO: not sure about these priorities, pk is before partial just to // have the same logic for fetch and update... if(pk != null && _resUrl) return prepareUrl(joinUrl(_resUrl, pk), _opt); if(partial != null && _res.$context) return prepareUrl(joinUrl(_res.$context, partial), _opt); if(pk != null && _res.$context) return prepareUrl(joinUrl(_res.$context, pk), _opt); if(partial != null) return prepareUrl(partial); return null; }, /** * @method * @memberOf RestUrlBuilder# * * @description Called to provide a collection's url. * * The collection url is used to fetch collection contents and to provide * a base url for children. * * @param {Collection} _col target collection * @param {mixed} _opt options passed to the $url() function. * @return {string} The collection url, null if anonymous */ collectionUrl: function(_col, _opt) { if(_col.$context) { var base = _col.$context.$url({ extension: false }); if(!base) return null; return prepareUrl(_col.$partial ? joinUrl(base, _col.$partial) : base, _opt); } else if(_col.$partial) { return prepareUrl(_col.$partial, _opt); } else { return prepareUrl(_resUrl, _opt); } }, /** * @method * @memberOf RestUrlBuilder# * * @description Called to provide an url for resource creation. * * @param {Model} _res target resource * @return {string} url */ createUrl: function(_res) { return _res.$context ? _res.$context.$url() : prepareUrl(_resUrl); }, /** * @method * @memberOf RestUrlBuilder# * * @description Called to provide an url for resource update. * * Returns the resource url by default. * * @param {Model} _res target resource * @return {string} url */ updateUrl: function(_res) { return this.resourceUrl(_res); }, /** * @method * @memberOf RestUrlBuilder# * * @description Called to provide an url for resource destruction. * * Returns the resource url by default. * * @param {Model} _res target resource * @return {string} url */ destroyUrl: function(_res) { return this.resourceUrl(_res); } }; }; }; })()) .config(['$restmodProvider', function($restmodProvider) { $restmodProvider.pushModelBase(['$injector', function($injector) { /** * @method setRestUrlOption * @memberof ModelBuilder# * * @description The setRestUrlOptions extensions allows to easily setup a rest url builder factory * for a given model chain. * * This is only available if the restUrlBuilderFactory is included. * * TODO: improve inheritance support. * * Available `options` are: * * primary: the selected primary key, defaults to 'id'. * * baseUrl: the api base url, this will be prepended to every url path. * * extension: a extension to append to every generated url. * * @param {object} _options Options * @return {ModelBuilder} self */ this.extend('setRestUrlOptions', function(_options) { return this.setUrlBuilderFactory($injector.get('restUrlBuilderFactory')(_options)); }); }]); }]); })(angular);
/** * React v0.10.0-rc1 */ !function(e){if("object"==typeof exports)module.exports=e();else if("function"==typeof define&&define.amd)define(e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.React=e()}}(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){ /** * Copyright 2013-2014 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. * * @providesModule AutoFocusMixin * @typechecks static-only */ "use strict"; var focusNode = _dereq_("./focusNode"); var AutoFocusMixin = { componentDidMount: function() { if (this.props.autoFocus) { focusNode(this.getDOMNode()); } } }; module.exports = AutoFocusMixin; },{"./focusNode":100}],2:[function(_dereq_,module,exports){ /** * Copyright 2013-2014 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. * * @providesModule CSSProperty */ "use strict"; /** * CSS properties which accept numbers but are not in units of "px". */ var isUnitlessNumber = { columnCount: true, fillOpacity: true, flex: true, flexGrow: true, flexShrink: true, fontWeight: true, lineClamp: true, lineHeight: true, opacity: true, order: true, orphans: true, widows: true, zIndex: true, zoom: 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: { backgroundImage: true, backgroundPosition: true, backgroundRepeat: true, backgroundColor: 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 } }; var CSSProperty = { isUnitlessNumber: isUnitlessNumber, shorthandPropertyExpansions: shorthandPropertyExpansions }; module.exports = CSSProperty; },{}],3:[function(_dereq_,module,exports){ /** * Copyright 2013-2014 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. * * @providesModule CSSPropertyOperations * @typechecks static-only */ "use strict"; var CSSProperty = _dereq_("./CSSProperty"); var dangerousStyleValue = _dereq_("./dangerousStyleValue"); var escapeTextForBrowser = _dereq_("./escapeTextForBrowser"); var hyphenate = _dereq_("./hyphenate"); var memoizeStringOnly = _dereq_("./memoizeStringOnly"); var processStyleName = memoizeStringOnly(function(styleName) { return escapeTextForBrowser(hyphenate(styleName)); }); /** * 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. * * @param {object} styles * @return {?string} */ createMarkupForStyles: function(styles) { var serialized = ''; for (var styleName in styles) { if (!styles.hasOwnProperty(styleName)) { continue; } var styleValue = styles[styleName]; if (styleValue != null) { serialized += processStyleName(styleName) + ':'; serialized += dangerousStyleValue(styleName, styleValue) + ';'; } } 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 */ setValueForStyles: function(node, styles) { var style = node.style; for (var styleName in styles) { if (!styles.hasOwnProperty(styleName)) { continue; } var styleValue = dangerousStyleValue(styleName, styles[styleName]); if (styleValue) { style[styleName] = styleValue; } else { var expansion = 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; },{"./CSSProperty":2,"./dangerousStyleValue":95,"./escapeTextForBrowser":98,"./hyphenate":110,"./memoizeStringOnly":120}],4:[function(_dereq_,module,exports){ /** * Copyright 2013-2014 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. * * @providesModule ChangeEventPlugin */ "use strict"; var EventConstants = _dereq_("./EventConstants"); var EventPluginHub = _dereq_("./EventPluginHub"); var EventPropagators = _dereq_("./EventPropagators"); var ExecutionEnvironment = _dereq_("./ExecutionEnvironment"); var ReactUpdates = _dereq_("./ReactUpdates"); var SyntheticEvent = _dereq_("./SyntheticEvent"); var isEventSupported = _dereq_("./isEventSupported"); var isTextInputElement = _dereq_("./isTextInputElement"); var keyOf = _dereq_("./keyOf"); var topLevelTypes = EventConstants.topLevelTypes; var eventTypes = { change: { phasedRegistrationNames: { bubbled: keyOf({onChange: null}), captured: keyOf({onChangeCapture: null}) }, dependencies: [ topLevelTypes.topBlur, topLevelTypes.topChange, topLevelTypes.topClick, topLevelTypes.topFocus, topLevelTypes.topInput, topLevelTypes.topKeyDown, topLevelTypes.topKeyUp, topLevelTypes.topSelectionChange ] } }; /** * For IE shims */ var activeElement = null; var activeElementID = null; var activeElementValue = null; var activeElementValueProp = null; /** * SECTION: handle `change` event */ function shouldUseChangeEvent(elem) { return ( elem.nodeName === 'SELECT' || (elem.nodeName === 'INPUT' && elem.type === 'file') ); } var doesChangeEventBubble = false; if (ExecutionEnvironment.canUseDOM) { // See `handleChange` comment below doesChangeEventBubble = isEventSupported('change') && ( !('documentMode' in document) || document.documentMode > 8 ); } function manualDispatchChangeEvent(nativeEvent) { var event = SyntheticEvent.getPooled( eventTypes.change, activeElementID, nativeEvent ); EventPropagators.accumulateTwoPhaseDispatches(event); // If change and propertychange bubbled, we'd just bind to it like all the // other events and have it go through ReactEventTopLevelCallback. 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. ReactUpdates.batchedUpdates(runEventInBatch, event); } function runEventInBatch(event) { EventPluginHub.enqueueEvents(event); EventPluginHub.processEventQueue(); } function startWatchingForChangeEventIE8(target, targetID) { activeElement = target; activeElementID = targetID; activeElement.attachEvent('onchange', manualDispatchChangeEvent); } function stopWatchingForChangeEventIE8() { if (!activeElement) { return; } activeElement.detachEvent('onchange', manualDispatchChangeEvent); activeElement = null; activeElementID = null; } function getTargetIDForChangeEvent( topLevelType, topLevelTarget, topLevelTargetID) { if (topLevelType === topLevelTypes.topChange) { return topLevelTargetID; } } function handleEventsForChangeEventIE8( topLevelType, topLevelTarget, topLevelTargetID) { if (topLevelType === topLevelTypes.topFocus) { // stopWatching() should be a noop here but we call it just in case we // missed a blur event somehow. stopWatchingForChangeEventIE8(); startWatchingForChangeEventIE8(topLevelTarget, topLevelTargetID); } else if (topLevelType === topLevelTypes.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') && ( !('documentMode' in document) || document.documentMode > 9 ); } /** * (For old IE.) Replacement getter/setter for the `value` property that gets * set on the active element. */ var newValueProp = { get: function() { return activeElementValueProp.get.call(this); }, set: function(val) { // Cast to a string so we can do equality checks. activeElementValue = '' + val; activeElementValueProp.set.call(this, val); } }; /** * (For old IE.) 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, targetID) { activeElement = target; activeElementID = targetID; activeElementValue = target.value; activeElementValueProp = Object.getOwnPropertyDescriptor( target.constructor.prototype, 'value' ); Object.defineProperty(activeElement, 'value', newValueProp); activeElement.attachEvent('onpropertychange', handlePropertyChange); } /** * (For old IE.) Removes the event listeners from the currently-tracked element, * if any exists. */ function stopWatchingForValueChange() { if (!activeElement) { return; } // delete restores the original property definition delete activeElement.value; activeElement.detachEvent('onpropertychange', handlePropertyChange); activeElement = null; activeElementID = null; activeElementValue = null; activeElementValueProp = null; } /** * (For old IE.) 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; } var value = nativeEvent.srcElement.value; if (value === activeElementValue) { return; } activeElementValue = value; manualDispatchChangeEvent(nativeEvent); } /** * If a `change` event should be fired, returns the target's ID. */ function getTargetIDForInputEvent( topLevelType, topLevelTarget, topLevelTargetID) { if (topLevelType === topLevelTypes.topInput) { // In modern browsers (i.e., not IE8 or IE9), the input event is exactly // what we want so fall through here and trigger an abstract event return topLevelTargetID; } } // For IE8 and IE9. function handleEventsForInputEventIE( topLevelType, topLevelTarget, topLevelTargetID) { if (topLevelType === topLevelTypes.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(topLevelTarget, topLevelTargetID); } else if (topLevelType === topLevelTypes.topBlur) { stopWatchingForValueChange(); } } // For IE8 and IE9. function getTargetIDForInputEventIE( topLevelType, topLevelTarget, topLevelTargetID) { if (topLevelType === topLevelTypes.topSelectionChange || topLevelType === topLevelTypes.topKeyUp || topLevelType === topLevelTypes.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. if (activeElement && activeElement.value !== activeElementValue) { activeElementValue = activeElement.value; return activeElementID; } } } /** * 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. return ( elem.nodeName === 'INPUT' && (elem.type === 'checkbox' || elem.type === 'radio') ); } function getTargetIDForClickEvent( topLevelType, topLevelTarget, topLevelTargetID) { if (topLevelType === topLevelTypes.topClick) { return topLevelTargetID; } } /** * 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, /** * @param {string} topLevelType Record from `EventConstants`. * @param {DOMEventTarget} topLevelTarget The listening component root node. * @param {string} topLevelTargetID ID of `topLevelTarget`. * @param {object} nativeEvent Native browser event. * @return {*} An accumulation of synthetic events. * @see {EventPluginHub.extractEvents} */ extractEvents: function( topLevelType, topLevelTarget, topLevelTargetID, nativeEvent) { var getTargetIDFunc, handleEventFunc; if (shouldUseChangeEvent(topLevelTarget)) { if (doesChangeEventBubble) { getTargetIDFunc = getTargetIDForChangeEvent; } else { handleEventFunc = handleEventsForChangeEventIE8; } } else if (isTextInputElement(topLevelTarget)) { if (isInputEventSupported) { getTargetIDFunc = getTargetIDForInputEvent; } else { getTargetIDFunc = getTargetIDForInputEventIE; handleEventFunc = handleEventsForInputEventIE; } } else if (shouldUseClickEvent(topLevelTarget)) { getTargetIDFunc = getTargetIDForClickEvent; } if (getTargetIDFunc) { var targetID = getTargetIDFunc( topLevelType, topLevelTarget, topLevelTargetID ); if (targetID) { var event = SyntheticEvent.getPooled( eventTypes.change, targetID, nativeEvent ); EventPropagators.accumulateTwoPhaseDispatches(event); return event; } } if (handleEventFunc) { handleEventFunc( topLevelType, topLevelTarget, topLevelTargetID ); } } }; module.exports = ChangeEventPlugin; },{"./EventConstants":14,"./EventPluginHub":16,"./EventPropagators":19,"./ExecutionEnvironment":20,"./ReactUpdates":71,"./SyntheticEvent":78,"./isEventSupported":113,"./isTextInputElement":115,"./keyOf":119}],5:[function(_dereq_,module,exports){ /** * Copyright 2013-2014 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. * * @providesModule ClientReactRootIndex * @typechecks */ "use strict"; var nextReactRootIndex = 0; var ClientReactRootIndex = { createReactRootIndex: function() { return nextReactRootIndex++; } }; module.exports = ClientReactRootIndex; },{}],6:[function(_dereq_,module,exports){ /** * Copyright 2013-2014 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. * * @providesModule CompositionEventPlugin * @typechecks static-only */ "use strict"; var EventConstants = _dereq_("./EventConstants"); var EventPropagators = _dereq_("./EventPropagators"); var ExecutionEnvironment = _dereq_("./ExecutionEnvironment"); var ReactInputSelection = _dereq_("./ReactInputSelection"); var SyntheticCompositionEvent = _dereq_("./SyntheticCompositionEvent"); var getTextContentAccessor = _dereq_("./getTextContentAccessor"); var keyOf = _dereq_("./keyOf"); var END_KEYCODES = [9, 13, 27, 32]; // Tab, Return, Esc, Space var START_KEYCODE = 229; var useCompositionEvent = ( ExecutionEnvironment.canUseDOM && 'CompositionEvent' in window ); // In IE9+, we have access to composition events, but the data supplied // by the native compositionend event may be incorrect. In Korean, for example, // the compositionend event contains only one character regardless of // how many characters have been composed since compositionstart. // We therefore use the fallback data while still using the native // events as triggers. var useFallbackData = ( !useCompositionEvent || 'documentMode' in document && document.documentMode > 8 ); var topLevelTypes = EventConstants.topLevelTypes; var currentComposition = null; // Events and their corresponding property names. var eventTypes = { compositionEnd: { phasedRegistrationNames: { bubbled: keyOf({onCompositionEnd: null}), captured: keyOf({onCompositionEndCapture: null}) }, dependencies: [ topLevelTypes.topBlur, topLevelTypes.topCompositionEnd, topLevelTypes.topKeyDown, topLevelTypes.topKeyPress, topLevelTypes.topKeyUp, topLevelTypes.topMouseDown ] }, compositionStart: { phasedRegistrationNames: { bubbled: keyOf({onCompositionStart: null}), captured: keyOf({onCompositionStartCapture: null}) }, dependencies: [ topLevelTypes.topBlur, topLevelTypes.topCompositionStart, topLevelTypes.topKeyDown, topLevelTypes.topKeyPress, topLevelTypes.topKeyUp, topLevelTypes.topMouseDown ] }, compositionUpdate: { phasedRegistrationNames: { bubbled: keyOf({onCompositionUpdate: null}), captured: keyOf({onCompositionUpdateCapture: null}) }, dependencies: [ topLevelTypes.topBlur, topLevelTypes.topCompositionUpdate, topLevelTypes.topKeyDown, topLevelTypes.topKeyPress, topLevelTypes.topKeyUp, topLevelTypes.topMouseDown ] } }; /** * Translate native top level events into event types. * * @param {string} topLevelType * @return {object} */ function getCompositionEventType(topLevelType) { switch (topLevelType) { case topLevelTypes.topCompositionStart: return eventTypes.compositionStart; case topLevelTypes.topCompositionEnd: return eventTypes.compositionEnd; case topLevelTypes.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 isFallbackStart(topLevelType, nativeEvent) { return ( topLevelType === topLevelTypes.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 isFallbackEnd(topLevelType, nativeEvent) { switch (topLevelType) { case topLevelTypes.topKeyUp: // Command keys insert or clear IME input. return (END_KEYCODES.indexOf(nativeEvent.keyCode) !== -1); case topLevelTypes.topKeyDown: // Expect IME keyCode on each keydown. If we get any other // code we must have exited earlier. return (nativeEvent.keyCode !== START_KEYCODE); case topLevelTypes.topKeyPress: case topLevelTypes.topMouseDown: case topLevelTypes.topBlur: // Events are not possible without cancelling IME. return true; default: return false; } } /** * Helper class stores information about selection and document state * so we can figure out what changed at a later date. * * @param {DOMEventTarget} root */ function FallbackCompositionState(root) { this.root = root; this.startSelection = ReactInputSelection.getSelection(root); this.startValue = this.getText(); } /** * Get current text of input. * * @return {string} */ FallbackCompositionState.prototype.getText = function() { return this.root.value || this.root[getTextContentAccessor()]; }; /** * Text that has changed since the start of composition. * * @return {string} */ FallbackCompositionState.prototype.getData = function() { var endValue = this.getText(); var prefixLength = this.startSelection.start; var suffixLength = this.startValue.length - this.startSelection.end; return endValue.substr( prefixLength, endValue.length - suffixLength - prefixLength ); }; /** * This plugin creates `onCompositionStart`, `onCompositionUpdate` and * `onCompositionEnd` events on inputs, textareas and contentEditable * nodes. */ var CompositionEventPlugin = { eventTypes: eventTypes, /** * @param {string} topLevelType Record from `EventConstants`. * @param {DOMEventTarget} topLevelTarget The listening component root node. * @param {string} topLevelTargetID ID of `topLevelTarget`. * @param {object} nativeEvent Native browser event. * @return {*} An accumulation of synthetic events. * @see {EventPluginHub.extractEvents} */ extractEvents: function( topLevelType, topLevelTarget, topLevelTargetID, nativeEvent) { var eventType; var data; if (useCompositionEvent) { eventType = getCompositionEventType(topLevelType); } else if (!currentComposition) { if (isFallbackStart(topLevelType, nativeEvent)) { eventType = eventTypes.compositionStart; } } else if (isFallbackEnd(topLevelType, nativeEvent)) { eventType = eventTypes.compositionEnd; } if (useFallbackData) { // The current composition is stored statically and must not be // overwritten while composition continues. if (!currentComposition && eventType === eventTypes.compositionStart) { currentComposition = new FallbackCompositionState(topLevelTarget); } else if (eventType === eventTypes.compositionEnd) { if (currentComposition) { data = currentComposition.getData(); currentComposition = null; } } } if (eventType) { var event = SyntheticCompositionEvent.getPooled( eventType, topLevelTargetID, nativeEvent ); if (data) { // Inject data generated from fallback path into the synthetic event. // This matches the property of native CompositionEventInterface. event.data = data; } EventPropagators.accumulateTwoPhaseDispatches(event); return event; } } }; module.exports = CompositionEventPlugin; },{"./EventConstants":14,"./EventPropagators":19,"./ExecutionEnvironment":20,"./ReactInputSelection":52,"./SyntheticCompositionEvent":76,"./getTextContentAccessor":108,"./keyOf":119}],7:[function(_dereq_,module,exports){ /** * Copyright 2013-2014 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. * * @providesModule DOMChildrenOperations * @typechecks static-only */ "use strict"; var Danger = _dereq_("./Danger"); var ReactMultiChildUpdateTypes = _dereq_("./ReactMultiChildUpdateTypes"); var getTextContentAccessor = _dereq_("./getTextContentAccessor"); /** * The DOM property to use when setting text content. * * @type {string} * @private */ var textContentAccessor = getTextContentAccessor(); /** * 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 */ function insertChildAt(parentNode, childNode, index) { var childNodes = parentNode.childNodes; if (childNodes[index] === childNode) { return; } // If `childNode` is already a child of `parentNode`, remove it so that // computing `childNodes[index]` takes into account the removal. if (childNode.parentNode === parentNode) { parentNode.removeChild(childNode); } if (index >= childNodes.length) { parentNode.appendChild(childNode); } else { parentNode.insertBefore(childNode, childNodes[index]); } } var updateTextContent; if (textContentAccessor === 'textContent') { /** * Sets the text content of `node` to `text`. * * @param {DOMElement} node Node to change * @param {string} text New text content */ updateTextContent = function(node, text) { node.textContent = text; }; } else { /** * Sets the text content of `node` to `text`. * * @param {DOMElement} node Node to change * @param {string} text New text content */ updateTextContent = function(node, text) { // In order to preserve newlines correctly, we can't use .innerText to set // the contents (see #1080), so we empty the element then append a text node while (node.firstChild) { node.removeChild(node.firstChild); } if (text) { var doc = node.ownerDocument || document; node.appendChild(doc.createTextNode(text)); } }; } /** * Operations for updating with DOM children. */ var DOMChildrenOperations = { dangerouslyReplaceNodeWithMarkup: Danger.dangerouslyReplaceNodeWithMarkup, updateTextContent: updateTextContent, /** * 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. * @param {array<string>} markupList List of markup strings. * @internal */ processUpdates: function(updates, markupList) { var update; // Mapping from parent IDs to initial child orderings. var initialChildren = null; // List of children that will be moved or removed. var updatedChildren = null; for (var i = 0; update = updates[i]; i++) { if (update.type === ReactMultiChildUpdateTypes.MOVE_EXISTING || update.type === ReactMultiChildUpdateTypes.REMOVE_NODE) { var updatedIndex = update.fromIndex; var updatedChild = update.parentNode.childNodes[updatedIndex]; var parentID = update.parentID; initialChildren = initialChildren || {}; initialChildren[parentID] = initialChildren[parentID] || []; initialChildren[parentID][updatedIndex] = updatedChild; updatedChildren = updatedChildren || []; updatedChildren.push(updatedChild); } } var renderedMarkup = Danger.dangerouslyRenderMarkup(markupList); // Remove updated children first so that `toIndex` is consistent. if (updatedChildren) { for (var j = 0; j < updatedChildren.length; j++) { updatedChildren[j].parentNode.removeChild(updatedChildren[j]); } } for (var k = 0; update = updates[k]; k++) { switch (update.type) { case ReactMultiChildUpdateTypes.INSERT_MARKUP: insertChildAt( update.parentNode, renderedMarkup[update.markupIndex], update.toIndex ); break; case ReactMultiChildUpdateTypes.MOVE_EXISTING: insertChildAt( update.parentNode, initialChildren[update.parentID][update.fromIndex], update.toIndex ); break; case ReactMultiChildUpdateTypes.TEXT_CONTENT: updateTextContent( update.parentNode, update.textContent ); break; case ReactMultiChildUpdateTypes.REMOVE_NODE: // Already removed by the for-loop above. break; } } } }; module.exports = DOMChildrenOperations; },{"./Danger":10,"./ReactMultiChildUpdateTypes":58,"./getTextContentAccessor":108}],8:[function(_dereq_,module,exports){ /** * Copyright 2013-2014 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. * * @providesModule DOMProperty * @typechecks static-only */ /*jslint bitwise: true */ "use strict"; var invariant = _dereq_("./invariant"); 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_ATTRIBUTE: 0x1, MUST_USE_PROPERTY: 0x2, HAS_SIDE_EFFECTS: 0x4, HAS_BOOLEAN_VALUE: 0x8, HAS_POSITIVE_NUMERIC_VALUE: 0x10, /** * 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. * * 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 Properties = domPropertyConfig.Properties || {}; 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) { ("production" !== "development" ? invariant( !DOMProperty.isStandardName[propName], '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 ) : invariant(!DOMProperty.isStandardName[propName])); DOMProperty.isStandardName[propName] = true; var lowerCased = propName.toLowerCase(); DOMProperty.getPossibleStandardName[lowerCased] = propName; var attributeName = DOMAttributeNames[propName]; if (attributeName) { DOMProperty.getPossibleStandardName[attributeName] = propName; } DOMProperty.getAttributeName[propName] = attributeName || lowerCased; DOMProperty.getPropertyName[propName] = DOMPropertyNames[propName] || propName; var mutationMethod = DOMMutationMethods[propName]; if (mutationMethod) { DOMProperty.getMutationMethod[propName] = mutationMethod; } var propConfig = Properties[propName]; DOMProperty.mustUseAttribute[propName] = propConfig & DOMPropertyInjection.MUST_USE_ATTRIBUTE; DOMProperty.mustUseProperty[propName] = propConfig & DOMPropertyInjection.MUST_USE_PROPERTY; DOMProperty.hasSideEffects[propName] = propConfig & DOMPropertyInjection.HAS_SIDE_EFFECTS; DOMProperty.hasBooleanValue[propName] = propConfig & DOMPropertyInjection.HAS_BOOLEAN_VALUE; DOMProperty.hasPositiveNumericValue[propName] = propConfig & DOMPropertyInjection.HAS_POSITIVE_NUMERIC_VALUE; ("production" !== "development" ? invariant( !DOMProperty.mustUseAttribute[propName] || !DOMProperty.mustUseProperty[propName], 'DOMProperty: Cannot require using both attribute and property: %s', propName ) : invariant(!DOMProperty.mustUseAttribute[propName] || !DOMProperty.mustUseProperty[propName])); ("production" !== "development" ? invariant( DOMProperty.mustUseProperty[propName] || !DOMProperty.hasSideEffects[propName], 'DOMProperty: Properties that have side effects must use property: %s', propName ) : invariant(DOMProperty.mustUseProperty[propName] || !DOMProperty.hasSideEffects[propName])); ("production" !== "development" ? invariant( !DOMProperty.hasBooleanValue[propName] || !DOMProperty.hasPositiveNumericValue[propName], 'DOMProperty: Cannot have both boolean and positive numeric value: %s', propName ) : invariant(!DOMProperty.hasBooleanValue[propName] || !DOMProperty.hasPositiveNumericValue[propName])); } } }; var defaultValueCache = {}; /** * 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', /** * Checks whether a property name is a standard property. * @type {Object} */ isStandardName: {}, /** * Mapping from lowercase property names to the properly cased version, used * to warn in the case of missing properties. * @type {Object} */ getPossibleStandardName: {}, /** * Mapping from normalized names to attribute names that differ. Attribute * names are used when rendering markup or with `*Attribute()`. * @type {Object} */ getAttributeName: {}, /** * Mapping from normalized names to properties on DOM node instances. * (This includes properties that mutate due to external factors.) * @type {Object} */ getPropertyName: {}, /** * Mapping from normalized names to mutation methods. This will only exist if * mutation cannot be set simply by the property or `setAttribute()`. * @type {Object} */ getMutationMethod: {}, /** * Whether the property must be accessed and mutated as an object property. * @type {Object} */ mustUseAttribute: {}, /** * Whether the property must be accessed and mutated using `*Attribute()`. * (This includes anything that fails `<propName> in <element>`.) * @type {Object} */ mustUseProperty: {}, /** * Whether or not setting a value causes side effects such as triggering * resources to be loaded or text selection changes. We must ensure that * the value is only set if it has changed. * @type {Object} */ hasSideEffects: {}, /** * Whether the property should be removed when set to a falsey value. * @type {Object} */ hasBooleanValue: {}, /** * Whether the property must be positive numeric or parse as a positive * numeric and should be removed when set to a falsey value. * @type {Object} */ hasPositiveNumericValue: {}, /** * 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; }, /** * Returns the default property value for a DOM property (i.e., not an * attribute). Most default values are '' or false, but not all. Worse yet, * some (in particular, `type`) vary depending on the type of element. * * TODO: Is it better to grab all the possible properties when creating an * element to avoid having to create the same element twice? */ getDefaultValueForProperty: function(nodeName, prop) { var nodeDefaults = defaultValueCache[nodeName]; var testElement; if (!nodeDefaults) { defaultValueCache[nodeName] = nodeDefaults = {}; } if (!(prop in nodeDefaults)) { testElement = document.createElement(nodeName); nodeDefaults[prop] = testElement[prop]; } return nodeDefaults[prop]; }, injection: DOMPropertyInjection }; module.exports = DOMProperty; },{"./invariant":112}],9:[function(_dereq_,module,exports){ /** * Copyright 2013-2014 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. * * @providesModule DOMPropertyOperations * @typechecks static-only */ "use strict"; var DOMProperty = _dereq_("./DOMProperty"); var escapeTextForBrowser = _dereq_("./escapeTextForBrowser"); var memoizeStringOnly = _dereq_("./memoizeStringOnly"); var warning = _dereq_("./warning"); function shouldIgnoreValue(name, value) { return value == null || DOMProperty.hasBooleanValue[name] && !value || DOMProperty.hasPositiveNumericValue[name] && (isNaN(value) || value < 1); } var processAttributeNameAndPrefix = memoizeStringOnly(function(name) { return escapeTextForBrowser(name) + '="'; }); if ("production" !== "development") { var reactProps = { children: true, dangerouslySetInnerHTML: true, key: true, ref: true }; var warnedProperties = {}; var warnUnknownProperty = function(name) { if (reactProps[name] || warnedProperties[name]) { return; } warnedProperties[name] = true; var lowerCasedName = name.toLowerCase(); // data-* attributes should be lowercase; suggest the lowercase version var standardName = DOMProperty.isCustomAttribute(lowerCasedName) ? lowerCasedName : DOMProperty.getPossibleStandardName[lowerCasedName]; // For now, only warn when we have a suggested correction. This prevents // logging too much when using transferPropsTo. ("production" !== "development" ? warning( standardName == null, 'Unknown DOM property ' + name + '. Did you mean ' + standardName + '?' ) : null); }; } /** * 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 processAttributeNameAndPrefix(DOMProperty.ID_ATTRIBUTE_NAME) + escapeTextForBrowser(id) + '"'; }, /** * 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) { if (DOMProperty.isStandardName[name]) { if (shouldIgnoreValue(name, value)) { return ''; } var attributeName = DOMProperty.getAttributeName[name]; if (DOMProperty.hasBooleanValue[name]) { return escapeTextForBrowser(attributeName); } return processAttributeNameAndPrefix(attributeName) + escapeTextForBrowser(value) + '"'; } else if (DOMProperty.isCustomAttribute(name)) { if (value == null) { return ''; } return processAttributeNameAndPrefix(name) + escapeTextForBrowser(value) + '"'; } else if ("production" !== "development") { warnUnknownProperty(name); } return null; }, /** * Sets the value for a property on a node. * * @param {DOMElement} node * @param {string} name * @param {*} value */ setValueForProperty: function(node, name, value) { if (DOMProperty.isStandardName[name]) { var mutationMethod = DOMProperty.getMutationMethod[name]; if (mutationMethod) { mutationMethod(node, value); } else if (shouldIgnoreValue(name, value)) { this.deleteValueForProperty(node, name); } else if (DOMProperty.mustUseAttribute[name]) { node.setAttribute(DOMProperty.getAttributeName[name], '' + value); } else { var propName = DOMProperty.getPropertyName[name]; if (!DOMProperty.hasSideEffects[name] || node[propName] !== value) { node[propName] = value; } } } else if (DOMProperty.isCustomAttribute(name)) { if (value == null) { node.removeAttribute(DOMProperty.getAttributeName[name]); } else { node.setAttribute(name, '' + value); } } else if ("production" !== "development") { warnUnknownProperty(name); } }, /** * Deletes the value for a property on a node. * * @param {DOMElement} node * @param {string} name */ deleteValueForProperty: function(node, name) { if (DOMProperty.isStandardName[name]) { var mutationMethod = DOMProperty.getMutationMethod[name]; if (mutationMethod) { mutationMethod(node, undefined); } else if (DOMProperty.mustUseAttribute[name]) { node.removeAttribute(DOMProperty.getAttributeName[name]); } else { var propName = DOMProperty.getPropertyName[name]; var defaultValue = DOMProperty.getDefaultValueForProperty( node.nodeName, propName ); if (!DOMProperty.hasSideEffects[name] || node[propName] !== defaultValue) { node[propName] = defaultValue; } } } else if (DOMProperty.isCustomAttribute(name)) { node.removeAttribute(name); } else if ("production" !== "development") { warnUnknownProperty(name); } } }; module.exports = DOMPropertyOperations; },{"./DOMProperty":8,"./escapeTextForBrowser":98,"./memoizeStringOnly":120,"./warning":134}],10:[function(_dereq_,module,exports){ /** * Copyright 2013-2014 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. * * @providesModule Danger * @typechecks static-only */ /*jslint evil: true, sub: true */ "use strict"; var ExecutionEnvironment = _dereq_("./ExecutionEnvironment"); var createNodesFromMarkup = _dereq_("./createNodesFromMarkup"); var emptyFunction = _dereq_("./emptyFunction"); var getMarkupWrap = _dereq_("./getMarkupWrap"); var invariant = _dereq_("./invariant"); var OPEN_TAG_NAME_EXP = /^(<[^ \/>]+)/; var RESULT_INDEX_ATTR = 'data-danger-index'; /** * Extracts the `nodeName` from a string of markup. * * NOTE: Extracting the `nodeName` does not require a regular expression match * because we make assumptions about React-generated markup (i.e. there are no * spaces surrounding the opening tag and there is at least one attribute). * * @param {string} markup String of markup. * @return {string} Node name of the supplied markup. * @see http://jsperf.com/extract-nodename */ function getNodeName(markup) { return markup.substring(1, markup.indexOf(' ')); } var Danger = { /** * Renders markup into an array of nodes. The markup is expected to render * into a list of root nodes. Also, the length of `resultList` and * `markupList` should be the same. * * @param {array<string>} markupList List of markup strings to render. * @return {array<DOMElement>} List of rendered nodes. * @internal */ dangerouslyRenderMarkup: function(markupList) { ("production" !== "development" ? invariant( ExecutionEnvironment.canUseDOM, 'dangerouslyRenderMarkup(...): Cannot render markup in a Worker ' + 'thread. This is likely a bug in the framework. Please report ' + 'immediately.' ) : invariant(ExecutionEnvironment.canUseDOM)); var nodeName; var markupByNodeName = {}; // Group markup by `nodeName` if a wrap is necessary, else by '*'. for (var i = 0; i < markupList.length; i++) { ("production" !== "development" ? invariant( markupList[i], 'dangerouslyRenderMarkup(...): Missing markup.' ) : invariant(markupList[i])); nodeName = getNodeName(markupList[i]); nodeName = getMarkupWrap(nodeName) ? nodeName : '*'; markupByNodeName[nodeName] = markupByNodeName[nodeName] || []; markupByNodeName[nodeName][i] = markupList[i]; } var resultList = []; var resultListAssignmentCount = 0; for (nodeName in markupByNodeName) { if (!markupByNodeName.hasOwnProperty(nodeName)) { continue; } var markupListByNodeName = markupByNodeName[nodeName]; // This for-in loop skips the holes of the sparse array. The order of // iteration should follow the order of assignment, which happens to match // numerical index order, but we don't rely on that. for (var resultIndex in markupListByNodeName) { if (markupListByNodeName.hasOwnProperty(resultIndex)) { var markup = markupListByNodeName[resultIndex]; // Push the requested markup with an additional RESULT_INDEX_ATTR // attribute. If the markup does not start with a < character, it // will be discarded below (with an appropriate console.error). markupListByNodeName[resultIndex] = markup.replace( OPEN_TAG_NAME_EXP, // This index will be parsed back out below. '$1 ' + RESULT_INDEX_ATTR + '="' + resultIndex + '" ' ); } } // Render each group of markup with similar wrapping `nodeName`. var renderNodes = createNodesFromMarkup( markupListByNodeName.join(''), emptyFunction // Do nothing special with <script> tags. ); for (i = 0; i < renderNodes.length; ++i) { var renderNode = renderNodes[i]; if (renderNode.hasAttribute && renderNode.hasAttribute(RESULT_INDEX_ATTR)) { resultIndex = +renderNode.getAttribute(RESULT_INDEX_ATTR); renderNode.removeAttribute(RESULT_INDEX_ATTR); ("production" !== "development" ? invariant( !resultList.hasOwnProperty(resultIndex), 'Danger: Assigning to an already-occupied result index.' ) : invariant(!resultList.hasOwnProperty(resultIndex))); resultList[resultIndex] = renderNode; // This should match resultList.length and markupList.length when // we're done. resultListAssignmentCount += 1; } else if ("production" !== "development") { console.error( "Danger: Discarding unexpected node:", renderNode ); } } } // Although resultList was populated out of order, it should now be a dense // array. ("production" !== "development" ? invariant( resultListAssignmentCount === resultList.length, 'Danger: Did not assign to every index of resultList.' ) : invariant(resultListAssignmentCount === resultList.length)); ("production" !== "development" ? invariant( resultList.length === markupList.length, 'Danger: Expected markup to render %s nodes, but rendered %s.', markupList.length, resultList.length ) : invariant(resultList.length === markupList.length)); return resultList; }, /** * 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) { ("production" !== "development" ? invariant( ExecutionEnvironment.canUseDOM, 'dangerouslyReplaceNodeWithMarkup(...): Cannot render markup in a ' + 'worker thread. This is likely a bug in the framework. Please report ' + 'immediately.' ) : invariant(ExecutionEnvironment.canUseDOM)); ("production" !== "development" ? invariant(markup, 'dangerouslyReplaceNodeWithMarkup(...): Missing markup.') : invariant(markup)); ("production" !== "development" ? invariant( oldChild.tagName.toLowerCase() !== 'html', '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 renderComponentToString().' ) : invariant(oldChild.tagName.toLowerCase() !== 'html')); var newChild = createNodesFromMarkup(markup, emptyFunction)[0]; oldChild.parentNode.replaceChild(newChild, oldChild); } }; module.exports = Danger; },{"./ExecutionEnvironment":20,"./createNodesFromMarkup":93,"./emptyFunction":96,"./getMarkupWrap":105,"./invariant":112}],11:[function(_dereq_,module,exports){ /** * Copyright 2013-2014 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. * * @providesModule DefaultDOMPropertyConfig */ /*jslint bitwise: true*/ "use strict"; var DOMProperty = _dereq_("./DOMProperty"); var MUST_USE_ATTRIBUTE = DOMProperty.injection.MUST_USE_ATTRIBUTE; var MUST_USE_PROPERTY = DOMProperty.injection.MUST_USE_PROPERTY; var HAS_BOOLEAN_VALUE = DOMProperty.injection.HAS_BOOLEAN_VALUE; var HAS_SIDE_EFFECTS = DOMProperty.injection.HAS_SIDE_EFFECTS; var HAS_POSITIVE_NUMERIC_VALUE = DOMProperty.injection.HAS_POSITIVE_NUMERIC_VALUE; var DefaultDOMPropertyConfig = { isCustomAttribute: RegExp.prototype.test.bind( /^(data|aria)-[a-z_][a-z\d_.\-]*$/ ), Properties: { /** * Standard Properties */ accept: null, accessKey: null, action: null, allowFullScreen: MUST_USE_ATTRIBUTE | HAS_BOOLEAN_VALUE, allowTransparency: MUST_USE_ATTRIBUTE, alt: null, async: HAS_BOOLEAN_VALUE, autoComplete: null, // autoFocus is polyfilled/normalized by AutoFocusMixin // autoFocus: HAS_BOOLEAN_VALUE, autoPlay: HAS_BOOLEAN_VALUE, cellPadding: null, cellSpacing: null, charSet: MUST_USE_ATTRIBUTE, checked: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE, className: MUST_USE_PROPERTY, cols: MUST_USE_ATTRIBUTE | HAS_POSITIVE_NUMERIC_VALUE, colSpan: null, content: null, contentEditable: null, contextMenu: MUST_USE_ATTRIBUTE, controls: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE, crossOrigin: null, data: null, // For `<object />` acts as `src`. dateTime: MUST_USE_ATTRIBUTE, defer: HAS_BOOLEAN_VALUE, dir: null, disabled: MUST_USE_ATTRIBUTE | HAS_BOOLEAN_VALUE, download: null, draggable: null, encType: null, form: MUST_USE_ATTRIBUTE, formNoValidate: HAS_BOOLEAN_VALUE, frameBorder: MUST_USE_ATTRIBUTE, height: MUST_USE_ATTRIBUTE, hidden: MUST_USE_ATTRIBUTE | HAS_BOOLEAN_VALUE, href: null, hrefLang: null, htmlFor: null, httpEquiv: null, icon: null, id: MUST_USE_PROPERTY, label: null, lang: null, list: null, loop: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE, max: null, maxLength: MUST_USE_ATTRIBUTE, mediaGroup: null, method: null, min: null, multiple: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE, muted: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE, name: null, noValidate: HAS_BOOLEAN_VALUE, pattern: null, placeholder: null, poster: null, preload: null, radioGroup: null, readOnly: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE, rel: null, required: HAS_BOOLEAN_VALUE, role: MUST_USE_ATTRIBUTE, rows: MUST_USE_ATTRIBUTE | HAS_POSITIVE_NUMERIC_VALUE, rowSpan: null, sandbox: null, scope: null, scrollLeft: MUST_USE_PROPERTY, scrollTop: MUST_USE_PROPERTY, seamless: MUST_USE_ATTRIBUTE | HAS_BOOLEAN_VALUE, selected: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE, size: MUST_USE_ATTRIBUTE | HAS_POSITIVE_NUMERIC_VALUE, span: HAS_POSITIVE_NUMERIC_VALUE, spellCheck: null, src: null, srcDoc: MUST_USE_PROPERTY, srcSet: null, step: null, style: null, tabIndex: null, target: null, title: null, type: null, value: MUST_USE_PROPERTY | HAS_SIDE_EFFECTS, width: MUST_USE_ATTRIBUTE, wmode: MUST_USE_ATTRIBUTE, /** * Non-standard Properties */ autoCapitalize: null, // Supported in Mobile Safari for keyboard hints autoCorrect: null, // Supported in Mobile Safari for keyboard hints property: null, // Supports OG in meta tags /** * SVG Properties */ cx: MUST_USE_ATTRIBUTE, cy: MUST_USE_ATTRIBUTE, d: MUST_USE_ATTRIBUTE, fill: MUST_USE_ATTRIBUTE, fx: MUST_USE_ATTRIBUTE, fy: MUST_USE_ATTRIBUTE, gradientTransform: MUST_USE_ATTRIBUTE, gradientUnits: MUST_USE_ATTRIBUTE, offset: MUST_USE_ATTRIBUTE, points: MUST_USE_ATTRIBUTE, r: MUST_USE_ATTRIBUTE, rx: MUST_USE_ATTRIBUTE, ry: MUST_USE_ATTRIBUTE, spreadMethod: MUST_USE_ATTRIBUTE, stopColor: MUST_USE_ATTRIBUTE, stopOpacity: MUST_USE_ATTRIBUTE, stroke: MUST_USE_ATTRIBUTE, strokeLinecap: MUST_USE_ATTRIBUTE, strokeWidth: MUST_USE_ATTRIBUTE, textAnchor: MUST_USE_ATTRIBUTE, transform: MUST_USE_ATTRIBUTE, version: MUST_USE_ATTRIBUTE, viewBox: MUST_USE_ATTRIBUTE, x1: MUST_USE_ATTRIBUTE, x2: MUST_USE_ATTRIBUTE, x: MUST_USE_ATTRIBUTE, y1: MUST_USE_ATTRIBUTE, y2: MUST_USE_ATTRIBUTE, y: MUST_USE_ATTRIBUTE }, DOMAttributeNames: { className: 'class', gradientTransform: 'gradientTransform', gradientUnits: 'gradientUnits', htmlFor: 'for', spreadMethod: 'spreadMethod', stopColor: 'stop-color', stopOpacity: 'stop-opacity', strokeLinecap: 'stroke-linecap', strokeWidth: 'stroke-width', textAnchor: 'text-anchor', viewBox: 'viewBox' }, DOMPropertyNames: { autoCapitalize: 'autocapitalize', autoComplete: 'autocomplete', autoCorrect: 'autocorrect', autoFocus: 'autofocus', autoPlay: 'autoplay', encType: 'enctype', hrefLang: 'hreflang', radioGroup: 'radiogroup', spellCheck: 'spellcheck', srcDoc: 'srcdoc', srcSet: 'srcset' } }; module.exports = DefaultDOMPropertyConfig; },{"./DOMProperty":8}],12:[function(_dereq_,module,exports){ /** * Copyright 2013-2014 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. * * @providesModule DefaultEventPluginOrder */ "use strict"; var keyOf = _dereq_("./keyOf"); /** * 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 DefaultEventPluginOrder = [ keyOf({ResponderEventPlugin: null}), keyOf({SimpleEventPlugin: null}), keyOf({TapEventPlugin: null}), keyOf({EnterLeaveEventPlugin: null}), keyOf({ChangeEventPlugin: null}), keyOf({SelectEventPlugin: null}), keyOf({CompositionEventPlugin: null}), keyOf({AnalyticsEventPlugin: null}), keyOf({MobileSafariClickEventPlugin: null}) ]; module.exports = DefaultEventPluginOrder; },{"./keyOf":119}],13:[function(_dereq_,module,exports){ /** * Copyright 2013-2014 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. * * @providesModule EnterLeaveEventPlugin * @typechecks static-only */ "use strict"; var EventConstants = _dereq_("./EventConstants"); var EventPropagators = _dereq_("./EventPropagators"); var SyntheticMouseEvent = _dereq_("./SyntheticMouseEvent"); var ReactMount = _dereq_("./ReactMount"); var keyOf = _dereq_("./keyOf"); var topLevelTypes = EventConstants.topLevelTypes; var getFirstReactDOM = ReactMount.getFirstReactDOM; var eventTypes = { mouseEnter: { registrationName: keyOf({onMouseEnter: null}), dependencies: [ topLevelTypes.topMouseOut, topLevelTypes.topMouseOver ] }, mouseLeave: { registrationName: keyOf({onMouseLeave: null}), dependencies: [ topLevelTypes.topMouseOut, topLevelTypes.topMouseOver ] } }; var extractedEvents = [null, null]; 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. * * @param {string} topLevelType Record from `EventConstants`. * @param {DOMEventTarget} topLevelTarget The listening component root node. * @param {string} topLevelTargetID ID of `topLevelTarget`. * @param {object} nativeEvent Native browser event. * @return {*} An accumulation of synthetic events. * @see {EventPluginHub.extractEvents} */ extractEvents: function( topLevelType, topLevelTarget, topLevelTargetID, nativeEvent) { if (topLevelType === topLevelTypes.topMouseOver && (nativeEvent.relatedTarget || nativeEvent.fromElement)) { return null; } if (topLevelType !== topLevelTypes.topMouseOut && topLevelType !== topLevelTypes.topMouseOver) { // Must not be a mouse in or mouse out - ignoring. return null; } var win; if (topLevelTarget.window === topLevelTarget) { // `topLevelTarget` is probably a window object. win = topLevelTarget; } else { // TODO: Figure out why `ownerDocument` is sometimes undefined in IE8. var doc = topLevelTarget.ownerDocument; if (doc) { win = doc.defaultView || doc.parentWindow; } else { win = window; } } var from, to; if (topLevelType === topLevelTypes.topMouseOut) { from = topLevelTarget; to = getFirstReactDOM(nativeEvent.relatedTarget || nativeEvent.toElement) || win; } else { from = win; to = topLevelTarget; } if (from === to) { // Nothing pertains to our managed components. return null; } var fromID = from ? ReactMount.getID(from) : ''; var toID = to ? ReactMount.getID(to) : ''; var leave = SyntheticMouseEvent.getPooled( eventTypes.mouseLeave, fromID, nativeEvent ); leave.type = 'mouseleave'; leave.target = from; leave.relatedTarget = to; var enter = SyntheticMouseEvent.getPooled( eventTypes.mouseEnter, toID, nativeEvent ); enter.type = 'mouseenter'; enter.target = to; enter.relatedTarget = from; EventPropagators.accumulateEnterLeaveDispatches(leave, enter, fromID, toID); extractedEvents[0] = leave; extractedEvents[1] = enter; return extractedEvents; } }; module.exports = EnterLeaveEventPlugin; },{"./EventConstants":14,"./EventPropagators":19,"./ReactMount":55,"./SyntheticMouseEvent":81,"./keyOf":119}],14:[function(_dereq_,module,exports){ /** * Copyright 2013-2014 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. * * @providesModule EventConstants */ "use strict"; var keyMirror = _dereq_("./keyMirror"); var PropagationPhases = keyMirror({bubbled: null, captured: null}); /** * Types of raw signals from the browser caught at the top level. */ var topLevelTypes = keyMirror({ topBlur: null, topChange: null, topClick: null, topCompositionEnd: null, topCompositionStart: null, topCompositionUpdate: null, topContextMenu: null, topCopy: null, topCut: null, topDoubleClick: null, topDrag: null, topDragEnd: null, topDragEnter: null, topDragExit: null, topDragLeave: null, topDragOver: null, topDragStart: null, topDrop: null, topError: null, topFocus: null, topInput: null, topKeyDown: null, topKeyPress: null, topKeyUp: null, topLoad: null, topMouseDown: null, topMouseMove: null, topMouseOut: null, topMouseOver: null, topMouseUp: null, topPaste: null, topReset: null, topScroll: null, topSelectionChange: null, topSubmit: null, topTouchCancel: null, topTouchEnd: null, topTouchMove: null, topTouchStart: null, topWheel: null }); var EventConstants = { topLevelTypes: topLevelTypes, PropagationPhases: PropagationPhases }; module.exports = EventConstants; },{"./keyMirror":118}],15:[function(_dereq_,module,exports){ /** * @providesModule EventListener */ var emptyFunction = _dereq_("./emptyFunction"); /** * 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(target, eventType, callback) { if (target.addEventListener) { target.addEventListener(eventType, callback, false); return { remove: function() { target.removeEventListener(eventType, callback, false); } }; } else if (target.attachEvent) { target.attachEvent('on' + eventType, callback); return { remove: function() { target.detachEvent(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(target, eventType, callback) { if (!target.addEventListener) { if ("production" !== "development") { 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 }; } else { target.addEventListener(eventType, callback, true); return { remove: function() { target.removeEventListener(eventType, callback, true); } }; } } }; module.exports = EventListener; },{"./emptyFunction":96}],16:[function(_dereq_,module,exports){ /** * Copyright 2013-2014 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. * * @providesModule EventPluginHub */ "use strict"; var EventPluginRegistry = _dereq_("./EventPluginRegistry"); var EventPluginUtils = _dereq_("./EventPluginUtils"); var ExecutionEnvironment = _dereq_("./ExecutionEnvironment"); var accumulate = _dereq_("./accumulate"); var forEachAccumulated = _dereq_("./forEachAccumulated"); var invariant = _dereq_("./invariant"); var isEventSupported = _dereq_("./isEventSupported"); var monitorCodeUse = _dereq_("./monitorCodeUse"); /** * Internal store for event listeners */ var listenerBank = {}; /** * 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. * @private */ var executeDispatchesAndRelease = function(event) { if (event) { var executeDispatch = EventPluginUtils.executeDispatch; // Plugins can provide custom behavior when dispatching events. var PluginModule = EventPluginRegistry.getPluginModuleForEvent(event); if (PluginModule && PluginModule.executeDispatch) { executeDispatch = PluginModule.executeDispatch; } EventPluginUtils.executeDispatchesInOrder(event, executeDispatch); if (!event.isPersistent()) { event.constructor.release(event); } } }; /** * - `InstanceHandle`: [required] Module that performs logical traversals of DOM * hierarchy given ids of the logical DOM elements involved. */ var InstanceHandle = null; function validateInstanceHandle() { var invalid = !InstanceHandle|| !InstanceHandle.traverseTwoPhase || !InstanceHandle.traverseEnterLeave; if (invalid) { throw new Error('InstanceHandle not injected before use!'); } } /** * 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 {object} InjectedMount * @public */ injectMount: EventPluginUtils.injection.injectMount, /** * @param {object} InjectedInstanceHandle * @public */ injectInstanceHandle: function(InjectedInstanceHandle) { InstanceHandle = InjectedInstanceHandle; if ("production" !== "development") { validateInstanceHandle(); } }, getInstanceHandle: function() { if ("production" !== "development") { validateInstanceHandle(); } return InstanceHandle; }, /** * @param {array} InjectedEventPluginOrder * @public */ injectEventPluginOrder: EventPluginRegistry.injectEventPluginOrder, /** * @param {object} injectedNamesToPlugins Map from names to plugin modules. */ injectEventPluginsByName: EventPluginRegistry.injectEventPluginsByName }, eventNameDispatchConfigs: EventPluginRegistry.eventNameDispatchConfigs, registrationNameModules: EventPluginRegistry.registrationNameModules, /** * Stores `listener` at `listenerBank[registrationName][id]`. Is idempotent. * * @param {string} id ID of the DOM element. * @param {string} registrationName Name of listener (e.g. `onClick`). * @param {?function} listener The callback to store. */ putListener: function(id, registrationName, listener) { ("production" !== "development" ? invariant( ExecutionEnvironment.canUseDOM, 'Cannot call putListener() in a non-DOM environment.' ) : invariant(ExecutionEnvironment.canUseDOM)); ("production" !== "development" ? invariant( !listener || typeof listener === 'function', 'Expected %s listener to be a function, instead got type %s', registrationName, typeof listener ) : invariant(!listener || typeof listener === 'function')); if ("production" !== "development") { // IE8 has no API for event capturing and the `onScroll` event doesn't // bubble. if (registrationName === 'onScroll' && !isEventSupported('scroll', true)) { monitorCodeUse('react_no_scroll_event'); console.warn('This browser doesn\'t support the `onScroll` event'); } } var bankForRegistrationName = listenerBank[registrationName] || (listenerBank[registrationName] = {}); bankForRegistrationName[id] = listener; }, /** * @param {string} id ID of the DOM element. * @param {string} registrationName Name of listener (e.g. `onClick`). * @return {?function} The stored callback. */ getListener: function(id, registrationName) { var bankForRegistrationName = listenerBank[registrationName]; return bankForRegistrationName && bankForRegistrationName[id]; }, /** * Deletes a listener from the registration bank. * * @param {string} id ID of the DOM element. * @param {string} registrationName Name of listener (e.g. `onClick`). */ deleteListener: function(id, registrationName) { var bankForRegistrationName = listenerBank[registrationName]; if (bankForRegistrationName) { delete bankForRegistrationName[id]; } }, /** * Deletes all listeners for the DOM element with the supplied ID. * * @param {string} id ID of the DOM element. */ deleteAllListeners: function(id) { for (var registrationName in listenerBank) { delete listenerBank[registrationName][id]; } }, /** * Allows registered plugins an opportunity to extract events from top-level * native browser events. * * @param {string} topLevelType Record from `EventConstants`. * @param {DOMEventTarget} topLevelTarget The listening component root node. * @param {string} topLevelTargetID ID of `topLevelTarget`. * @param {object} nativeEvent Native browser event. * @return {*} An accumulation of synthetic events. * @internal */ extractEvents: function( topLevelType, topLevelTarget, topLevelTargetID, nativeEvent) { var events; var plugins = EventPluginRegistry.plugins; for (var i = 0, l = plugins.length; i < l; i++) { // Not every plugin in the ordering may be loaded at runtime. var possiblePlugin = plugins[i]; if (possiblePlugin) { var extractedEvents = possiblePlugin.extractEvents( topLevelType, topLevelTarget, topLevelTargetID, nativeEvent ); if (extractedEvents) { events = accumulate(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 = accumulate(eventQueue, events); } }, /** * Dispatches all synthetic events on the event queue. * * @internal */ processEventQueue: function() { // Set `eventQueue` to null before processing it so that we can tell if more // events get enqueued while processing. var processingEventQueue = eventQueue; eventQueue = null; forEachAccumulated(processingEventQueue, executeDispatchesAndRelease); ("production" !== "development" ? invariant( !eventQueue, 'processEventQueue(): Additional events were enqueued while processing ' + 'an event queue. Support for this has not yet been implemented.' ) : invariant(!eventQueue)); }, /** * These are needed for tests only. Do not use! */ __purge: function() { listenerBank = {}; }, __getListenerBank: function() { return listenerBank; } }; module.exports = EventPluginHub; },{"./EventPluginRegistry":17,"./EventPluginUtils":18,"./ExecutionEnvironment":20,"./accumulate":87,"./forEachAccumulated":101,"./invariant":112,"./isEventSupported":113,"./monitorCodeUse":125}],17:[function(_dereq_,module,exports){ /** * Copyright 2013-2014 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. * * @providesModule EventPluginRegistry * @typechecks static-only */ "use strict"; var invariant = _dereq_("./invariant"); /** * 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); ("production" !== "development" ? invariant( pluginIndex > -1, 'EventPluginRegistry: Cannot inject event plugins that do not exist in ' + 'the plugin ordering, `%s`.', pluginName ) : invariant(pluginIndex > -1)); if (EventPluginRegistry.plugins[pluginIndex]) { continue; } ("production" !== "development" ? invariant( PluginModule.extractEvents, 'EventPluginRegistry: Event plugins must implement an `extractEvents` ' + 'method, but `%s` does not.', pluginName ) : invariant(PluginModule.extractEvents)); EventPluginRegistry.plugins[pluginIndex] = PluginModule; var publishedEvents = PluginModule.eventTypes; for (var eventName in publishedEvents) { ("production" !== "development" ? invariant( publishEventForPlugin( publishedEvents[eventName], PluginModule, eventName ), 'EventPluginRegistry: Failed to publish event `%s` for plugin `%s`.', eventName, pluginName ) : invariant(publishEventForPlugin( publishedEvents[eventName], PluginModule, eventName ))); } } } /** * 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) { ("production" !== "development" ? invariant( !EventPluginRegistry.eventNameDispatchConfigs[eventName], 'EventPluginHub: More than one plugin attempted to publish the same ' + 'event name, `%s`.', eventName ) : invariant(!EventPluginRegistry.eventNameDispatchConfigs[eventName])); 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 and * can be used with `EventPluginHub.putListener` to register listeners. * * @param {string} registrationName Registration name to add. * @param {object} PluginModule Plugin publishing the event. * @private */ function publishRegistrationName(registrationName, PluginModule, eventName) { ("production" !== "development" ? invariant( !EventPluginRegistry.registrationNameModules[registrationName], 'EventPluginHub: More than one plugin attempted to publish the same ' + 'registration name, `%s`.', registrationName ) : invariant(!EventPluginRegistry.registrationNameModules[registrationName])); EventPluginRegistry.registrationNameModules[registrationName] = PluginModule; EventPluginRegistry.registrationNameDependencies[registrationName] = PluginModule.eventTypes[eventName].dependencies; } /** * 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: {}, /** * 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) { ("production" !== "development" ? invariant( !EventPluginOrder, 'EventPluginRegistry: Cannot inject event plugin ordering more than once.' ) : invariant(!EventPluginOrder)); // 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[pluginName] !== PluginModule) { ("production" !== "development" ? invariant( !namesToPlugins[pluginName], 'EventPluginRegistry: Cannot inject two different event plugins ' + 'using the same name, `%s`.', pluginName ) : invariant(!namesToPlugins[pluginName])); 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; } for (var phase in dispatchConfig.phasedRegistrationNames) { if (!dispatchConfig.phasedRegistrationNames.hasOwnProperty(phase)) { continue; } var PluginModule = EventPluginRegistry.registrationNameModules[ dispatchConfig.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]; } } } }; module.exports = EventPluginRegistry; },{"./invariant":112}],18:[function(_dereq_,module,exports){ /** * Copyright 2013-2014 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. * * @providesModule EventPluginUtils */ "use strict"; var EventConstants = _dereq_("./EventConstants"); var invariant = _dereq_("./invariant"); /** * Injected dependencies: */ /** * - `Mount`: [required] Module that can convert between React dom IDs and * actual node references. */ var injection = { Mount: null, injectMount: function(InjectedMount) { injection.Mount = InjectedMount; if ("production" !== "development") { ("production" !== "development" ? invariant( InjectedMount && InjectedMount.getNode, 'EventPluginUtils.injection.injectMount(...): Injected Mount module ' + 'is missing getNode.' ) : invariant(InjectedMount && InjectedMount.getNode)); } } }; var topLevelTypes = EventConstants.topLevelTypes; function isEndish(topLevelType) { return topLevelType === topLevelTypes.topMouseUp || topLevelType === topLevelTypes.topTouchEnd || topLevelType === topLevelTypes.topTouchCancel; } function isMoveish(topLevelType) { return topLevelType === topLevelTypes.topMouseMove || topLevelType === topLevelTypes.topTouchMove; } function isStartish(topLevelType) { return topLevelType === topLevelTypes.topMouseDown || topLevelType === topLevelTypes.topTouchStart; } var validateEventDispatches; if ("production" !== "development") { validateEventDispatches = function(event) { var dispatchListeners = event._dispatchListeners; var dispatchIDs = event._dispatchIDs; var listenersIsArr = Array.isArray(dispatchListeners); var idsIsArr = Array.isArray(dispatchIDs); var IDsLen = idsIsArr ? dispatchIDs.length : dispatchIDs ? 1 : 0; var listenersLen = listenersIsArr ? dispatchListeners.length : dispatchListeners ? 1 : 0; ("production" !== "development" ? invariant( idsIsArr === listenersIsArr && IDsLen === listenersLen, 'EventPluginUtils: Invalid `event`.' ) : invariant(idsIsArr === listenersIsArr && IDsLen === listenersLen)); }; } /** * Invokes `cb(event, listener, id)`. Avoids using call if no scope is * provided. The `(listener,id)` pair effectively forms the "dispatch" but are * kept separate to conserve memory. */ function forEachEventDispatch(event, cb) { var dispatchListeners = event._dispatchListeners; var dispatchIDs = event._dispatchIDs; if ("production" !== "development") { validateEventDispatches(event); } if (Array.isArray(dispatchListeners)) { for (var i = 0; i < dispatchListeners.length; i++) { if (event.isPropagationStopped()) { break; } // Listeners and IDs are two parallel arrays that are always in sync. cb(event, dispatchListeners[i], dispatchIDs[i]); } } else if (dispatchListeners) { cb(event, dispatchListeners, dispatchIDs); } } /** * Default implementation of PluginModule.executeDispatch(). * @param {SyntheticEvent} SyntheticEvent to handle * @param {function} Application-level callback * @param {string} domID DOM id to pass to the callback. */ function executeDispatch(event, listener, domID) { event.currentTarget = injection.Mount.getNode(domID); var returnValue = listener(event, domID); event.currentTarget = null; return returnValue; } /** * Standard/simple iteration through an event's collected dispatches. */ function executeDispatchesInOrder(event, executeDispatch) { forEachEventDispatch(event, executeDispatch); event._dispatchListeners = null; event._dispatchIDs = null; } /** * Standard/simple iteration through an event's collected dispatches, but stops * at the first dispatch execution returning true, and returns that id. * * @return id of the first dispatch execution who's listener returns true, or * null if no listener returned true. */ function executeDispatchesInOrderStopAtTrue(event) { var dispatchListeners = event._dispatchListeners; var dispatchIDs = event._dispatchIDs; if ("production" !== "development") { validateEventDispatches(event); } if (Array.isArray(dispatchListeners)) { for (var i = 0; i < dispatchListeners.length; i++) { if (event.isPropagationStopped()) { break; } // Listeners and IDs are two parallel arrays that are always in sync. if (dispatchListeners[i](event, dispatchIDs[i])) { return dispatchIDs[i]; } } } else if (dispatchListeners) { if (dispatchListeners(event, dispatchIDs)) { return dispatchIDs; } } return null; } /** * 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 ("production" !== "development") { validateEventDispatches(event); } var dispatchListener = event._dispatchListeners; var dispatchID = event._dispatchIDs; ("production" !== "development" ? invariant( !Array.isArray(dispatchListener), 'executeDirectDispatch(...): Invalid `event`.' ) : invariant(!Array.isArray(dispatchListener))); var res = dispatchListener ? dispatchListener(event, dispatchID) : null; event._dispatchListeners = null; event._dispatchIDs = null; return res; } /** * @param {SyntheticEvent} event * @return {bool} 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, executeDispatch: executeDispatch, executeDispatchesInOrder: executeDispatchesInOrder, executeDispatchesInOrderStopAtTrue: executeDispatchesInOrderStopAtTrue, hasDispatches: hasDispatches, injection: injection, useTouchEvents: false }; module.exports = EventPluginUtils; },{"./EventConstants":14,"./invariant":112}],19:[function(_dereq_,module,exports){ /** * Copyright 2013-2014 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. * * @providesModule EventPropagators */ "use strict"; var EventConstants = _dereq_("./EventConstants"); var EventPluginHub = _dereq_("./EventPluginHub"); var accumulate = _dereq_("./accumulate"); var forEachAccumulated = _dereq_("./forEachAccumulated"); var PropagationPhases = EventConstants.PropagationPhases; 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(id, event, propagationPhase) { var registrationName = event.dispatchConfig.phasedRegistrationNames[propagationPhase]; return getListener(id, 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(domID, upwards, event) { if ("production" !== "development") { if (!domID) { throw new Error('Dispatching id must not be null'); } } var phase = upwards ? PropagationPhases.bubbled : PropagationPhases.captured; var listener = listenerAtPhase(domID, event, phase); if (listener) { event._dispatchListeners = accumulate(event._dispatchListeners, listener); event._dispatchIDs = accumulate(event._dispatchIDs, domID); } } /** * 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 can not 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) { EventPluginHub.injection.getInstanceHandle().traverseTwoPhase( event.dispatchMarker, 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(id, ignoredDirection, event) { if (event && event.dispatchConfig.registrationName) { var registrationName = event.dispatchConfig.registrationName; var listener = getListener(id, registrationName); if (listener) { event._dispatchListeners = accumulate(event._dispatchListeners, listener); event._dispatchIDs = accumulate(event._dispatchIDs, id); } } } /** * Accumulates dispatches on an `SyntheticEvent`, but only for the * `dispatchMarker`. * @param {SyntheticEvent} event */ function accumulateDirectDispatchesSingle(event) { if (event && event.dispatchConfig.registrationName) { accumulateDispatches(event.dispatchMarker, null, event); } } function accumulateTwoPhaseDispatches(events) { forEachAccumulated(events, accumulateTwoPhaseDispatchesSingle); } function accumulateEnterLeaveDispatches(leave, enter, fromID, toID) { EventPluginHub.injection.getInstanceHandle().traverseEnterLeave( fromID, toID, 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, accumulateDirectDispatches: accumulateDirectDispatches, accumulateEnterLeaveDispatches: accumulateEnterLeaveDispatches }; module.exports = EventPropagators; },{"./EventConstants":14,"./EventPluginHub":16,"./accumulate":87,"./forEachAccumulated":101}],20:[function(_dereq_,module,exports){ /** * Copyright 2013-2014 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. * * @providesModule ExecutionEnvironment */ /*jslint evil: true */ "use strict"; var canUseDOM = typeof window !== 'undefined'; /** * 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), isInWorker: !canUseDOM // For now, this is true - might change in the future. }; module.exports = ExecutionEnvironment; },{}],21:[function(_dereq_,module,exports){ /** * Copyright 2013-2014 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. * * @providesModule LinkedValueUtils * @typechecks static-only */ "use strict"; var ReactPropTypes = _dereq_("./ReactPropTypes"); var invariant = _dereq_("./invariant"); var warning = _dereq_("./warning"); var hasReadOnlyValue = { 'button': true, 'checkbox': true, 'image': true, 'hidden': true, 'radio': true, 'reset': true, 'submit': true }; function _assertSingleLink(input) { ("production" !== "development" ? invariant( input.props.checkedLink == null || input.props.valueLink == null, 'Cannot provide a checkedLink and a valueLink. If you want to use ' + 'checkedLink, you probably don\'t want to use valueLink and vice versa.' ) : invariant(input.props.checkedLink == null || input.props.valueLink == null)); } function _assertValueLink(input) { _assertSingleLink(input); ("production" !== "development" ? invariant( input.props.value == null && input.props.onChange == null, 'Cannot provide a valueLink and a value or onChange event. If you want ' + 'to use value or onChange, you probably don\'t want to use valueLink.' ) : invariant(input.props.value == null && input.props.onChange == null)); } function _assertCheckedLink(input) { _assertSingleLink(input); ("production" !== "development" ? invariant( input.props.checked == null && input.props.onChange == null, 'Cannot provide a checkedLink and a checked property or onChange event. ' + 'If you want to use checked or onChange, you probably don\'t want to ' + 'use checkedLink' ) : invariant(input.props.checked == null && input.props.onChange == null)); } /** * @param {SyntheticEvent} e change event to handle */ function _handleLinkedValueChange(e) { /*jshint validthis:true */ this.props.valueLink.requestChange(e.target.value); } /** * @param {SyntheticEvent} e change event to handle */ function _handleLinkedCheckChange(e) { /*jshint validthis:true */ this.props.checkedLink.requestChange(e.target.checked); } /** * Provide a linked `value` attribute for controlled forms. You should not use * this outside of the ReactDOM controlled form components. */ var LinkedValueUtils = { Mixin: { propTypes: { value: function(props, propName, componentName) { if ("production" !== "development") { ("production" !== "development" ? warning( !props[propName] || hasReadOnlyValue[props.type] || props.onChange || props.readOnly || props.disabled, '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`.' ) : null); } }, checked: function(props, propName, componentName) { if ("production" !== "development") { ("production" !== "development" ? warning( !props[propName] || props.onChange || props.readOnly || props.disabled, '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`.' ) : null); } }, onChange: ReactPropTypes.func } }, /** * @param {ReactComponent} input Form component * @return {*} current value of the input either from value prop or link. */ getValue: function(input) { if (input.props.valueLink) { _assertValueLink(input); return input.props.valueLink.value; } return input.props.value; }, /** * @param {ReactComponent} input Form component * @return {*} current checked status of the input either from checked prop * or link. */ getChecked: function(input) { if (input.props.checkedLink) { _assertCheckedLink(input); return input.props.checkedLink.value; } return input.props.checked; }, /** * @param {ReactComponent} input Form component * @return {function} change callback either from onChange prop or link. */ getOnChange: function(input) { if (input.props.valueLink) { _assertValueLink(input); return _handleLinkedValueChange; } else if (input.props.checkedLink) { _assertCheckedLink(input); return _handleLinkedCheckChange; } return input.props.onChange; } }; module.exports = LinkedValueUtils; },{"./ReactPropTypes":64,"./invariant":112,"./warning":134}],22:[function(_dereq_,module,exports){ /** * Copyright 2013-2014 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. * * @providesModule MobileSafariClickEventPlugin * @typechecks static-only */ "use strict"; var EventConstants = _dereq_("./EventConstants"); var emptyFunction = _dereq_("./emptyFunction"); var topLevelTypes = EventConstants.topLevelTypes; /** * 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. * * This particular plugin works around the bug by attaching an empty click * listener on `touchstart` (which does fire on every element). */ var MobileSafariClickEventPlugin = { eventTypes: null, /** * @param {string} topLevelType Record from `EventConstants`. * @param {DOMEventTarget} topLevelTarget The listening component root node. * @param {string} topLevelTargetID ID of `topLevelTarget`. * @param {object} nativeEvent Native browser event. * @return {*} An accumulation of synthetic events. * @see {EventPluginHub.extractEvents} */ extractEvents: function( topLevelType, topLevelTarget, topLevelTargetID, nativeEvent) { if (topLevelType === topLevelTypes.topTouchStart) { var target = nativeEvent.target; if (target && !target.onclick) { target.onclick = emptyFunction; } } } }; module.exports = MobileSafariClickEventPlugin; },{"./EventConstants":14,"./emptyFunction":96}],23:[function(_dereq_,module,exports){ /** * Copyright 2013-2014 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. * * @providesModule PooledClass */ "use strict"; var invariant = _dereq_("./invariant"); /** * 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 fiveArgumentPooler = function(a1, a2, a3, a4, a5) { var Klass = this; if (Klass.instancePool.length) { var instance = Klass.instancePool.pop(); Klass.call(instance, a1, a2, a3, a4, a5); return instance; } else { return new Klass(a1, a2, a3, a4, a5); } }; var standardReleaser = function(instance) { var Klass = this; ("production" !== "development" ? invariant( instance instanceof Klass, 'Trying to release an instance into a pool of a different type.' ) : invariant(instance instanceof Klass)); if (instance.destructor) { 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 (optional). * * @param {Function} CopyConstructor Constructor that can be used to reset. * @param {Function} pooler Customizable pooler. */ var addPoolingTo = function(CopyConstructor, pooler) { 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, fiveArgumentPooler: fiveArgumentPooler }; module.exports = PooledClass; },{"./invariant":112}],24:[function(_dereq_,module,exports){ /** * Copyright 2013-2014 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. * * @providesModule React */ "use strict"; var DOMPropertyOperations = _dereq_("./DOMPropertyOperations"); var EventPluginUtils = _dereq_("./EventPluginUtils"); var ReactChildren = _dereq_("./ReactChildren"); var ReactComponent = _dereq_("./ReactComponent"); var ReactCompositeComponent = _dereq_("./ReactCompositeComponent"); var ReactContext = _dereq_("./ReactContext"); var ReactCurrentOwner = _dereq_("./ReactCurrentOwner"); var ReactDOM = _dereq_("./ReactDOM"); var ReactDOMComponent = _dereq_("./ReactDOMComponent"); var ReactDefaultInjection = _dereq_("./ReactDefaultInjection"); var ReactInstanceHandles = _dereq_("./ReactInstanceHandles"); var ReactMount = _dereq_("./ReactMount"); var ReactMultiChild = _dereq_("./ReactMultiChild"); var ReactPerf = _dereq_("./ReactPerf"); var ReactPropTypes = _dereq_("./ReactPropTypes"); var ReactServerRendering = _dereq_("./ReactServerRendering"); var ReactTextComponent = _dereq_("./ReactTextComponent"); var onlyChild = _dereq_("./onlyChild"); ReactDefaultInjection.inject(); var React = { Children: { map: ReactChildren.map, forEach: ReactChildren.forEach, only: onlyChild }, DOM: ReactDOM, PropTypes: ReactPropTypes, initializeTouchEvents: function(shouldUseTouch) { EventPluginUtils.useTouchEvents = shouldUseTouch; }, createClass: ReactCompositeComponent.createClass, constructAndRenderComponent: ReactMount.constructAndRenderComponent, constructAndRenderComponentByID: ReactMount.constructAndRenderComponentByID, renderComponent: ReactPerf.measure( 'React', 'renderComponent', ReactMount.renderComponent ), renderComponentToString: ReactServerRendering.renderComponentToString, renderComponentToStaticMarkup: ReactServerRendering.renderComponentToStaticMarkup, unmountComponentAtNode: ReactMount.unmountComponentAtNode, isValidClass: ReactCompositeComponent.isValidClass, isValidComponent: ReactComponent.isValidComponent, withContext: ReactContext.withContext, __internals: { Component: ReactComponent, CurrentOwner: ReactCurrentOwner, DOMComponent: ReactDOMComponent, DOMPropertyOperations: DOMPropertyOperations, InstanceHandles: ReactInstanceHandles, Mount: ReactMount, MultiChild: ReactMultiChild, TextComponent: ReactTextComponent } }; if ("production" !== "development") { var ExecutionEnvironment = _dereq_("./ExecutionEnvironment"); if (ExecutionEnvironment.canUseDOM && window.top === window.self && navigator.userAgent.indexOf('Chrome') > -1) { console.debug( 'Download the React DevTools for a better development experience: ' + 'http://fb.me/react-devtools' ); } } // Version exists only in the open-source version of React, not in Facebook's // internal version. React.version = '0.10.0-rc1'; module.exports = React; },{"./DOMPropertyOperations":9,"./EventPluginUtils":18,"./ExecutionEnvironment":20,"./ReactChildren":26,"./ReactComponent":27,"./ReactCompositeComponent":29,"./ReactContext":30,"./ReactCurrentOwner":31,"./ReactDOM":32,"./ReactDOMComponent":34,"./ReactDefaultInjection":44,"./ReactInstanceHandles":53,"./ReactMount":55,"./ReactMultiChild":57,"./ReactPerf":60,"./ReactPropTypes":64,"./ReactServerRendering":68,"./ReactTextComponent":70,"./onlyChild":128}],25:[function(_dereq_,module,exports){ /** * Copyright 2013-2014 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. * * @providesModule ReactBrowserComponentMixin */ "use strict"; var ReactMount = _dereq_("./ReactMount"); var invariant = _dereq_("./invariant"); var ReactBrowserComponentMixin = { /** * Returns the DOM node rendered by this component. * * @return {DOMElement} The root node of this component. * @final * @protected */ getDOMNode: function() { ("production" !== "development" ? invariant( this.isMounted(), 'getDOMNode(): A component must be mounted to have a DOM node.' ) : invariant(this.isMounted())); return ReactMount.getNode(this._rootNodeID); } }; module.exports = ReactBrowserComponentMixin; },{"./ReactMount":55,"./invariant":112}],26:[function(_dereq_,module,exports){ /** * Copyright 2013-2014 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. * * @providesModule ReactChildren */ "use strict"; var PooledClass = _dereq_("./PooledClass"); var invariant = _dereq_("./invariant"); var traverseAllChildren = _dereq_("./traverseAllChildren"); var twoArgumentPooler = PooledClass.twoArgumentPooler; var threeArgumentPooler = PooledClass.threeArgumentPooler; /** * PooledClass representing the bookkeeping associated with performing a child * traversal. Allows avoiding binding callbacks. * * @constructor ForEachBookKeeping * @param {!function} forEachFunction Function to perform traversal with. * @param {?*} forEachContext Context to perform context with. */ function ForEachBookKeeping(forEachFunction, forEachContext) { this.forEachFunction = forEachFunction; this.forEachContext = forEachContext; } PooledClass.addPoolingTo(ForEachBookKeeping, twoArgumentPooler); function forEachSingleChild(traverseContext, child, name, i) { var forEachBookKeeping = traverseContext; forEachBookKeeping.forEachFunction.call( forEachBookKeeping.forEachContext, child, i); } /** * Iterates through children that are typically specified as `props.children`. * * The provided forEachFunc(child, index) will be called for each * leaf child. * * @param {?*} children Children tree container. * @param {function(*, int)} forEachFunc. * @param {*} forEachContext Context for forEachContext. */ function forEachChildren(children, forEachFunc, forEachContext) { if (children == null) { return children; } var traverseContext = ForEachBookKeeping.getPooled(forEachFunc, forEachContext); traverseAllChildren(children, forEachSingleChild, traverseContext); ForEachBookKeeping.release(traverseContext); } /** * PooledClass representing the bookkeeping associated with performing a child * mapping. Allows avoiding binding callbacks. * * @constructor MapBookKeeping * @param {!*} mapResult Object containing the ordered map of results. * @param {!function} mapFunction Function to perform mapping with. * @param {?*} mapContext Context to perform mapping with. */ function MapBookKeeping(mapResult, mapFunction, mapContext) { this.mapResult = mapResult; this.mapFunction = mapFunction; this.mapContext = mapContext; } PooledClass.addPoolingTo(MapBookKeeping, threeArgumentPooler); function mapSingleChildIntoContext(traverseContext, child, name, i) { var mapBookKeeping = traverseContext; var mapResult = mapBookKeeping.mapResult; var mappedChild = mapBookKeeping.mapFunction.call(mapBookKeeping.mapContext, child, i); // We found a component instance ("production" !== "development" ? invariant( !mapResult.hasOwnProperty(name), 'ReactChildren.map(...): Encountered two children with the same key, ' + '`%s`. Children keys must be unique.', name ) : invariant(!mapResult.hasOwnProperty(name))); mapResult[name] = mappedChild; } /** * Maps children that are typically specified as `props.children`. * * The provided mapFunction(child, key, index) will be called for each * leaf child. * * TODO: This may likely break any calls to `ReactChildren.map` that were * previously relying on the fact that we guarded against null children. * * @param {?*} children Children tree container. * @param {function(*, int)} mapFunction. * @param {*} mapContext Context for mapFunction. * @return {object} Object containing the ordered map of results. */ function mapChildren(children, func, context) { if (children == null) { return children; } var mapResult = {}; var traverseContext = MapBookKeeping.getPooled(mapResult, func, context); traverseAllChildren(children, mapSingleChildIntoContext, traverseContext); MapBookKeeping.release(traverseContext); return mapResult; } var ReactChildren = { forEach: forEachChildren, map: mapChildren }; module.exports = ReactChildren; },{"./PooledClass":23,"./invariant":112,"./traverseAllChildren":133}],27:[function(_dereq_,module,exports){ /** * Copyright 2013-2014 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. * * @providesModule ReactComponent */ "use strict"; var ReactCurrentOwner = _dereq_("./ReactCurrentOwner"); var ReactOwner = _dereq_("./ReactOwner"); var ReactUpdates = _dereq_("./ReactUpdates"); var invariant = _dereq_("./invariant"); var keyMirror = _dereq_("./keyMirror"); var merge = _dereq_("./merge"); var monitorCodeUse = _dereq_("./monitorCodeUse"); /** * Every React component is in one of these life cycles. */ var ComponentLifeCycle = keyMirror({ /** * Mounted components have a DOM node representation and are capable of * receiving new props. */ MOUNTED: null, /** * Unmounted components are inactive and cannot receive new props. */ UNMOUNTED: null }); /** * Warn if there's no key explicitly set on dynamic arrays of children or * object keys are not valid. This allows us to keep track of children between * updates. */ var ownerHasExplicitKeyWarning = {}; var ownerHasPropertyWarning = {}; var ownerHasMonitoredObjectMap = {}; var NUMERIC_PROPERTY_REGEX = /^\d+$/; var injected = false; /** * Optionally injectable environment dependent cleanup hook. (server vs. * browser etc). Example: A browser system caches DOM nodes based on component * ID and must remove that cache entry when this instance is unmounted. * * @private */ var unmountIDFromEnvironment = null; /** * The "image" of a component tree, is the platform specific (typically * serialized) data that represents a tree of lower level UI building blocks. * On the web, this "image" is HTML markup which describes a construction of * low level `div` and `span` nodes. Other platforms may have different * encoding of this "image". This must be injected. * * @private */ var mountImageIntoNode = null; /** * Warn if the component doesn't have an explicit key assigned to it. * This component is in an array. The array could grow and shrink or be * reordered. All children that haven't already been validated are required to * have a "key" property assigned to it. * * @internal * @param {ReactComponent} component Component that requires a key. */ function validateExplicitKey(component) { if (component.__keyValidated__ || component.props.key != null) { return; } component.__keyValidated__ = true; // We can't provide friendly warnings for top level components. if (!ReactCurrentOwner.current) { return; } // Name of the component whose render method tried to pass children. var currentName = ReactCurrentOwner.current.constructor.displayName; if (ownerHasExplicitKeyWarning.hasOwnProperty(currentName)) { return; } ownerHasExplicitKeyWarning[currentName] = true; var message = 'Each child in an array should have a unique "key" prop. ' + 'Check the render method of ' + currentName + '.'; var childOwnerName = null; if (!component.isOwnedBy(ReactCurrentOwner.current)) { // Name of the component that originally created this child. childOwnerName = component._owner && component._owner.constructor.displayName; // Usually the current owner is the offender, but if it accepts // children as a property, it may be the creator of the child that's // responsible for assigning it a key. message += ' It was passed a child from ' + childOwnerName + '.'; } message += ' See http://fb.me/react-warning-keys for more information.'; monitorCodeUse('react_key_warning', { component: currentName, componentOwner: childOwnerName }); console.warn(message); } /** * Warn if the key is being defined as an object property but has an incorrect * value. * * @internal * @param {string} name Property name of the key. * @param {ReactComponent} component Component that requires a key. */ function validatePropertyKey(name) { if (NUMERIC_PROPERTY_REGEX.test(name)) { // Name of the component whose render method tried to pass children. var currentName = ReactCurrentOwner.current.constructor.displayName; if (ownerHasPropertyWarning.hasOwnProperty(currentName)) { return; } ownerHasPropertyWarning[currentName] = true; monitorCodeUse('react_numeric_key_warning'); console.warn( 'Child objects should have non-numeric keys so ordering is preserved. ' + 'Check the render method of ' + currentName + '. ' + 'See http://fb.me/react-warning-keys for more information.' ); } } /** * Log that we're using an object map. We're considering deprecating this * feature and replace it with proper Map and ImmutableMap data structures. * * @internal */ function monitorUseOfObjectMap() { // Name of the component whose render method tried to pass children. // We only use this to avoid spewing the logs. We lose additional // owner stacks but hopefully one level is enough to trace the source. var currentName = (ReactCurrentOwner.current && ReactCurrentOwner.current.constructor.displayName) || ''; if (ownerHasMonitoredObjectMap.hasOwnProperty(currentName)) { return; } ownerHasMonitoredObjectMap[currentName] = true; monitorCodeUse('react_object_map_children'); } /** * Ensure that every component either is passed in a static location, in an * array with an explicit keys property defined, or in an object literal * with valid key property. * * @internal * @param {*} component Statically passed child of any type. * @return {boolean} */ function validateChildKeys(component) { if (Array.isArray(component)) { for (var i = 0; i < component.length; i++) { var child = component[i]; if (ReactComponent.isValidComponent(child)) { validateExplicitKey(child); } } } else if (ReactComponent.isValidComponent(component)) { // This component was passed in a valid location. component.__keyValidated__ = true; } else if (component && typeof component === 'object') { monitorUseOfObjectMap(); for (var name in component) { validatePropertyKey(name, component); } } } /** * Components are the basic units of composition in React. * * Every component accepts a set of keyed input parameters known as "props" that * are initialized by the constructor. Once a component is mounted, the props * can be mutated using `setProps` or `replaceProps`. * * Every component is capable of the following operations: * * `mountComponent` * Initializes the component, renders markup, and registers event listeners. * * `receiveComponent` * Updates the rendered DOM nodes to match the given component. * * `unmountComponent` * Releases any resources allocated by this component. * * Components can also be "owned" by other components. Being owned by another * component means being constructed by that component. This is different from * being the child of a component, which means having a DOM representation that * is a child of the DOM representation of that component. * * @class ReactComponent */ var ReactComponent = { injection: { injectEnvironment: function(ReactComponentEnvironment) { ("production" !== "development" ? invariant( !injected, 'ReactComponent: injectEnvironment() can only be called once.' ) : invariant(!injected)); mountImageIntoNode = ReactComponentEnvironment.mountImageIntoNode; unmountIDFromEnvironment = ReactComponentEnvironment.unmountIDFromEnvironment; ReactComponent.BackendIDOperations = ReactComponentEnvironment.BackendIDOperations; ReactComponent.ReactReconcileTransaction = ReactComponentEnvironment.ReactReconcileTransaction; injected = true; } }, /** * @param {?object} object * @return {boolean} True if `object` is a valid component. * @final */ isValidComponent: function(object) { if (!object || !object.type || !object.type.prototype) { return false; } // This is the safer way of duck checking the type of instance this is. // The object can be a generic descriptor but the type property refers to // the constructor and it's prototype can be used to inspect the type that // will actually get mounted. var prototype = object.type.prototype; return ( typeof prototype.mountComponentIntoNode === 'function' && typeof prototype.receiveComponent === 'function' ); }, /** * @internal */ LifeCycle: ComponentLifeCycle, /** * Injected module that provides ability to mutate individual properties. * Injected into the base class because many different subclasses need access * to this. * * @internal */ BackendIDOperations: null, /** * React references `ReactReconcileTransaction` using this property in order * to allow dependency injection. * * @internal */ ReactReconcileTransaction: null, /** * Base functionality for every ReactComponent constructor. Mixed into the * `ReactComponent` prototype, but exposed statically for easy access. * * @lends {ReactComponent.prototype} */ Mixin: { /** * Checks whether or not this component is mounted. * * @return {boolean} True if mounted, false otherwise. * @final * @protected */ isMounted: function() { return this._lifeCycleState === ComponentLifeCycle.MOUNTED; }, /** * Sets a subset of the props. * * @param {object} partialProps Subset of the next props. * @param {?function} callback Called after props are updated. * @final * @public */ setProps: function(partialProps, callback) { // Merge with `_pendingProps` if it exists, otherwise with existing props. this.replaceProps( merge(this._pendingProps || this.props, partialProps), callback ); }, /** * Replaces all of the props. * * @param {object} props New props. * @param {?function} callback Called after props are updated. * @final * @public */ replaceProps: function(props, callback) { ("production" !== "development" ? invariant( this.isMounted(), 'replaceProps(...): Can only update a mounted component.' ) : invariant(this.isMounted())); ("production" !== "development" ? invariant( this._mountDepth === 0, 'replaceProps(...): You called `setProps` or `replaceProps` on a ' + 'component with a parent. This is an anti-pattern since props will ' + 'get reactively updated when rendered. Instead, change the owner\'s ' + '`render` method to pass the correct value as props to the component ' + 'where it is created.' ) : invariant(this._mountDepth === 0)); this._pendingProps = props; ReactUpdates.enqueueUpdate(this, callback); }, /** * Base constructor for all React components. * * Subclasses that override this method should make sure to invoke * `ReactComponent.Mixin.construct.call(this, ...)`. * * @param {?object} initialProps * @param {*} children * @internal */ construct: function(initialProps, children) { this.props = initialProps || {}; // Record the component responsible for creating this component. this._owner = ReactCurrentOwner.current; // All components start unmounted. this._lifeCycleState = ComponentLifeCycle.UNMOUNTED; this._pendingProps = null; this._pendingCallbacks = null; // Unlike _pendingProps and _pendingCallbacks, we won't use null to // indicate that nothing is pending because it's possible for a component // to have a null owner. Instead, an owner change is pending when // this._owner !== this._pendingOwner. this._pendingOwner = this._owner; // Children can be more than one argument var childrenLength = arguments.length - 1; if (childrenLength === 1) { if ("production" !== "development") { validateChildKeys(children); } this.props.children = children; } else if (childrenLength > 1) { var childArray = Array(childrenLength); for (var i = 0; i < childrenLength; i++) { if ("production" !== "development") { validateChildKeys(arguments[i + 1]); } childArray[i] = arguments[i + 1]; } this.props.children = childArray; } }, /** * Initializes the component, renders markup, and registers event listeners. * * NOTE: This does not insert any nodes into the DOM. * * Subclasses that override this method should make sure to invoke * `ReactComponent.Mixin.mountComponent.call(this, ...)`. * * @param {string} rootID DOM ID of the root node. * @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction * @param {number} mountDepth number of components in the owner hierarchy. * @return {?string} Rendered markup to be inserted into the DOM. * @internal */ mountComponent: function(rootID, transaction, mountDepth) { ("production" !== "development" ? invariant( !this.isMounted(), 'mountComponent(%s, ...): Can only mount an unmounted component. ' + 'Make sure to avoid storing components between renders or reusing a ' + 'single component instance in multiple places.', rootID ) : invariant(!this.isMounted())); var props = this.props; if (props.ref != null) { ReactOwner.addComponentAsRefTo(this, props.ref, this._owner); } this._rootNodeID = rootID; this._lifeCycleState = ComponentLifeCycle.MOUNTED; this._mountDepth = mountDepth; // Effectively: return ''; }, /** * Releases any resources allocated by `mountComponent`. * * NOTE: This does not remove any nodes from the DOM. * * Subclasses that override this method should make sure to invoke * `ReactComponent.Mixin.unmountComponent.call(this)`. * * @internal */ unmountComponent: function() { ("production" !== "development" ? invariant( this.isMounted(), 'unmountComponent(): Can only unmount a mounted component.' ) : invariant(this.isMounted())); var props = this.props; if (props.ref != null) { ReactOwner.removeComponentAsRefFrom(this, props.ref, this._owner); } unmountIDFromEnvironment(this._rootNodeID); this._rootNodeID = null; this._lifeCycleState = ComponentLifeCycle.UNMOUNTED; }, /** * Given a new instance of this component, updates the rendered DOM nodes * as if that instance was rendered instead. * * Subclasses that override this method should make sure to invoke * `ReactComponent.Mixin.receiveComponent.call(this, ...)`. * * @param {object} nextComponent Next set of properties. * @param {ReactReconcileTransaction} transaction * @internal */ receiveComponent: function(nextComponent, transaction) { ("production" !== "development" ? invariant( this.isMounted(), 'receiveComponent(...): Can only update a mounted component.' ) : invariant(this.isMounted())); this._pendingOwner = nextComponent._owner; this._pendingProps = nextComponent.props; this._performUpdateIfNecessary(transaction); }, /** * Call `_performUpdateIfNecessary` within a new transaction. * * @internal */ performUpdateIfNecessary: function() { var transaction = ReactComponent.ReactReconcileTransaction.getPooled(); transaction.perform(this._performUpdateIfNecessary, this, transaction); ReactComponent.ReactReconcileTransaction.release(transaction); }, /** * If `_pendingProps` is set, update the component. * * @param {ReactReconcileTransaction} transaction * @internal */ _performUpdateIfNecessary: function(transaction) { if (this._pendingProps == null) { return; } var prevProps = this.props; var prevOwner = this._owner; this.props = this._pendingProps; this._owner = this._pendingOwner; this._pendingProps = null; this.updateComponent(transaction, prevProps, prevOwner); }, /** * Updates the component's currently mounted representation. * * @param {ReactReconcileTransaction} transaction * @param {object} prevProps * @internal */ updateComponent: function(transaction, prevProps, prevOwner) { var props = this.props; // 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`. if (this._owner !== prevOwner || props.ref !== prevProps.ref) { if (prevProps.ref != null) { ReactOwner.removeComponentAsRefFrom( this, prevProps.ref, prevOwner ); } // Correct, even if the owner is the same, and only the ref has changed. if (props.ref != null) { ReactOwner.addComponentAsRefTo(this, props.ref, this._owner); } } }, /** * Mounts this component and inserts it into the DOM. * * @param {string} rootID DOM ID of the root node. * @param {DOMElement} container DOM element to mount into. * @param {boolean} shouldReuseMarkup If true, do not insert markup * @final * @internal * @see {ReactMount.renderComponent} */ mountComponentIntoNode: function(rootID, container, shouldReuseMarkup) { var transaction = ReactComponent.ReactReconcileTransaction.getPooled(); transaction.perform( this._mountComponentIntoNode, this, rootID, container, transaction, shouldReuseMarkup ); ReactComponent.ReactReconcileTransaction.release(transaction); }, /** * @param {string} rootID DOM ID of the root node. * @param {DOMElement} container DOM element to mount into. * @param {ReactReconcileTransaction} transaction * @param {boolean} shouldReuseMarkup If true, do not insert markup * @final * @private */ _mountComponentIntoNode: function( rootID, container, transaction, shouldReuseMarkup) { var markup = this.mountComponent(rootID, transaction, 0); mountImageIntoNode(markup, container, shouldReuseMarkup); }, /** * Checks if this component is owned by the supplied `owner` component. * * @param {ReactComponent} owner Component to check. * @return {boolean} True if `owners` owns this component. * @final * @internal */ isOwnedBy: function(owner) { return this._owner === owner; }, /** * Gets another component, that shares the same owner as this one, by ref. * * @param {string} ref of a sibling Component. * @return {?ReactComponent} the actual sibling Component. * @final * @internal */ getSiblingByRef: function(ref) { var owner = this._owner; if (!owner || !owner.refs) { return null; } return owner.refs[ref]; } } }; module.exports = ReactComponent; },{"./ReactCurrentOwner":31,"./ReactOwner":59,"./ReactUpdates":71,"./invariant":112,"./keyMirror":118,"./merge":121,"./monitorCodeUse":125}],28:[function(_dereq_,module,exports){ /** * Copyright 2013-2014 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. * * @providesModule ReactComponentBrowserEnvironment */ /*jslint evil: true */ "use strict"; var ReactDOMIDOperations = _dereq_("./ReactDOMIDOperations"); var ReactMarkupChecksum = _dereq_("./ReactMarkupChecksum"); var ReactMount = _dereq_("./ReactMount"); var ReactPerf = _dereq_("./ReactPerf"); var ReactReconcileTransaction = _dereq_("./ReactReconcileTransaction"); var getReactRootElementInContainer = _dereq_("./getReactRootElementInContainer"); var invariant = _dereq_("./invariant"); var ELEMENT_NODE_TYPE = 1; var DOC_NODE_TYPE = 9; /** * Abstracts away all functionality of `ReactComponent` requires knowledge of * the browser context. */ var ReactComponentBrowserEnvironment = { ReactReconcileTransaction: ReactReconcileTransaction, BackendIDOperations: ReactDOMIDOperations, /** * If a particular environment requires that some resources be cleaned up, * specify this in the injected Mixin. In the DOM, we would likely want to * purge any cached node ID lookups. * * @private */ unmountIDFromEnvironment: function(rootNodeID) { ReactMount.purgeID(rootNodeID); }, /** * @param {string} markup Markup string to place into the DOM Element. * @param {DOMElement} container DOM Element to insert markup into. * @param {boolean} shouldReuseMarkup Should reuse the existing markup in the * container if possible. */ mountImageIntoNode: ReactPerf.measure( 'ReactComponentBrowserEnvironment', 'mountImageIntoNode', function(markup, container, shouldReuseMarkup) { ("production" !== "development" ? invariant( container && ( container.nodeType === ELEMENT_NODE_TYPE || container.nodeType === DOC_NODE_TYPE ), 'mountComponentIntoNode(...): Target container is not valid.' ) : invariant(container && ( container.nodeType === ELEMENT_NODE_TYPE || container.nodeType === DOC_NODE_TYPE ))); if (shouldReuseMarkup) { if (ReactMarkupChecksum.canReuseMarkup( markup, getReactRootElementInContainer(container))) { return; } else { ("production" !== "development" ? invariant( container.nodeType !== DOC_NODE_TYPE, 'You\'re trying to render a component to the document using ' + 'server rendering but the checksum was invalid. This usually ' + 'means you rendered a different component type or props on ' + 'the client from the one on the server, or your render() ' + 'methods are impure. React cannot handle this case due to ' + 'cross-browser quirks by rendering at the document root. You ' + 'should look for environment dependent code in your components ' + 'and ensure the props are the same client and server side.' ) : invariant(container.nodeType !== DOC_NODE_TYPE)); if ("production" !== "development") { console.warn( 'React attempted to use reuse markup in a container but the ' + 'checksum was invalid. This generally means that you are ' + 'using server rendering and the markup generated on the ' + 'server was not what the client was expecting. React injected' + 'new markup to compensate which works but you have lost many ' + 'of the benefits of server rendering. Instead, figure out ' + 'why the markup being generated is different on the client ' + 'or server.' ); } } } ("production" !== "development" ? invariant( container.nodeType !== DOC_NODE_TYPE, 'You\'re trying to render a component to the document but ' + 'you didn\'t use server rendering. We can\'t do this ' + 'without using server rendering due to cross-browser quirks. ' + 'See renderComponentToString() for server rendering.' ) : invariant(container.nodeType !== DOC_NODE_TYPE)); container.innerHTML = markup; } ) }; module.exports = ReactComponentBrowserEnvironment; },{"./ReactDOMIDOperations":36,"./ReactMarkupChecksum":54,"./ReactMount":55,"./ReactPerf":60,"./ReactReconcileTransaction":66,"./getReactRootElementInContainer":107,"./invariant":112}],29:[function(_dereq_,module,exports){ /** * Copyright 2013-2014 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. * * @providesModule ReactCompositeComponent */ "use strict"; var ReactComponent = _dereq_("./ReactComponent"); var ReactContext = _dereq_("./ReactContext"); var ReactCurrentOwner = _dereq_("./ReactCurrentOwner"); var ReactErrorUtils = _dereq_("./ReactErrorUtils"); var ReactOwner = _dereq_("./ReactOwner"); var ReactPerf = _dereq_("./ReactPerf"); var ReactPropTransferer = _dereq_("./ReactPropTransferer"); var ReactPropTypeLocations = _dereq_("./ReactPropTypeLocations"); var ReactPropTypeLocationNames = _dereq_("./ReactPropTypeLocationNames"); var ReactUpdates = _dereq_("./ReactUpdates"); var instantiateReactComponent = _dereq_("./instantiateReactComponent"); var invariant = _dereq_("./invariant"); var keyMirror = _dereq_("./keyMirror"); var merge = _dereq_("./merge"); var mixInto = _dereq_("./mixInto"); var monitorCodeUse = _dereq_("./monitorCodeUse"); var objMap = _dereq_("./objMap"); var shouldUpdateReactComponent = _dereq_("./shouldUpdateReactComponent"); var warning = _dereq_("./warning"); /** * Policies that describe methods in `ReactCompositeComponentInterface`. */ var SpecPolicy = keyMirror({ /** * These methods may be defined only once by the class specification or mixin. */ DEFINE_ONCE: null, /** * These methods may be defined by both the class specification and mixins. * Subsequent definitions will be chained. These methods must return void. */ DEFINE_MANY: null, /** * These methods are overriding the base ReactCompositeComponent class. */ OVERRIDE_BASE: null, /** * These methods are similar to DEFINE_MANY, except we assume they return * objects. We try to merge the keys of the return values of all the mixed in * functions. If there is a key conflict we throw. */ DEFINE_MANY_MERGED: null }); var injectedMixins = []; /** * Composite components are higher-level components that compose other composite * or native components. * * To create a new type of `ReactCompositeComponent`, pass a specification of * your new class to `React.createClass`. The only requirement of your class * specification is that you implement a `render` method. * * var MyComponent = React.createClass({ * render: function() { * return <div>Hello World</div>; * } * }); * * The class specification supports a specific protocol of methods that have * special meaning (e.g. `render`). See `ReactCompositeComponentInterface` for * more the comprehensive protocol. Any other properties and methods in the * class specification will available on the prototype. * * @interface ReactCompositeComponentInterface * @internal */ var ReactCompositeComponentInterface = { /** * An array of Mixin objects to include when defining your component. * * @type {array} * @optional */ mixins: SpecPolicy.DEFINE_MANY, /** * An object containing properties and methods that should be defined on * the component's constructor instead of its prototype (static methods). * * @type {object} * @optional */ statics: SpecPolicy.DEFINE_MANY, /** * Definition of prop types for this component. * * @type {object} * @optional */ propTypes: SpecPolicy.DEFINE_MANY, /** * Definition of context types for this component. * * @type {object} * @optional */ contextTypes: SpecPolicy.DEFINE_MANY, /** * Definition of context types this component sets for its children. * * @type {object} * @optional */ childContextTypes: SpecPolicy.DEFINE_MANY, // ==== Definition methods ==== /** * Invoked when the component is mounted. Values in the mapping will be set on * `this.props` if that prop is not specified (i.e. using an `in` check). * * This method is invoked before `getInitialState` and therefore cannot rely * on `this.state` or use `this.setState`. * * @return {object} * @optional */ getDefaultProps: SpecPolicy.DEFINE_MANY_MERGED, /** * Invoked once before the component is mounted. The return value will be used * as the initial value of `this.state`. * * getInitialState: function() { * return { * isOn: false, * fooBaz: new BazFoo() * } * } * * @return {object} * @optional */ getInitialState: SpecPolicy.DEFINE_MANY_MERGED, /** * @return {object} * @optional */ getChildContext: SpecPolicy.DEFINE_MANY_MERGED, /** * Uses props from `this.props` and state from `this.state` to render the * structure of the component. * * No guarantees are made about when or how often this method is invoked, so * it must not have side effects. * * render: function() { * var name = this.props.name; * return <div>Hello, {name}!</div>; * } * * @return {ReactComponent} * @nosideeffects * @required */ render: SpecPolicy.DEFINE_ONCE, // ==== Delegate methods ==== /** * Invoked when the component is initially created and about to be mounted. * This may have side effects, but any external subscriptions or data created * by this method must be cleaned up in `componentWillUnmount`. * * @optional */ componentWillMount: SpecPolicy.DEFINE_MANY, /** * Invoked when the component has been mounted and has a DOM representation. * However, there is no guarantee that the DOM node is in the document. * * Use this as an opportunity to operate on the DOM when the component has * been mounted (initialized and rendered) for the first time. * * @param {DOMElement} rootNode DOM element representing the component. * @optional */ componentDidMount: SpecPolicy.DEFINE_MANY, /** * Invoked before the component receives new props. * * Use this as an opportunity to react to a prop transition by updating the * state using `this.setState`. Current props are accessed via `this.props`. * * componentWillReceiveProps: function(nextProps, nextContext) { * this.setState({ * likesIncreasing: nextProps.likeCount > this.props.likeCount * }); * } * * NOTE: There is no equivalent `componentWillReceiveState`. An incoming prop * transition may cause a state change, but the opposite is not true. If you * need it, you are probably looking for `componentWillUpdate`. * * @param {object} nextProps * @optional */ componentWillReceiveProps: SpecPolicy.DEFINE_MANY, /** * Invoked while deciding if the component should be updated as a result of * receiving new props, state and/or context. * * Use this as an opportunity to `return false` when you're certain that the * transition to the new props/state/context will not require a component * update. * * shouldComponentUpdate: function(nextProps, nextState, nextContext) { * return !equal(nextProps, this.props) || * !equal(nextState, this.state) || * !equal(nextContext, this.context); * } * * @param {object} nextProps * @param {?object} nextState * @param {?object} nextContext * @return {boolean} True if the component should update. * @optional */ shouldComponentUpdate: SpecPolicy.DEFINE_ONCE, /** * Invoked when the component is about to update due to a transition from * `this.props`, `this.state` and `this.context` to `nextProps`, `nextState` * and `nextContext`. * * Use this as an opportunity to perform preparation before an update occurs. * * NOTE: You **cannot** use `this.setState()` in this method. * * @param {object} nextProps * @param {?object} nextState * @param {?object} nextContext * @param {ReactReconcileTransaction} transaction * @optional */ componentWillUpdate: SpecPolicy.DEFINE_MANY, /** * Invoked when the component's DOM representation has been updated. * * Use this as an opportunity to operate on the DOM when the component has * been updated. * * @param {object} prevProps * @param {?object} prevState * @param {?object} prevContext * @param {DOMElement} rootNode DOM element representing the component. * @optional */ componentDidUpdate: SpecPolicy.DEFINE_MANY, /** * Invoked when the component is about to be removed from its parent and have * its DOM representation destroyed. * * Use this as an opportunity to deallocate any external resources. * * NOTE: There is no `componentDidUnmount` since your component will have been * destroyed by that point. * * @optional */ componentWillUnmount: SpecPolicy.DEFINE_MANY, // ==== Advanced methods ==== /** * Updates the component's currently mounted DOM representation. * * By default, this implements React's rendering and reconciliation algorithm. * Sophisticated clients may wish to override this. * * @param {ReactReconcileTransaction} transaction * @internal * @overridable */ updateComponent: SpecPolicy.OVERRIDE_BASE }; /** * Mapping from class specification keys to special processing functions. * * Although these are declared like instance properties in the specification * when defining classes using `React.createClass`, they are actually static * and are accessible on the constructor instead of the prototype. Despite * being static, they must be defined outside of the "statics" key under * which all other static methods are defined. */ var RESERVED_SPEC_KEYS = { displayName: function(ConvenienceConstructor, displayName) { ConvenienceConstructor.componentConstructor.displayName = displayName; }, mixins: function(ConvenienceConstructor, mixins) { if (mixins) { for (var i = 0; i < mixins.length; i++) { mixSpecIntoComponent(ConvenienceConstructor, mixins[i]); } } }, childContextTypes: function(ConvenienceConstructor, childContextTypes) { var Constructor = ConvenienceConstructor.componentConstructor; validateTypeDef( Constructor, childContextTypes, ReactPropTypeLocations.childContext ); Constructor.childContextTypes = merge( Constructor.childContextTypes, childContextTypes ); }, contextTypes: function(ConvenienceConstructor, contextTypes) { var Constructor = ConvenienceConstructor.componentConstructor; validateTypeDef( Constructor, contextTypes, ReactPropTypeLocations.context ); Constructor.contextTypes = merge(Constructor.contextTypes, contextTypes); }, propTypes: function(ConvenienceConstructor, propTypes) { var Constructor = ConvenienceConstructor.componentConstructor; validateTypeDef( Constructor, propTypes, ReactPropTypeLocations.prop ); Constructor.propTypes = merge(Constructor.propTypes, propTypes); }, statics: function(ConvenienceConstructor, statics) { mixStaticSpecIntoComponent(ConvenienceConstructor, statics); } }; function validateTypeDef(Constructor, typeDef, location) { for (var propName in typeDef) { if (typeDef.hasOwnProperty(propName)) { ("production" !== "development" ? invariant( typeof typeDef[propName] == 'function', '%s: %s type `%s` is invalid; it must be a function, usually from ' + 'React.PropTypes.', Constructor.displayName || 'ReactCompositeComponent', ReactPropTypeLocationNames[location], propName ) : invariant(typeof typeDef[propName] == 'function')); } } } function validateMethodOverride(proto, name) { var specPolicy = ReactCompositeComponentInterface[name]; // Disallow overriding of base class methods unless explicitly allowed. if (ReactCompositeComponentMixin.hasOwnProperty(name)) { ("production" !== "development" ? invariant( specPolicy === SpecPolicy.OVERRIDE_BASE, 'ReactCompositeComponentInterface: You are attempting to override ' + '`%s` from your class specification. Ensure that your method names ' + 'do not overlap with React methods.', name ) : invariant(specPolicy === SpecPolicy.OVERRIDE_BASE)); } // Disallow defining methods more than once unless explicitly allowed. if (proto.hasOwnProperty(name)) { ("production" !== "development" ? invariant( specPolicy === SpecPolicy.DEFINE_MANY || specPolicy === SpecPolicy.DEFINE_MANY_MERGED, 'ReactCompositeComponentInterface: You are attempting to define ' + '`%s` on your component more than once. This conflict may be due ' + 'to a mixin.', name ) : invariant(specPolicy === SpecPolicy.DEFINE_MANY || specPolicy === SpecPolicy.DEFINE_MANY_MERGED)); } } function validateLifeCycleOnReplaceState(instance) { var compositeLifeCycleState = instance._compositeLifeCycleState; ("production" !== "development" ? invariant( instance.isMounted() || compositeLifeCycleState === CompositeLifeCycle.MOUNTING, 'replaceState(...): Can only update a mounted or mounting component.' ) : invariant(instance.isMounted() || compositeLifeCycleState === CompositeLifeCycle.MOUNTING)); ("production" !== "development" ? invariant(compositeLifeCycleState !== CompositeLifeCycle.RECEIVING_STATE, 'replaceState(...): Cannot update during an existing state transition ' + '(such as within `render`). This could potentially cause an infinite ' + 'loop so it is forbidden.' ) : invariant(compositeLifeCycleState !== CompositeLifeCycle.RECEIVING_STATE)); ("production" !== "development" ? invariant(compositeLifeCycleState !== CompositeLifeCycle.UNMOUNTING, 'replaceState(...): Cannot update while unmounting component. This ' + 'usually means you called setState() on an unmounted component.' ) : invariant(compositeLifeCycleState !== CompositeLifeCycle.UNMOUNTING)); } /** * Custom version of `mixInto` which handles policy validation and reserved * specification keys when building `ReactCompositeComponent` classses. */ function mixSpecIntoComponent(ConvenienceConstructor, spec) { ("production" !== "development" ? invariant( !isValidClass(spec), 'ReactCompositeComponent: You\'re attempting to ' + 'use a component class as a mixin. Instead, just use a regular object.' ) : invariant(!isValidClass(spec))); ("production" !== "development" ? invariant( !ReactComponent.isValidComponent(spec), 'ReactCompositeComponent: You\'re attempting to ' + 'use a component as a mixin. Instead, just use a regular object.' ) : invariant(!ReactComponent.isValidComponent(spec))); var Constructor = ConvenienceConstructor.componentConstructor; var proto = Constructor.prototype; for (var name in spec) { var property = spec[name]; if (!spec.hasOwnProperty(name)) { continue; } validateMethodOverride(proto, name); if (RESERVED_SPEC_KEYS.hasOwnProperty(name)) { RESERVED_SPEC_KEYS[name](ConvenienceConstructor, property); } else { // Setup methods on prototype: // The following member methods should not be automatically bound: // 1. Expected ReactCompositeComponent methods (in the "interface"). // 2. Overridden methods (that were mixed in). var isCompositeComponentMethod = name in ReactCompositeComponentInterface; var isInherited = name in proto; var markedDontBind = property && property.__reactDontBind; var isFunction = typeof property === 'function'; var shouldAutoBind = isFunction && !isCompositeComponentMethod && !isInherited && !markedDontBind; if (shouldAutoBind) { if (!proto.__reactAutoBindMap) { proto.__reactAutoBindMap = {}; } proto.__reactAutoBindMap[name] = property; proto[name] = property; } else { if (isInherited) { // For methods which are defined more than once, call the existing // methods before calling the new property. if (ReactCompositeComponentInterface[name] === SpecPolicy.DEFINE_MANY_MERGED) { proto[name] = createMergedResultFunction(proto[name], property); } else { proto[name] = createChainedFunction(proto[name], property); } } else { proto[name] = property; } } } } } function mixStaticSpecIntoComponent(ConvenienceConstructor, statics) { if (!statics) { return; } for (var name in statics) { var property = statics[name]; if (!statics.hasOwnProperty(name)) { return; } var isInherited = name in ConvenienceConstructor; var result = property; if (isInherited) { var existingProperty = ConvenienceConstructor[name]; var existingType = typeof existingProperty; var propertyType = typeof property; ("production" !== "development" ? invariant( existingType === 'function' && propertyType === 'function', 'ReactCompositeComponent: You are attempting to define ' + '`%s` on your component more than once, but that is only supported ' + 'for functions, which are chained together. This conflict may be ' + 'due to a mixin.', name ) : invariant(existingType === 'function' && propertyType === 'function')); result = createChainedFunction(existingProperty, property); } ConvenienceConstructor[name] = result; ConvenienceConstructor.componentConstructor[name] = result; } } /** * Merge two objects, but throw if both contain the same key. * * @param {object} one The first object, which is mutated. * @param {object} two The second object * @return {object} one after it has been mutated to contain everything in two. */ function mergeObjectsWithNoDuplicateKeys(one, two) { ("production" !== "development" ? invariant( one && two && typeof one === 'object' && typeof two === 'object', 'mergeObjectsWithNoDuplicateKeys(): Cannot merge non-objects' ) : invariant(one && two && typeof one === 'object' && typeof two === 'object')); objMap(two, function(value, key) { ("production" !== "development" ? invariant( one[key] === undefined, 'mergeObjectsWithNoDuplicateKeys(): ' + 'Tried to merge two objects with the same key: %s', key ) : invariant(one[key] === undefined)); one[key] = value; }); return one; } /** * Creates a function that invokes two functions and merges their return values. * * @param {function} one Function to invoke first. * @param {function} two Function to invoke second. * @return {function} Function that invokes the two argument functions. * @private */ function createMergedResultFunction(one, two) { return function mergedResult() { var a = one.apply(this, arguments); var b = two.apply(this, arguments); if (a == null) { return b; } else if (b == null) { return a; } return mergeObjectsWithNoDuplicateKeys(a, b); }; } /** * Creates a function that invokes two functions and ignores their return vales. * * @param {function} one Function to invoke first. * @param {function} two Function to invoke second. * @return {function} Function that invokes the two argument functions. * @private */ function createChainedFunction(one, two) { return function chainedFunction() { one.apply(this, arguments); two.apply(this, arguments); }; } if ("production" !== "development") { var unmountedPropertyWhitelist = { constructor: true, construct: true, isOwnedBy: true, // should be deprecated but can have code mod (internal) type: true, props: true, // currently private but belong on the descriptor and are valid for use // inside the framework: __keyValidated__: true, _owner: true, _currentContext: true }; var componentInstanceProperties = { __keyValidated__: true, __keySetters: true, _compositeLifeCycleState: true, _currentContext: true, _defaultProps: true, _instance: true, _lifeCycleState: true, _mountDepth: true, _owner: true, _pendingCallbacks: true, _pendingContext: true, _pendingForceUpdate: true, _pendingOwner: true, _pendingProps: true, _pendingState: true, _renderedComponent: true, _rootNodeID: true, context: true, props: true, refs: true, state: true, // These are known instance properties coming from other sources _pendingQueries: true, _queryPropListeners: true, queryParams: true }; var hasWarnedOnComponentType = {}; var warningStackCounter = 0; var issueMembraneWarning = function(instance, key) { var isWhitelisted = unmountedPropertyWhitelist.hasOwnProperty(key); if (warningStackCounter > 0 || isWhitelisted) { return; } var name = instance.constructor.displayName || 'Unknown'; var owner = ReactCurrentOwner.current; var ownerName = (owner && owner.constructor.displayName) || 'Unknown'; var warningKey = key + '|' + name + '|' + ownerName; if (hasWarnedOnComponentType.hasOwnProperty(warningKey)) { // We have already warned for this combination. Skip it this time. return; } hasWarnedOnComponentType[warningKey] = true; var context = owner ? ' in ' + ownerName + '.' : ' at the top level.'; var staticMethodExample = '<' + name + ' />.type.' + key + '(...)'; monitorCodeUse('react_descriptor_property_access', { component: name }); console.warn( 'Invalid access to component property "' + key + '" on ' + name + context + ' See http://fb.me/react-warning-descriptors .' + ' Use a static method instead: ' + staticMethodExample ); }; var wrapInMembraneFunction = function(fn, thisBinding) { if (fn.__reactMembraneFunction && fn.__reactMembraneSelf === thisBinding) { return fn.__reactMembraneFunction; } return fn.__reactMembraneFunction = function() { /** * By getting this function, you've already received a warning. The * internals of this function will likely cause more warnings. To avoid * Spamming too much we disable any warning triggered inside of this * stack. */ warningStackCounter++; try { // If the this binding is unchanged, we defer to the real component. // This is important to keep some referential integrity in the // internals. E.g. owner equality check. var self = this === thisBinding ? this.__realComponentInstance : this; return fn.apply(self, arguments); } finally { warningStackCounter--; } }; }; var defineMembraneProperty = function(membrane, prototype, key) { Object.defineProperty(membrane, key, { configurable: false, enumerable: true, get: function() { if (this === membrane) { // We're allowed to access the prototype directly. return prototype[key]; } issueMembraneWarning(this, key); var realValue = this.__realComponentInstance[key]; // If the real value is a function, we need to provide a wrapper that // disables nested warnings. The properties type and constructors are // expected to the be constructors and therefore is often use with an // equality check and we shouldn't try to rebind those. if (typeof realValue === 'function' && key !== 'type' && key !== 'constructor') { return wrapInMembraneFunction(realValue, this); } return realValue; }, set: function(value) { if (this === membrane) { // We're allowed to set a value on the prototype directly. prototype[key] = value; return; } issueMembraneWarning(this, key); this.__realComponentInstance[key] = value; } }); }; /** * Creates a membrane prototype which wraps the original prototype. If any * property is accessed in an unmounted state, a warning is issued. * * @param {object} prototype Original prototype. * @return {object} The membrane prototype. * @private */ var createMountWarningMembrane = function(prototype) { var membrane = {}; var key; for (key in prototype) { defineMembraneProperty(membrane, prototype, key); } // These are properties that goes into the instance but not the prototype. // We can create the membrane on the prototype even though this will // result in a faulty hasOwnProperty check it's better perf. for (key in componentInstanceProperties) { if (componentInstanceProperties.hasOwnProperty(key) && !(key in prototype)) { defineMembraneProperty(membrane, prototype, key); } } return membrane; }; /** * Creates a membrane constructor which wraps the component that gets mounted. * * @param {function} constructor Original constructor. * @return {function} The membrane constructor. * @private */ var createDescriptorProxy = function(constructor) { try { var ProxyConstructor = function() { this.__realComponentInstance = new constructor(); // We can only safely pass through known instance variables. Unknown // expandos are not safe. Use the real mounted instance to avoid this // problem if it blows something up. Object.freeze(this); }; ProxyConstructor.prototype = createMountWarningMembrane( constructor.prototype ); return ProxyConstructor; } catch(x) { // In IE8 define property will fail on non-DOM objects. If anything in // the membrane creation fails, we'll bail out and just use the plain // constructor without warnings. return constructor; } }; } /** * `ReactCompositeComponent` maintains an auxiliary life cycle state in * `this._compositeLifeCycleState` (which can be null). * * This is different from the life cycle state maintained by `ReactComponent` in * `this._lifeCycleState`. The following diagram shows how the states overlap in * time. There are times when the CompositeLifeCycle is null - at those times it * is only meaningful to look at ComponentLifeCycle alone. * * Top Row: ReactComponent.ComponentLifeCycle * Low Row: ReactComponent.CompositeLifeCycle * * +-------+------------------------------------------------------+--------+ * | UN | MOUNTED | UN | * |MOUNTED| | MOUNTED| * +-------+------------------------------------------------------+--------+ * | ^--------+ +------+ +------+ +------+ +--------^ | * | | | | | | | | | | | | * | 0--|MOUNTING|-0-|RECEIV|-0-|RECEIV|-0-|RECEIV|-0-| UN |--->0 | * | | | |PROPS | | PROPS| | STATE| |MOUNTING| | * | | | | | | | | | | | | * | | | | | | | | | | | | * | +--------+ +------+ +------+ +------+ +--------+ | * | | | | * +-------+------------------------------------------------------+--------+ */ var CompositeLifeCycle = keyMirror({ /** * Components in the process of being mounted respond to state changes * differently. */ MOUNTING: null, /** * Components in the process of being unmounted are guarded against state * changes. */ UNMOUNTING: null, /** * Components that are mounted and receiving new props respond to state * changes differently. */ RECEIVING_PROPS: null, /** * Components that are mounted and receiving new state are guarded against * additional state changes. */ RECEIVING_STATE: null }); /** * @lends {ReactCompositeComponent.prototype} */ var ReactCompositeComponentMixin = { /** * Base constructor for all composite component. * * @param {?object} initialProps * @param {*} children * @final * @internal */ construct: function(initialProps, children) { // Children can be either an array or more than one argument ReactComponent.Mixin.construct.apply(this, arguments); ReactOwner.Mixin.construct.apply(this, arguments); this.state = null; this._pendingState = null; this.context = null; this._currentContext = ReactContext.current; this._pendingContext = null; // The descriptor that was used to instantiate this component. Will be // set by the instantiator instead of the constructor since this // constructor is currently used by both instances and descriptors. this._descriptor = null; this._compositeLifeCycleState = null; }, /** * Components in the intermediate state now has cyclic references. To avoid * breaking JSON serialization we expose a custom JSON format. * @return {object} JSON compatible representation. * @internal * @final */ toJSON: function() { return { type: this.type, props: this.props }; }, /** * Checks whether or not this composite component is mounted. * @return {boolean} True if mounted, false otherwise. * @protected * @final */ isMounted: function() { return ReactComponent.Mixin.isMounted.call(this) && this._compositeLifeCycleState !== CompositeLifeCycle.MOUNTING; }, /** * Initializes the component, renders markup, and registers event listeners. * * @param {string} rootID DOM ID of the root node. * @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction * @param {number} mountDepth number of components in the owner hierarchy * @return {?string} Rendered markup to be inserted into the DOM. * @final * @internal */ mountComponent: ReactPerf.measure( 'ReactCompositeComponent', 'mountComponent', function(rootID, transaction, mountDepth) { ReactComponent.Mixin.mountComponent.call( this, rootID, transaction, mountDepth ); this._compositeLifeCycleState = CompositeLifeCycle.MOUNTING; this.context = this._processContext(this._currentContext); this._defaultProps = this.getDefaultProps ? this.getDefaultProps() : null; this.props = this._processProps(this.props); if (this.__reactAutoBindMap) { this._bindAutoBindMethods(); } this.state = this.getInitialState ? this.getInitialState() : null; ("production" !== "development" ? invariant( typeof this.state === 'object' && !Array.isArray(this.state), '%s.getInitialState(): must return an object or null', this.constructor.displayName || 'ReactCompositeComponent' ) : invariant(typeof this.state === 'object' && !Array.isArray(this.state))); this._pendingState = null; this._pendingForceUpdate = false; if (this.componentWillMount) { this.componentWillMount(); // When mounting, calls to `setState` by `componentWillMount` will set // `this._pendingState` without triggering a re-render. if (this._pendingState) { this.state = this._pendingState; this._pendingState = null; } } this._renderedComponent = instantiateReactComponent( this._renderValidatedComponent() ); // Done with mounting, `setState` will now trigger UI changes. this._compositeLifeCycleState = null; var markup = this._renderedComponent.mountComponent( rootID, transaction, mountDepth + 1 ); if (this.componentDidMount) { transaction.getReactMountReady().enqueue(this, this.componentDidMount); } return markup; } ), /** * Releases any resources allocated by `mountComponent`. * * @final * @internal */ unmountComponent: function() { this._compositeLifeCycleState = CompositeLifeCycle.UNMOUNTING; if (this.componentWillUnmount) { this.componentWillUnmount(); } this._compositeLifeCycleState = null; this._defaultProps = null; this._renderedComponent.unmountComponent(); this._renderedComponent = null; ReactComponent.Mixin.unmountComponent.call(this); // Some existing components rely on this.props even after they've been // destroyed (in event handlers). // TODO: this.props = null; // TODO: this.state = null; }, /** * Sets a subset of the state. Always use this or `replaceState` 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. * * There is no guarantee that calls to `setState` will run synchronously, * as they may eventually be batched together. You can provide an optional * callback that will be executed when the call to setState is actually * completed. * * @param {object} partialState Next partial state to be merged with state. * @param {?function} callback Called after state is updated. * @final * @protected */ setState: function(partialState, callback) { ("production" !== "development" ? invariant( typeof partialState === 'object' || partialState == null, 'setState(...): takes an object of state variables to update.' ) : invariant(typeof partialState === 'object' || partialState == null)); if ("production" !== "development") { ("production" !== "development" ? warning( partialState != null, 'setState(...): You passed an undefined or null state object; ' + 'instead, use forceUpdate().' ) : null); } // Merge with `_pendingState` if it exists, otherwise with existing state. this.replaceState( merge(this._pendingState || this.state, partialState), callback ); }, /** * 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 {object} completeState Next state. * @param {?function} callback Called after state is updated. * @final * @protected */ replaceState: function(completeState, callback) { validateLifeCycleOnReplaceState(this); this._pendingState = completeState; ReactUpdates.enqueueUpdate(this, callback); }, /** * 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 = null; var contextTypes = this.constructor.contextTypes; if (contextTypes) { maskedContext = {}; for (var contextName in contextTypes) { maskedContext[contextName] = context[contextName]; } if ("production" !== "development") { this._checkPropTypes( contextTypes, maskedContext, ReactPropTypeLocations.context ); } } return maskedContext; }, /** * @param {object} currentContext * @return {object} * @private */ _processChildContext: function(currentContext) { var childContext = this.getChildContext && this.getChildContext(); var displayName = this.constructor.displayName || 'ReactCompositeComponent'; if (childContext) { ("production" !== "development" ? invariant( typeof this.constructor.childContextTypes === 'object', '%s.getChildContext(): childContextTypes must be defined in order to ' + 'use getChildContext().', displayName ) : invariant(typeof this.constructor.childContextTypes === 'object')); if ("production" !== "development") { this._checkPropTypes( this.constructor.childContextTypes, childContext, ReactPropTypeLocations.childContext ); } for (var name in childContext) { ("production" !== "development" ? invariant( name in this.constructor.childContextTypes, '%s.getChildContext(): key "%s" is not defined in childContextTypes.', displayName, name ) : invariant(name in this.constructor.childContextTypes)); } return merge(currentContext, childContext); } return currentContext; }, /** * Processes props by setting default values for unspecified props and * asserting that the props are valid. Does not mutate its argument; returns * a new props object with defaults merged in. * * @param {object} newProps * @return {object} * @private */ _processProps: function(newProps) { var props = merge(newProps); var defaultProps = this._defaultProps; for (var propName in defaultProps) { if (typeof props[propName] === 'undefined') { props[propName] = defaultProps[propName]; } } if ("production" !== "development") { var propTypes = this.constructor.propTypes; if (propTypes) { this._checkPropTypes(propTypes, props, ReactPropTypeLocations.prop); } } return props; }, /** * Assert that the props are valid * * @param {object} propTypes Map of prop name to a ReactPropType * @param {object} props * @param {string} location e.g. "prop", "context", "child context" * @private */ _checkPropTypes: function(propTypes, props, location) { var componentName = this.constructor.displayName; for (var propName in propTypes) { if (propTypes.hasOwnProperty(propName)) { propTypes[propName](props, propName, componentName, location); } } }, performUpdateIfNecessary: function() { var compositeLifeCycleState = this._compositeLifeCycleState; // Do not trigger a state transition if we are in the middle of mounting or // receiving props because both of those will already be doing this. if (compositeLifeCycleState === CompositeLifeCycle.MOUNTING || compositeLifeCycleState === CompositeLifeCycle.RECEIVING_PROPS) { return; } ReactComponent.Mixin.performUpdateIfNecessary.call(this); }, /** * If any of `_pendingProps`, `_pendingState`, or `_pendingForceUpdate` is * set, update the component. * * @param {ReactReconcileTransaction} transaction * @internal */ _performUpdateIfNecessary: function(transaction) { if (this._pendingProps == null && this._pendingState == null && this._pendingContext == null && !this._pendingForceUpdate) { return; } var nextFullContext = this._pendingContext || this._currentContext; var nextContext = this._processContext(nextFullContext); this._pendingContext = null; var nextProps = this.props; if (this._pendingProps != null) { nextProps = this._processProps(this._pendingProps); this._pendingProps = null; this._compositeLifeCycleState = CompositeLifeCycle.RECEIVING_PROPS; if (this.componentWillReceiveProps) { this.componentWillReceiveProps(nextProps, nextContext); } } this._compositeLifeCycleState = CompositeLifeCycle.RECEIVING_STATE; // Unlike props, state, and context, we specifically don't want to set // _pendingOwner to null here because it's possible for a component to have // a null owner, so we instead make `this._owner === this._pendingOwner` // mean that there's no owner change pending. var nextOwner = this._pendingOwner; var nextState = this._pendingState || this.state; this._pendingState = null; try { if (this._pendingForceUpdate || !this.shouldComponentUpdate || this.shouldComponentUpdate(nextProps, nextState, nextContext)) { this._pendingForceUpdate = false; // Will set `this.props`, `this.state` and `this.context`. this._performComponentUpdate( nextProps, nextOwner, nextState, nextFullContext, nextContext, transaction ); } else { // If it's determined that a component should not update, we still want // to set props and state. this.props = nextProps; this._owner = nextOwner; this.state = nextState; this._currentContext = nextFullContext; this.context = nextContext; } } finally { this._compositeLifeCycleState = null; } }, /** * Merges new props and state, notifies delegate methods of update and * performs update. * * @param {object} nextProps Next object to set as properties. * @param {?ReactComponent} nextOwner Next component to set as owner * @param {?object} nextState Next object to set as state. * @param {?object} nextFullContext Next object to set as _currentContext. * @param {?object} nextContext Next object to set as context. * @param {ReactReconcileTransaction} transaction * @private */ _performComponentUpdate: function( nextProps, nextOwner, nextState, nextFullContext, nextContext, transaction ) { var prevProps = this.props; var prevOwner = this._owner; var prevState = this.state; var prevContext = this.context; if (this.componentWillUpdate) { this.componentWillUpdate(nextProps, nextState, nextContext); } this.props = nextProps; this._owner = nextOwner; this.state = nextState; this._currentContext = nextFullContext; this.context = nextContext; this.updateComponent( transaction, prevProps, prevOwner, prevState, prevContext ); if (this.componentDidUpdate) { transaction.getReactMountReady().enqueue( this, this.componentDidUpdate.bind(this, prevProps, prevState, prevContext) ); } }, receiveComponent: function(nextComponent, transaction) { if (nextComponent === this._descriptor) { // Since props and context are immutable after the component is // mounted, we can do a cheap identity compare here to determine // if this is a superfluous reconcile. return; } // Update the descriptor that was last used by this component instance this._descriptor = nextComponent; this._pendingContext = nextComponent._currentContext; ReactComponent.Mixin.receiveComponent.call( this, nextComponent, transaction ); }, /** * Updates the component's currently mounted DOM representation. * * By default, this implements React's rendering and reconciliation algorithm. * Sophisticated clients may wish to override this. * * @param {ReactReconcileTransaction} transaction * @param {object} prevProps * @param {?ReactComponent} prevOwner * @param {?object} prevState * @param {?object} prevContext * @internal * @overridable */ updateComponent: ReactPerf.measure( 'ReactCompositeComponent', 'updateComponent', function(transaction, prevProps, prevOwner, prevState, prevContext) { ReactComponent.Mixin.updateComponent.call( this, transaction, prevProps, prevOwner ); var prevComponentInstance = this._renderedComponent; var nextComponent = this._renderValidatedComponent(); if (shouldUpdateReactComponent(prevComponentInstance, nextComponent)) { prevComponentInstance.receiveComponent(nextComponent, transaction); } else { // These two IDs are actually the same! But nothing should rely on that. var thisID = this._rootNodeID; var prevComponentID = prevComponentInstance._rootNodeID; prevComponentInstance.unmountComponent(); this._renderedComponent = instantiateReactComponent(nextComponent); var nextMarkup = this._renderedComponent.mountComponent( thisID, transaction, this._mountDepth + 1 ); ReactComponent.BackendIDOperations.dangerouslyReplaceNodeWithMarkupByID( prevComponentID, nextMarkup ); } } ), /** * 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 `shouldUpdateComponent`, but it will invoke * `componentWillUpdate` and `componentDidUpdate`. * * @param {?function} callback Called after update is complete. * @final * @protected */ forceUpdate: function(callback) { var compositeLifeCycleState = this._compositeLifeCycleState; ("production" !== "development" ? invariant( this.isMounted() || compositeLifeCycleState === CompositeLifeCycle.MOUNTING, 'forceUpdate(...): Can only force an update on mounted or mounting ' + 'components.' ) : invariant(this.isMounted() || compositeLifeCycleState === CompositeLifeCycle.MOUNTING)); ("production" !== "development" ? invariant( compositeLifeCycleState !== CompositeLifeCycle.RECEIVING_STATE && compositeLifeCycleState !== CompositeLifeCycle.UNMOUNTING, 'forceUpdate(...): Cannot force an update while unmounting component ' + 'or during an existing state transition (such as within `render`).' ) : invariant(compositeLifeCycleState !== CompositeLifeCycle.RECEIVING_STATE && compositeLifeCycleState !== CompositeLifeCycle.UNMOUNTING)); this._pendingForceUpdate = true; ReactUpdates.enqueueUpdate(this, callback); }, /** * @private */ _renderValidatedComponent: ReactPerf.measure( 'ReactCompositeComponent', '_renderValidatedComponent', function() { var renderedComponent; var previousContext = ReactContext.current; ReactContext.current = this._processChildContext(this._currentContext); ReactCurrentOwner.current = this; try { renderedComponent = this.render(); } finally { ReactContext.current = previousContext; ReactCurrentOwner.current = null; } ("production" !== "development" ? invariant( ReactComponent.isValidComponent(renderedComponent), '%s.render(): A valid ReactComponent must be returned. You may have ' + 'returned null, undefined, an array, or some other invalid object.', this.constructor.displayName || 'ReactCompositeComponent' ) : invariant(ReactComponent.isValidComponent(renderedComponent))); return renderedComponent; } ), /** * @private */ _bindAutoBindMethods: function() { for (var autoBindKey in this.__reactAutoBindMap) { if (!this.__reactAutoBindMap.hasOwnProperty(autoBindKey)) { continue; } var method = this.__reactAutoBindMap[autoBindKey]; this[autoBindKey] = this._bindAutoBindMethod(ReactErrorUtils.guard( method, this.constructor.displayName + '.' + autoBindKey )); } }, /** * Binds a method to the component. * * @param {function} method Method to be bound. * @private */ _bindAutoBindMethod: function(method) { var component = this; var boundMethod = function() { return method.apply(component, arguments); }; if ("production" !== "development") { boundMethod.__reactBoundContext = component; boundMethod.__reactBoundMethod = method; boundMethod.__reactBoundArguments = null; var componentName = component.constructor.displayName; var _bind = boundMethod.bind; boundMethod.bind = function(newThis ) {var args=Array.prototype.slice.call(arguments,1); // User is trying to bind() an autobound method; we effectively will // ignore the value of "this" that the user is trying to use, so // let's warn. if (newThis !== component && newThis !== null) { monitorCodeUse('react_bind_warning', { component: componentName }); console.warn( 'bind(): React component methods may only be bound to the ' + 'component instance. See ' + componentName ); } else if (!args.length) { monitorCodeUse('react_bind_warning', { component: componentName }); console.warn( 'bind(): You are binding a component method to the component. ' + 'React does this for you automatically in a high-performance ' + 'way, so you can safely remove this call. See ' + componentName ); return boundMethod; } var reboundMethod = _bind.apply(boundMethod, arguments); reboundMethod.__reactBoundContext = component; reboundMethod.__reactBoundMethod = method; reboundMethod.__reactBoundArguments = args; return reboundMethod; }; } return boundMethod; } }; var ReactCompositeComponentBase = function() {}; mixInto(ReactCompositeComponentBase, ReactComponent.Mixin); mixInto(ReactCompositeComponentBase, ReactOwner.Mixin); mixInto(ReactCompositeComponentBase, ReactPropTransferer.Mixin); mixInto(ReactCompositeComponentBase, ReactCompositeComponentMixin); /** * Checks if a value is a valid component constructor. * * @param {*} * @return {boolean} * @public */ function isValidClass(componentClass) { return componentClass instanceof Function && 'componentConstructor' in componentClass && componentClass.componentConstructor instanceof Function; } /** * Module for creating composite components. * * @class ReactCompositeComponent * @extends ReactComponent * @extends ReactOwner * @extends ReactPropTransferer */ var ReactCompositeComponent = { LifeCycle: CompositeLifeCycle, Base: ReactCompositeComponentBase, /** * Creates a composite component class given a class specification. * * @param {object} spec Class specification (which must define `render`). * @return {function} Component constructor function. * @public */ createClass: function(spec) { var Constructor = function() {}; Constructor.prototype = new ReactCompositeComponentBase(); Constructor.prototype.constructor = Constructor; var DescriptorConstructor = Constructor; var ConvenienceConstructor = function(props, children) { var descriptor = new DescriptorConstructor(); descriptor.construct.apply(descriptor, arguments); return descriptor; }; ConvenienceConstructor.componentConstructor = Constructor; Constructor.ConvenienceConstructor = ConvenienceConstructor; ConvenienceConstructor.originalSpec = spec; injectedMixins.forEach( mixSpecIntoComponent.bind(null, ConvenienceConstructor) ); mixSpecIntoComponent(ConvenienceConstructor, spec); ("production" !== "development" ? invariant( Constructor.prototype.render, 'createClass(...): Class specification must implement a `render` method.' ) : invariant(Constructor.prototype.render)); if ("production" !== "development") { if (Constructor.prototype.componentShouldUpdate) { monitorCodeUse( 'react_component_should_update_warning', { component: spec.displayName } ); console.warn( (spec.displayName || 'A component') + ' 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.' ); } } // Expose the convience constructor on the prototype so that it can be // easily accessed on descriptors. E.g. <Foo />.type === Foo.type and for // static methods like <Foo />.type.staticMethod(); // This should not be named constructor since this may not be the function // that created the descriptor, and it may not even be a constructor. ConvenienceConstructor.type = Constructor; Constructor.prototype.type = Constructor; // Reduce time spent doing lookups by setting these on the prototype. for (var methodName in ReactCompositeComponentInterface) { if (!Constructor.prototype[methodName]) { Constructor.prototype[methodName] = null; } } if ("production" !== "development") { // In DEV the convenience constructor generates a proxy to another // instance around it to warn about access to properties on the // descriptor. DescriptorConstructor = createDescriptorProxy(Constructor); } return ConvenienceConstructor; }, isValidClass: isValidClass, injection: { injectMixin: function(mixin) { injectedMixins.push(mixin); } } }; module.exports = ReactCompositeComponent; },{"./ReactComponent":27,"./ReactContext":30,"./ReactCurrentOwner":31,"./ReactErrorUtils":47,"./ReactOwner":59,"./ReactPerf":60,"./ReactPropTransferer":61,"./ReactPropTypeLocationNames":62,"./ReactPropTypeLocations":63,"./ReactUpdates":71,"./instantiateReactComponent":111,"./invariant":112,"./keyMirror":118,"./merge":121,"./mixInto":124,"./monitorCodeUse":125,"./objMap":126,"./shouldUpdateReactComponent":131,"./warning":134}],30:[function(_dereq_,module,exports){ /** * Copyright 2013-2014 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. * * @providesModule ReactContext */ "use strict"; var merge = _dereq_("./merge"); /** * 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: {}, /** * 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) { var result; var previousContext = ReactContext.current; ReactContext.current = merge(previousContext, newContext); try { result = scopedCallback(); } finally { ReactContext.current = previousContext; } return result; } }; module.exports = ReactContext; },{"./merge":121}],31:[function(_dereq_,module,exports){ /** * Copyright 2013-2014 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. * * @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; },{}],32:[function(_dereq_,module,exports){ /** * Copyright 2013-2014 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. * * @providesModule ReactDOM * @typechecks static-only */ "use strict"; var ReactDOMComponent = _dereq_("./ReactDOMComponent"); var mergeInto = _dereq_("./mergeInto"); var objMapKeyVal = _dereq_("./objMapKeyVal"); /** * 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. * * @param {string} tag Tag name (e.g. `div`). * @param {boolean} omitClose True if the close tag should be omitted. * @private */ function createDOMComponentClass(tag, omitClose) { var Constructor = function() {}; Constructor.prototype = new ReactDOMComponent(tag, omitClose); Constructor.prototype.constructor = Constructor; Constructor.displayName = tag; var ConvenienceConstructor = function(props, children) { var instance = new Constructor(); instance.construct.apply(instance, arguments); return instance; }; // Expose the constructor on the ConvenienceConstructor and prototype so that // it can be easily easily accessed on descriptors. // E.g. <div />.type === div.type ConvenienceConstructor.type = Constructor; Constructor.prototype.type = Constructor; Constructor.ConvenienceConstructor = ConvenienceConstructor; ConvenienceConstructor.componentConstructor = Constructor; return ConvenienceConstructor; } /** * Creates a mapping from supported HTML tags to `ReactDOMComponent` classes. * This is also accessible via `React.DOM`. * * @public */ var ReactDOM = objMapKeyVal({ a: false, abbr: false, address: false, area: true, article: false, aside: false, audio: false, b: false, base: true, bdi: false, bdo: false, big: false, blockquote: false, body: false, br: true, button: false, canvas: false, caption: false, cite: false, code: false, col: true, colgroup: false, data: false, datalist: false, dd: false, del: false, details: false, dfn: false, div: false, dl: false, dt: false, em: false, embed: true, fieldset: false, figcaption: false, figure: false, footer: false, form: false, // NOTE: Injected, see `ReactDOMForm`. h1: false, h2: false, h3: false, h4: false, h5: false, h6: false, head: false, header: false, hr: true, html: false, i: false, iframe: false, img: true, input: true, ins: false, kbd: false, keygen: true, label: false, legend: false, li: false, link: true, main: false, map: false, mark: false, menu: false, menuitem: false, // NOTE: Close tag should be omitted, but causes problems. meta: true, meter: false, nav: false, noscript: false, object: false, ol: false, optgroup: false, option: false, output: false, p: false, param: true, pre: false, progress: false, q: false, rp: false, rt: false, ruby: false, s: false, samp: false, script: false, section: false, select: false, small: false, source: true, span: false, strong: false, style: false, sub: false, summary: false, sup: false, table: false, tbody: false, td: false, textarea: false, // NOTE: Injected, see `ReactDOMTextarea`. tfoot: false, th: false, thead: false, time: false, title: false, tr: false, track: true, u: false, ul: false, 'var': false, video: false, wbr: true, // SVG circle: false, defs: false, g: false, line: false, linearGradient: false, path: false, polygon: false, polyline: false, radialGradient: false, rect: false, stop: false, svg: false, text: false }, createDOMComponentClass); var injection = { injectComponentClasses: function(componentClasses) { mergeInto(ReactDOM, componentClasses); } }; ReactDOM.injection = injection; module.exports = ReactDOM; },{"./ReactDOMComponent":34,"./mergeInto":123,"./objMapKeyVal":127}],33:[function(_dereq_,module,exports){ /** * Copyright 2013-2014 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. * * @providesModule ReactDOMButton */ "use strict"; var AutoFocusMixin = _dereq_("./AutoFocusMixin"); var ReactBrowserComponentMixin = _dereq_("./ReactBrowserComponentMixin"); var ReactCompositeComponent = _dereq_("./ReactCompositeComponent"); var ReactDOM = _dereq_("./ReactDOM"); var keyMirror = _dereq_("./keyMirror"); // Store a reference to the <button> `ReactDOMComponent`. var button = ReactDOM.button; var mouseListenerNames = keyMirror({ onClick: true, onDoubleClick: true, onMouseDown: true, onMouseMove: true, onMouseUp: true, onClickCapture: true, onDoubleClickCapture: true, onMouseDownCapture: true, onMouseMoveCapture: true, onMouseUpCapture: true }); /** * Implements a <button> native component that does not receive mouse events * when `disabled` is set. */ var ReactDOMButton = ReactCompositeComponent.createClass({ displayName: 'ReactDOMButton', mixins: [AutoFocusMixin, ReactBrowserComponentMixin], render: function() { var props = {}; // Copy the props; except the mouse listeners if we're disabled for (var key in this.props) { if (this.props.hasOwnProperty(key) && (!this.props.disabled || !mouseListenerNames[key])) { props[key] = this.props[key]; } } return button(props, this.props.children); } }); module.exports = ReactDOMButton; },{"./AutoFocusMixin":1,"./ReactBrowserComponentMixin":25,"./ReactCompositeComponent":29,"./ReactDOM":32,"./keyMirror":118}],34:[function(_dereq_,module,exports){ /** * Copyright 2013-2014 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. * * @providesModule ReactDOMComponent * @typechecks static-only */ "use strict"; var CSSPropertyOperations = _dereq_("./CSSPropertyOperations"); var DOMProperty = _dereq_("./DOMProperty"); var DOMPropertyOperations = _dereq_("./DOMPropertyOperations"); var ReactBrowserComponentMixin = _dereq_("./ReactBrowserComponentMixin"); var ReactComponent = _dereq_("./ReactComponent"); var ReactEventEmitter = _dereq_("./ReactEventEmitter"); var ReactMount = _dereq_("./ReactMount"); var ReactMultiChild = _dereq_("./ReactMultiChild"); var ReactPerf = _dereq_("./ReactPerf"); var escapeTextForBrowser = _dereq_("./escapeTextForBrowser"); var invariant = _dereq_("./invariant"); var keyOf = _dereq_("./keyOf"); var merge = _dereq_("./merge"); var mixInto = _dereq_("./mixInto"); var deleteListener = ReactEventEmitter.deleteListener; var listenTo = ReactEventEmitter.listenTo; var registrationNameModules = ReactEventEmitter.registrationNameModules; // For quickly matching children type, to test if can be treated as content. var CONTENT_TYPES = {'string': true, 'number': true}; var STYLE = keyOf({style: null}); var ELEMENT_NODE_TYPE = 1; /** * @param {?object} props */ function assertValidProps(props) { if (!props) { return; } // Note the use of `==` which checks for null or undefined. ("production" !== "development" ? invariant( props.children == null || props.dangerouslySetInnerHTML == null, 'Can only set one of `children` or `props.dangerouslySetInnerHTML`.' ) : invariant(props.children == null || props.dangerouslySetInnerHTML == null)); ("production" !== "development" ? invariant( props.style == null || typeof props.style === 'object', 'The `style` prop expects a mapping from style properties to values, ' + 'not a string.' ) : invariant(props.style == null || typeof props.style === 'object')); } function putListener(id, registrationName, listener, transaction) { var container = ReactMount.findReactContainerForID(id); if (container) { var doc = container.nodeType === ELEMENT_NODE_TYPE ? container.ownerDocument : container; listenTo(registrationName, doc); } transaction.getPutListenerQueue().enqueuePutListener( id, registrationName, listener ); } /** * @constructor ReactDOMComponent * @extends ReactComponent * @extends ReactMultiChild */ function ReactDOMComponent(tag, omitClose) { this._tagOpen = '<' + tag; this._tagClose = omitClose ? '' : '</' + tag + '>'; this.tagName = tag.toUpperCase(); } ReactDOMComponent.Mixin = { /** * Generates root tag markup then recurses. This method has side effects and * is not idempotent. * * @internal * @param {string} rootID The root DOM ID for this node. * @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction * @param {number} mountDepth number of components in the owner hierarchy * @return {string} The computed markup. */ mountComponent: ReactPerf.measure( 'ReactDOMComponent', 'mountComponent', function(rootID, transaction, mountDepth) { ReactComponent.Mixin.mountComponent.call( this, rootID, transaction, mountDepth ); assertValidProps(this.props); return ( this._createOpenTagMarkupAndPutListeners(transaction) + this._createContentMarkup(transaction) + this._tagClose ); } ), /** * 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 * @return {string} Markup of opening tag. */ _createOpenTagMarkupAndPutListeners: function(transaction) { var props = this.props; var ret = this._tagOpen; for (var propKey in props) { if (!props.hasOwnProperty(propKey)) { continue; } var propValue = props[propKey]; if (propValue == null) { continue; } if (registrationNameModules[propKey]) { putListener(this._rootNodeID, propKey, propValue, transaction); } else { if (propKey === STYLE) { if (propValue) { propValue = props.style = merge(props.style); } propValue = CSSPropertyOperations.createMarkupForStyles(propValue); } var 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 + '>'; } var markupForID = DOMPropertyOperations.createMarkupForID(this._rootNodeID); return ret + ' ' + markupForID + '>'; }, /** * Creates markup for the content between the tags. * * @private * @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction * @return {string} Content markup. */ _createContentMarkup: function(transaction) { // Intentional use of != to avoid catching zero/false. var innerHTML = this.props.dangerouslySetInnerHTML; if (innerHTML != null) { if (innerHTML.__html != null) { return innerHTML.__html; } } else { var contentToUse = CONTENT_TYPES[typeof this.props.children] ? this.props.children : null; var childrenToUse = contentToUse != null ? null : this.props.children; if (contentToUse != null) { return escapeTextForBrowser(contentToUse); } else if (childrenToUse != null) { var mountImages = this.mountChildren( childrenToUse, transaction ); return mountImages.join(''); } } return ''; }, receiveComponent: function(nextComponent, transaction) { if (nextComponent === this) { // Since props and context are immutable after the component is // mounted, we can do a cheap identity compare here to determine // if this is a superfluous reconcile. // TODO: compare the descriptor return; } assertValidProps(nextComponent.props); ReactComponent.Mixin.receiveComponent.call( this, nextComponent, transaction ); }, /** * Updates a native DOM component after it has already been allocated and * attached to the DOM. Reconciles the root DOM node, then recurses. * * @param {ReactReconcileTransaction} transaction * @param {object} prevProps * @internal * @overridable */ updateComponent: ReactPerf.measure( 'ReactDOMComponent', 'updateComponent', function(transaction, prevProps, prevOwner) { ReactComponent.Mixin.updateComponent.call( this, transaction, prevProps, prevOwner ); this._updateDOMProperties(prevProps, transaction); this._updateDOMChildren(prevProps, transaction); } ), /** * 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 {ReactReconcileTransaction} transaction */ _updateDOMProperties: function(lastProps, transaction) { var nextProps = this.props; var propKey; var styleName; var styleUpdates; for (propKey in lastProps) { if (nextProps.hasOwnProperty(propKey) || !lastProps.hasOwnProperty(propKey)) { continue; } if (propKey === STYLE) { var lastStyle = lastProps[propKey]; for (styleName in lastStyle) { if (lastStyle.hasOwnProperty(styleName)) { styleUpdates = styleUpdates || {}; styleUpdates[styleName] = ''; } } } else if (registrationNameModules[propKey]) { deleteListener(this._rootNodeID, propKey); } else if ( DOMProperty.isStandardName[propKey] || DOMProperty.isCustomAttribute(propKey)) { ReactComponent.BackendIDOperations.deletePropertyByID( this._rootNodeID, propKey ); } } for (propKey in nextProps) { var nextProp = nextProps[propKey]; var lastProp = lastProps[propKey]; if (!nextProps.hasOwnProperty(propKey) || nextProp === lastProp) { continue; } if (propKey === STYLE) { if (nextProp) { nextProp = nextProps.style = merge(nextProp); } if (lastProp) { // Unset styles on `lastProp` but not on `nextProp`. for (styleName in lastProp) { if (lastProp.hasOwnProperty(styleName) && !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[propKey]) { putListener(this._rootNodeID, propKey, nextProp, transaction); } else if ( DOMProperty.isStandardName[propKey] || DOMProperty.isCustomAttribute(propKey)) { ReactComponent.BackendIDOperations.updatePropertyByID( this._rootNodeID, propKey, nextProp ); } } if (styleUpdates) { ReactComponent.BackendIDOperations.updateStylesByID( this._rootNodeID, styleUpdates ); } }, /** * Reconciles the children with the various properties that affect the * children content. * * @param {object} lastProps * @param {ReactReconcileTransaction} transaction */ _updateDOMChildren: function(lastProps, transaction) { var nextProps = this.props; 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); } else if (lastHasContentOrHtml && !nextHasContentOrHtml) { this.updateTextContent(''); } if (nextContent != null) { if (lastContent !== nextContent) { this.updateTextContent('' + nextContent); } } else if (nextHtml != null) { if (lastHtml !== nextHtml) { ReactComponent.BackendIDOperations.updateInnerHTMLByID( this._rootNodeID, nextHtml ); } } else if (nextChildren != null) { this.updateChildren(nextChildren, transaction); } }, /** * Destroys all event registrations for this instance. Does not remove from * the DOM. That must be done by the parent. * * @internal */ unmountComponent: function() { this.unmountChildren(); ReactEventEmitter.deleteAllListeners(this._rootNodeID); ReactComponent.Mixin.unmountComponent.call(this); } }; mixInto(ReactDOMComponent, ReactComponent.Mixin); mixInto(ReactDOMComponent, ReactDOMComponent.Mixin); mixInto(ReactDOMComponent, ReactMultiChild.Mixin); mixInto(ReactDOMComponent, ReactBrowserComponentMixin); module.exports = ReactDOMComponent; },{"./CSSPropertyOperations":3,"./DOMProperty":8,"./DOMPropertyOperations":9,"./ReactBrowserComponentMixin":25,"./ReactComponent":27,"./ReactEventEmitter":48,"./ReactMount":55,"./ReactMultiChild":57,"./ReactPerf":60,"./escapeTextForBrowser":98,"./invariant":112,"./keyOf":119,"./merge":121,"./mixInto":124}],35:[function(_dereq_,module,exports){ /** * Copyright 2013-2014 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. * * @providesModule ReactDOMForm */ "use strict"; var ReactBrowserComponentMixin = _dereq_("./ReactBrowserComponentMixin"); var ReactCompositeComponent = _dereq_("./ReactCompositeComponent"); var ReactDOM = _dereq_("./ReactDOM"); var ReactEventEmitter = _dereq_("./ReactEventEmitter"); var EventConstants = _dereq_("./EventConstants"); // Store a reference to the <form> `ReactDOMComponent`. var form = ReactDOM.form; /** * Since onSubmit doesn't bubble OR capture on the top level in IE8, we need * to capture it on the <form> element itself. There are lots of hacks we could * do to accomplish this, but the most reliable is to make <form> a * composite component and use `componentDidMount` to attach the event handlers. */ var ReactDOMForm = ReactCompositeComponent.createClass({ displayName: 'ReactDOMForm', mixins: [ReactBrowserComponentMixin], render: function() { // TODO: Instead of using `ReactDOM` directly, we should use JSX. However, // `jshint` fails to parse JSX so in order for linting to work in the open // source repo, we need to just use `ReactDOM.form`. return this.transferPropsTo(form(null, this.props.children)); }, componentDidMount: function() { ReactEventEmitter.trapBubbledEvent( EventConstants.topLevelTypes.topReset, 'reset', this.getDOMNode() ); ReactEventEmitter.trapBubbledEvent( EventConstants.topLevelTypes.topSubmit, 'submit', this.getDOMNode() ); } }); module.exports = ReactDOMForm; },{"./EventConstants":14,"./ReactBrowserComponentMixin":25,"./ReactCompositeComponent":29,"./ReactDOM":32,"./ReactEventEmitter":48}],36:[function(_dereq_,module,exports){ /** * Copyright 2013-2014 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. * * @providesModule ReactDOMIDOperations * @typechecks static-only */ /*jslint evil: true */ "use strict"; var CSSPropertyOperations = _dereq_("./CSSPropertyOperations"); var DOMChildrenOperations = _dereq_("./DOMChildrenOperations"); var DOMPropertyOperations = _dereq_("./DOMPropertyOperations"); var ReactMount = _dereq_("./ReactMount"); var ReactPerf = _dereq_("./ReactPerf"); var invariant = _dereq_("./invariant"); /** * Errors for properties that should not be updated with `updatePropertyById()`. * * @type {object} * @private */ var INVALID_PROPERTY_ERRORS = { dangerouslySetInnerHTML: '`dangerouslySetInnerHTML` must be set using `updateInnerHTMLByID()`.', style: '`style` must be set using `updateStylesByID()`.' }; var useWhitespaceWorkaround; /** * Operations used to process updates to DOM nodes. This is made injectable via * `ReactComponent.BackendIDOperations`. */ var ReactDOMIDOperations = { /** * Updates a DOM node with new property values. This should only be used to * update DOM properties in `DOMProperty`. * * @param {string} id ID of the node to update. * @param {string} name A valid property name, see `DOMProperty`. * @param {*} value New value of the property. * @internal */ updatePropertyByID: ReactPerf.measure( 'ReactDOMIDOperations', 'updatePropertyByID', function(id, name, value) { var node = ReactMount.getNode(id); ("production" !== "development" ? invariant( !INVALID_PROPERTY_ERRORS.hasOwnProperty(name), 'updatePropertyByID(...): %s', INVALID_PROPERTY_ERRORS[name] ) : invariant(!INVALID_PROPERTY_ERRORS.hasOwnProperty(name))); // If we're updating to null or undefined, we should remove the property // from the DOM node instead of inadvertantly setting to a string. This // brings us in line with the same behavior we have on initial render. if (value != null) { DOMPropertyOperations.setValueForProperty(node, name, value); } else { DOMPropertyOperations.deleteValueForProperty(node, name); } } ), /** * Updates a DOM node to remove a property. This should only be used to remove * DOM properties in `DOMProperty`. * * @param {string} id ID of the node to update. * @param {string} name A property name to remove, see `DOMProperty`. * @internal */ deletePropertyByID: ReactPerf.measure( 'ReactDOMIDOperations', 'deletePropertyByID', function(id, name, value) { var node = ReactMount.getNode(id); ("production" !== "development" ? invariant( !INVALID_PROPERTY_ERRORS.hasOwnProperty(name), 'updatePropertyByID(...): %s', INVALID_PROPERTY_ERRORS[name] ) : invariant(!INVALID_PROPERTY_ERRORS.hasOwnProperty(name))); DOMPropertyOperations.deleteValueForProperty(node, name, value); } ), /** * Updates a DOM node with new style values. If a value is specified as '', * the corresponding style property will be unset. * * @param {string} id ID of the node to update. * @param {object} styles Mapping from styles to values. * @internal */ updateStylesByID: ReactPerf.measure( 'ReactDOMIDOperations', 'updateStylesByID', function(id, styles) { var node = ReactMount.getNode(id); CSSPropertyOperations.setValueForStyles(node, styles); } ), /** * Updates a DOM node's innerHTML. * * @param {string} id ID of the node to update. * @param {string} html An HTML string. * @internal */ updateInnerHTMLByID: ReactPerf.measure( 'ReactDOMIDOperations', 'updateInnerHTMLByID', function(id, html) { var node = ReactMount.getNode(id); // 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 if (useWhitespaceWorkaround === undefined) { // Feature detection; only IE8 is known to behave improperly like this. var temp = document.createElement('div'); temp.innerHTML = ' '; useWhitespaceWorkaround = temp.innerHTML === ''; } if (useWhitespaceWorkaround) { // 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. node.parentNode.replaceChild(node, node); } if (useWhitespaceWorkaround && html.match(/^[ \r\n\t\f]/)) { // Recover leading whitespace by temporarily prepending any character. // \uFEFF has the potential advantage of being zero-width/invisible. node.innerHTML = '\uFEFF' + html; node.firstChild.deleteData(0, 1); } else { node.innerHTML = html; } } ), /** * Updates a DOM node's text content set by `props.content`. * * @param {string} id ID of the node to update. * @param {string} content Text content. * @internal */ updateTextContentByID: ReactPerf.measure( 'ReactDOMIDOperations', 'updateTextContentByID', function(id, content) { var node = ReactMount.getNode(id); DOMChildrenOperations.updateTextContent(node, content); } ), /** * Replaces a DOM node that exists in the document with markup. * * @param {string} id ID of child to be replaced. * @param {string} markup Dangerous markup to inject in place of child. * @internal * @see {Danger.dangerouslyReplaceNodeWithMarkup} */ dangerouslyReplaceNodeWithMarkupByID: ReactPerf.measure( 'ReactDOMIDOperations', 'dangerouslyReplaceNodeWithMarkupByID', function(id, markup) { var node = ReactMount.getNode(id); DOMChildrenOperations.dangerouslyReplaceNodeWithMarkup(node, markup); } ), /** * Updates a component's children by processing a series of updates. * * @param {array<object>} updates List of update configurations. * @param {array<string>} markup List of markup strings. * @internal */ dangerouslyProcessChildrenUpdates: ReactPerf.measure( 'ReactDOMIDOperations', 'dangerouslyProcessChildrenUpdates', function(updates, markup) { for (var i = 0; i < updates.length; i++) { updates[i].parentNode = ReactMount.getNode(updates[i].parentID); } DOMChildrenOperations.processUpdates(updates, markup); } ) }; module.exports = ReactDOMIDOperations; },{"./CSSPropertyOperations":3,"./DOMChildrenOperations":7,"./DOMPropertyOperations":9,"./ReactMount":55,"./ReactPerf":60,"./invariant":112}],37:[function(_dereq_,module,exports){ /** * Copyright 2013-2014 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. * * @providesModule ReactDOMImg */ "use strict"; var ReactBrowserComponentMixin = _dereq_("./ReactBrowserComponentMixin"); var ReactCompositeComponent = _dereq_("./ReactCompositeComponent"); var ReactDOM = _dereq_("./ReactDOM"); var ReactEventEmitter = _dereq_("./ReactEventEmitter"); var EventConstants = _dereq_("./EventConstants"); // Store a reference to the <img> `ReactDOMComponent`. var img = ReactDOM.img; /** * Since onLoad doesn't bubble OR capture on the top level in IE8, we need to * capture it on the <img> element itself. There are lots of hacks we could do * to accomplish this, but the most reliable is to make <img> a composite * component and use `componentDidMount` to attach the event handlers. */ var ReactDOMImg = ReactCompositeComponent.createClass({ displayName: 'ReactDOMImg', tagName: 'IMG', mixins: [ReactBrowserComponentMixin], render: function() { return img(this.props); }, componentDidMount: function() { var node = this.getDOMNode(); ReactEventEmitter.trapBubbledEvent( EventConstants.topLevelTypes.topLoad, 'load', node ); ReactEventEmitter.trapBubbledEvent( EventConstants.topLevelTypes.topError, 'error', node ); } }); module.exports = ReactDOMImg; },{"./EventConstants":14,"./ReactBrowserComponentMixin":25,"./ReactCompositeComponent":29,"./ReactDOM":32,"./ReactEventEmitter":48}],38:[function(_dereq_,module,exports){ /** * Copyright 2013-2014 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. * * @providesModule ReactDOMInput */ "use strict"; var AutoFocusMixin = _dereq_("./AutoFocusMixin"); var DOMPropertyOperations = _dereq_("./DOMPropertyOperations"); var LinkedValueUtils = _dereq_("./LinkedValueUtils"); var ReactBrowserComponentMixin = _dereq_("./ReactBrowserComponentMixin"); var ReactCompositeComponent = _dereq_("./ReactCompositeComponent"); var ReactDOM = _dereq_("./ReactDOM"); var ReactMount = _dereq_("./ReactMount"); var invariant = _dereq_("./invariant"); var merge = _dereq_("./merge"); // Store a reference to the <input> `ReactDOMComponent`. var input = ReactDOM.input; var instancesByReactID = {}; /** * Implements an <input> native 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 = ReactCompositeComponent.createClass({ displayName: 'ReactDOMInput', mixins: [AutoFocusMixin, LinkedValueUtils.Mixin, ReactBrowserComponentMixin], getInitialState: function() { var defaultValue = this.props.defaultValue; return { checked: this.props.defaultChecked || false, value: defaultValue != null ? defaultValue : null }; }, shouldComponentUpdate: function() { // Defer any updates to this component during the `onChange` handler. return !this._isChanging; }, render: function() { // Clone `this.props` so we don't mutate the input. var props = merge(this.props); props.defaultChecked = null; props.defaultValue = null; var value = LinkedValueUtils.getValue(this); props.value = value != null ? value : this.state.value; var checked = LinkedValueUtils.getChecked(this); props.checked = checked != null ? checked : this.state.checked; props.onChange = this._handleChange; return input(props, this.props.children); }, componentDidMount: function() { var id = ReactMount.getID(this.getDOMNode()); instancesByReactID[id] = this; }, componentWillUnmount: function() { var rootNode = this.getDOMNode(); var id = ReactMount.getID(rootNode); delete instancesByReactID[id]; }, componentDidUpdate: function(prevProps, prevState, prevContext) { var rootNode = this.getDOMNode(); if (this.props.checked != null) { DOMPropertyOperations.setValueForProperty( rootNode, 'checked', this.props.checked || false ); } var value = LinkedValueUtils.getValue(this); 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. DOMPropertyOperations.setValueForProperty(rootNode, 'value', '' + value); } }, _handleChange: function(event) { var returnValue; var onChange = LinkedValueUtils.getOnChange(this); if (onChange) { this._isChanging = true; returnValue = onChange.call(this, event); this._isChanging = false; } this.setState({ checked: event.target.checked, value: event.target.value }); var name = this.props.name; if (this.props.type === 'radio' && name != null) { var rootNode = this.getDOMNode(); 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, let's just use the global // `querySelectorAll` to ensure we don't miss anything. var group = queryRoot.querySelectorAll( 'input[name=' + JSON.stringify('' + name) + '][type="radio"]'); for (var i = 0, groupLen = group.length; i < groupLen; i++) { var otherNode = group[i]; if (otherNode === rootNode || otherNode.form !== rootNode.form) { continue; } var otherID = ReactMount.getID(otherNode); ("production" !== "development" ? invariant( otherID, 'ReactDOMInput: Mixing React and non-React radio inputs with the ' + 'same `name` is not supported.' ) : invariant(otherID)); var otherInstance = instancesByReactID[otherID]; ("production" !== "development" ? invariant( otherInstance, 'ReactDOMInput: Unknown radio button ID %s.', otherID ) : invariant(otherInstance)); // In some cases, this will actually change the `checked` state value. // In other cases, there's no change but this forces a reconcile upon // which componentDidUpdate will reset the DOM property to whatever it // should be. otherInstance.setState({ checked: false }); } } return returnValue; } }); module.exports = ReactDOMInput; },{"./AutoFocusMixin":1,"./DOMPropertyOperations":9,"./LinkedValueUtils":21,"./ReactBrowserComponentMixin":25,"./ReactCompositeComponent":29,"./ReactDOM":32,"./ReactMount":55,"./invariant":112,"./merge":121}],39:[function(_dereq_,module,exports){ /** * Copyright 2013-2014 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. * * @providesModule ReactDOMOption */ "use strict"; var ReactBrowserComponentMixin = _dereq_("./ReactBrowserComponentMixin"); var ReactCompositeComponent = _dereq_("./ReactCompositeComponent"); var ReactDOM = _dereq_("./ReactDOM"); var warning = _dereq_("./warning"); // Store a reference to the <option> `ReactDOMComponent`. var option = ReactDOM.option; /** * Implements an <option> native component that warns when `selected` is set. */ var ReactDOMOption = ReactCompositeComponent.createClass({ displayName: 'ReactDOMOption', mixins: [ReactBrowserComponentMixin], componentWillMount: function() { // TODO (yungsters): Remove support for `selected` in <option>. if ("production" !== "development") { ("production" !== "development" ? warning( this.props.selected == null, 'Use the `defaultValue` or `value` props on <select> instead of ' + 'setting `selected` on <option>.' ) : null); } }, render: function() { return option(this.props, this.props.children); } }); module.exports = ReactDOMOption; },{"./ReactBrowserComponentMixin":25,"./ReactCompositeComponent":29,"./ReactDOM":32,"./warning":134}],40:[function(_dereq_,module,exports){ /** * Copyright 2013-2014 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. * * @providesModule ReactDOMSelect */ "use strict"; var AutoFocusMixin = _dereq_("./AutoFocusMixin"); var LinkedValueUtils = _dereq_("./LinkedValueUtils"); var ReactBrowserComponentMixin = _dereq_("./ReactBrowserComponentMixin"); var ReactCompositeComponent = _dereq_("./ReactCompositeComponent"); var ReactDOM = _dereq_("./ReactDOM"); var invariant = _dereq_("./invariant"); var merge = _dereq_("./merge"); // Store a reference to the <select> `ReactDOMComponent`. var select = ReactDOM.select; /** * Validation function for `value` and `defaultValue`. * @private */ function selectValueType(props, propName, componentName) { if (props[propName] == null) { return; } if (props.multiple) { ("production" !== "development" ? invariant( Array.isArray(props[propName]), 'The `%s` prop supplied to <select> must be an array if `multiple` is ' + 'true.', propName ) : invariant(Array.isArray(props[propName]))); } else { ("production" !== "development" ? invariant( !Array.isArray(props[propName]), 'The `%s` prop supplied to <select> must be a scalar value if ' + '`multiple` is false.', propName ) : invariant(!Array.isArray(props[propName]))); } } /** * If `value` is supplied, updates <option> elements on mount and update. * @param {ReactComponent} component Instance of ReactDOMSelect * @param {?*} propValue For uncontrolled components, null/undefined. For * controlled components, a string (or with `multiple`, a list of strings). * @private */ function updateOptions(component, propValue) { var multiple = component.props.multiple; var value = propValue != null ? propValue : component.state.value; var options = component.getDOMNode().options; var selectedValue, i, l; if (multiple) { selectedValue = {}; for (i = 0, l = value.length; i < l; ++i) { selectedValue['' + value[i]] = true; } } else { selectedValue = '' + value; } for (i = 0, l = options.length; i < l; i++) { var selected = multiple ? selectedValue.hasOwnProperty(options[i].value) : options[i].value === selectedValue; if (selected !== options[i].selected) { options[i].selected = selected; } } } /** * Implements a <select> native component that allows optionally setting the * props `value` and `defaultValue`. If `multiple` is false, the prop must be a * string. If `multiple` is true, the prop must be an array of strings. * * 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 = ReactCompositeComponent.createClass({ displayName: 'ReactDOMSelect', mixins: [AutoFocusMixin, LinkedValueUtils.Mixin, ReactBrowserComponentMixin], propTypes: { defaultValue: selectValueType, value: selectValueType }, getInitialState: function() { return {value: this.props.defaultValue || (this.props.multiple ? [] : '')}; }, componentWillReceiveProps: function(nextProps) { if (!this.props.multiple && nextProps.multiple) { this.setState({value: [this.state.value]}); } else if (this.props.multiple && !nextProps.multiple) { this.setState({value: this.state.value[0]}); } }, shouldComponentUpdate: function() { // Defer any updates to this component during the `onChange` handler. return !this._isChanging; }, render: function() { // Clone `this.props` so we don't mutate the input. var props = merge(this.props); props.onChange = this._handleChange; props.value = null; return select(props, this.props.children); }, componentDidMount: function() { updateOptions(this, LinkedValueUtils.getValue(this)); }, componentDidUpdate: function() { var value = LinkedValueUtils.getValue(this); if (value != null) { updateOptions(this, value); } }, _handleChange: function(event) { var returnValue; var onChange = LinkedValueUtils.getOnChange(this); if (onChange) { this._isChanging = true; returnValue = onChange.call(this, event); this._isChanging = false; } var selectedValue; if (this.props.multiple) { selectedValue = []; var options = event.target.options; for (var i = 0, l = options.length; i < l; i++) { if (options[i].selected) { selectedValue.push(options[i].value); } } } else { selectedValue = event.target.value; } this.setState({value: selectedValue}); return returnValue; } }); module.exports = ReactDOMSelect; },{"./AutoFocusMixin":1,"./LinkedValueUtils":21,"./ReactBrowserComponentMixin":25,"./ReactCompositeComponent":29,"./ReactDOM":32,"./invariant":112,"./merge":121}],41:[function(_dereq_,module,exports){ /** * Copyright 2013-2014 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. * * @providesModule ReactDOMSelection */ "use strict"; var getNodeForCharacterOffset = _dereq_("./getNodeForCharacterOffset"); var getTextContentAccessor = _dereq_("./getTextContentAccessor"); /** * 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(); if (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); var rangeLength = currentRange.toString().length; var tempRange = currentRange.cloneRange(); tempRange.selectNodeContents(node); tempRange.setEnd(currentRange.startContainer, currentRange.startOffset); var start = 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; detectionRange.detach(); 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 (typeof 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 programatically 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) { var selection = window.getSelection(); var length = node[getTextContentAccessor()].length; var start = Math.min(offsets.start, length); var end = typeof 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); } range.detach(); } } var ReactDOMSelection = { /** * @param {DOMElement} node */ getOffsets: function(node) { var getOffsets = document.selection ? getIEOffsets : getModernOffsets; return getOffsets(node); }, /** * @param {DOMElement|DOMTextNode} node * @param {object} offsets */ setOffsets: function(node, offsets) { var setOffsets = document.selection ? setIEOffsets : setModernOffsets; setOffsets(node, offsets); } }; module.exports = ReactDOMSelection; },{"./getNodeForCharacterOffset":106,"./getTextContentAccessor":108}],42:[function(_dereq_,module,exports){ /** * Copyright 2013-2014 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. * * @providesModule ReactDOMTextarea */ "use strict"; var AutoFocusMixin = _dereq_("./AutoFocusMixin"); var DOMPropertyOperations = _dereq_("./DOMPropertyOperations"); var LinkedValueUtils = _dereq_("./LinkedValueUtils"); var ReactBrowserComponentMixin = _dereq_("./ReactBrowserComponentMixin"); var ReactCompositeComponent = _dereq_("./ReactCompositeComponent"); var ReactDOM = _dereq_("./ReactDOM"); var invariant = _dereq_("./invariant"); var merge = _dereq_("./merge"); var warning = _dereq_("./warning"); // Store a reference to the <textarea> `ReactDOMComponent`. var textarea = ReactDOM.textarea; /** * Implements a <textarea> native 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 = ReactCompositeComponent.createClass({ displayName: 'ReactDOMTextarea', mixins: [AutoFocusMixin, LinkedValueUtils.Mixin, ReactBrowserComponentMixin], getInitialState: function() { var defaultValue = this.props.defaultValue; // TODO (yungsters): Remove support for children content in <textarea>. var children = this.props.children; if (children != null) { if ("production" !== "development") { ("production" !== "development" ? warning( false, 'Use the `defaultValue` or `value` props instead of setting ' + 'children on <textarea>.' ) : null); } ("production" !== "development" ? invariant( defaultValue == null, 'If you supply `defaultValue` on a <textarea>, do not pass children.' ) : invariant(defaultValue == null)); if (Array.isArray(children)) { ("production" !== "development" ? invariant( children.length <= 1, '<textarea> can only have at most one child.' ) : invariant(children.length <= 1)); children = children[0]; } defaultValue = '' + children; } if (defaultValue == null) { defaultValue = ''; } var value = LinkedValueUtils.getValue(this); return { // We save the initial value so that `ReactDOMComponent` doesn't update // `textContent` (unnecessary since we update value). // The initial value can be a boolean or object so that's why it's // forced to be a string. initialValue: '' + (value != null ? value : defaultValue), value: defaultValue }; }, shouldComponentUpdate: function() { // Defer any updates to this component during the `onChange` handler. return !this._isChanging; }, render: function() { // Clone `this.props` so we don't mutate the input. var props = merge(this.props); var value = LinkedValueUtils.getValue(this); ("production" !== "development" ? invariant( props.dangerouslySetInnerHTML == null, '`dangerouslySetInnerHTML` does not make sense on <textarea>.' ) : invariant(props.dangerouslySetInnerHTML == null)); props.defaultValue = null; props.value = value != null ? value : this.state.value; props.onChange = this._handleChange; // Always set children to the same thing. In IE9, the selection range will // get reset if `textContent` is mutated. return textarea(props, this.state.initialValue); }, componentDidUpdate: function(prevProps, prevState, prevContext) { var value = LinkedValueUtils.getValue(this); if (value != null) { var rootNode = this.getDOMNode(); // Cast `value` to a string to ensure the value is set correctly. While // browsers typically do this as necessary, jsdom doesn't. DOMPropertyOperations.setValueForProperty(rootNode, 'value', '' + value); } }, _handleChange: function(event) { var returnValue; var onChange = LinkedValueUtils.getOnChange(this); if (onChange) { this._isChanging = true; returnValue = onChange.call(this, event); this._isChanging = false; } this.setState({value: event.target.value}); return returnValue; } }); module.exports = ReactDOMTextarea; },{"./AutoFocusMixin":1,"./DOMPropertyOperations":9,"./LinkedValueUtils":21,"./ReactBrowserComponentMixin":25,"./ReactCompositeComponent":29,"./ReactDOM":32,"./invariant":112,"./merge":121,"./warning":134}],43:[function(_dereq_,module,exports){ /** * Copyright 2013-2014 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. * * @providesModule ReactDefaultBatchingStrategy */ "use strict"; var ReactUpdates = _dereq_("./ReactUpdates"); var Transaction = _dereq_("./Transaction"); var emptyFunction = _dereq_("./emptyFunction"); var mixInto = _dereq_("./mixInto"); 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(); } mixInto(ReactDefaultBatchingStrategyTransaction, Transaction.Mixin); mixInto(ReactDefaultBatchingStrategyTransaction, { 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, param) { var alreadyBatchingUpdates = ReactDefaultBatchingStrategy.isBatchingUpdates; ReactDefaultBatchingStrategy.isBatchingUpdates = true; // The code is written this way to avoid extra allocations if (alreadyBatchingUpdates) { callback(param); } else { transaction.perform(callback, null, param); } } }; module.exports = ReactDefaultBatchingStrategy; },{"./ReactUpdates":71,"./Transaction":85,"./emptyFunction":96,"./mixInto":124}],44:[function(_dereq_,module,exports){ /** * Copyright 2013-2014 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. * * @providesModule ReactDefaultInjection */ "use strict"; var ReactInjection = _dereq_("./ReactInjection"); var ExecutionEnvironment = _dereq_("./ExecutionEnvironment"); var DefaultDOMPropertyConfig = _dereq_("./DefaultDOMPropertyConfig"); var ChangeEventPlugin = _dereq_("./ChangeEventPlugin"); var ClientReactRootIndex = _dereq_("./ClientReactRootIndex"); var CompositionEventPlugin = _dereq_("./CompositionEventPlugin"); var DefaultEventPluginOrder = _dereq_("./DefaultEventPluginOrder"); var EnterLeaveEventPlugin = _dereq_("./EnterLeaveEventPlugin"); var MobileSafariClickEventPlugin = _dereq_("./MobileSafariClickEventPlugin"); var ReactBrowserComponentMixin = _dereq_("./ReactBrowserComponentMixin"); var ReactComponentBrowserEnvironment = _dereq_("./ReactComponentBrowserEnvironment"); var ReactEventTopLevelCallback = _dereq_("./ReactEventTopLevelCallback"); var ReactDOM = _dereq_("./ReactDOM"); var ReactDOMButton = _dereq_("./ReactDOMButton"); var ReactDOMForm = _dereq_("./ReactDOMForm"); var ReactDOMImg = _dereq_("./ReactDOMImg"); var ReactDOMInput = _dereq_("./ReactDOMInput"); var ReactDOMOption = _dereq_("./ReactDOMOption"); var ReactDOMSelect = _dereq_("./ReactDOMSelect"); var ReactDOMTextarea = _dereq_("./ReactDOMTextarea"); var ReactInstanceHandles = _dereq_("./ReactInstanceHandles"); var ReactMount = _dereq_("./ReactMount"); var SelectEventPlugin = _dereq_("./SelectEventPlugin"); var ServerReactRootIndex = _dereq_("./ServerReactRootIndex"); var SimpleEventPlugin = _dereq_("./SimpleEventPlugin"); var ReactDefaultBatchingStrategy = _dereq_("./ReactDefaultBatchingStrategy"); var createFullPageComponent = _dereq_("./createFullPageComponent"); function inject() { ReactInjection.EventEmitter.injectTopLevelCallbackCreator( ReactEventTopLevelCallback ); /** * Inject modules for resolving DOM hierarchy and plugin ordering. */ ReactInjection.EventPluginHub.injectEventPluginOrder(DefaultEventPluginOrder); ReactInjection.EventPluginHub.injectInstanceHandle(ReactInstanceHandles); ReactInjection.EventPluginHub.injectMount(ReactMount); /** * Some important event plugins included by default (without having to require * them). */ ReactInjection.EventPluginHub.injectEventPluginsByName({ SimpleEventPlugin: SimpleEventPlugin, EnterLeaveEventPlugin: EnterLeaveEventPlugin, ChangeEventPlugin: ChangeEventPlugin, CompositionEventPlugin: CompositionEventPlugin, MobileSafariClickEventPlugin: MobileSafariClickEventPlugin, SelectEventPlugin: SelectEventPlugin }); ReactInjection.DOM.injectComponentClasses({ button: ReactDOMButton, form: ReactDOMForm, img: ReactDOMImg, input: ReactDOMInput, option: ReactDOMOption, select: ReactDOMSelect, textarea: ReactDOMTextarea, html: createFullPageComponent(ReactDOM.html), head: createFullPageComponent(ReactDOM.head), title: createFullPageComponent(ReactDOM.title), body: createFullPageComponent(ReactDOM.body) }); // This needs to happen after createFullPageComponent() otherwise the mixin // gets double injected. ReactInjection.CompositeComponent.injectMixin(ReactBrowserComponentMixin); ReactInjection.DOMProperty.injectDOMPropertyConfig(DefaultDOMPropertyConfig); ReactInjection.Updates.injectBatchingStrategy( ReactDefaultBatchingStrategy ); ReactInjection.RootIndex.injectCreateReactRootIndex( ExecutionEnvironment.canUseDOM ? ClientReactRootIndex.createReactRootIndex : ServerReactRootIndex.createReactRootIndex ); ReactInjection.Component.injectEnvironment(ReactComponentBrowserEnvironment); if ("production" !== "development") { var url = (ExecutionEnvironment.canUseDOM && window.location.href) || ''; if ((/[?&]react_perf\b/).test(url)) { var ReactDefaultPerf = _dereq_("./ReactDefaultPerf"); ReactDefaultPerf.start(); } } } module.exports = { inject: inject }; },{"./ChangeEventPlugin":4,"./ClientReactRootIndex":5,"./CompositionEventPlugin":6,"./DefaultDOMPropertyConfig":11,"./DefaultEventPluginOrder":12,"./EnterLeaveEventPlugin":13,"./ExecutionEnvironment":20,"./MobileSafariClickEventPlugin":22,"./ReactBrowserComponentMixin":25,"./ReactComponentBrowserEnvironment":28,"./ReactDOM":32,"./ReactDOMButton":33,"./ReactDOMForm":35,"./ReactDOMImg":37,"./ReactDOMInput":38,"./ReactDOMOption":39,"./ReactDOMSelect":40,"./ReactDOMTextarea":42,"./ReactDefaultBatchingStrategy":43,"./ReactDefaultPerf":45,"./ReactEventTopLevelCallback":50,"./ReactInjection":51,"./ReactInstanceHandles":53,"./ReactMount":55,"./SelectEventPlugin":72,"./ServerReactRootIndex":73,"./SimpleEventPlugin":74,"./createFullPageComponent":92}],45:[function(_dereq_,module,exports){ /** * Copyright 2013-2014 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. * * @providesModule ReactDefaultPerf * @typechecks static-only */ "use strict"; var DOMProperty = _dereq_("./DOMProperty"); var ReactDefaultPerfAnalysis = _dereq_("./ReactDefaultPerfAnalysis"); var ReactMount = _dereq_("./ReactMount"); var ReactPerf = _dereq_("./ReactPerf"); var performanceNow = _dereq_("./performanceNow"); function roundFloat(val) { return Math.floor(val * 100) / 100; } var ReactDefaultPerf = { _allMeasurements: [], // last item in the list is the current one _injected: false, start: function() { if (!ReactDefaultPerf._injected) { ReactPerf.injection.injectMeasure(ReactDefaultPerf.measure); } ReactDefaultPerf._allMeasurements.length = 0; ReactPerf.enableMeasure = true; }, stop: function() { ReactPerf.enableMeasure = false; }, getLastMeasurements: function() { return ReactDefaultPerf._allMeasurements; }, printExclusive: function(measurements) { measurements = measurements || ReactDefaultPerf._allMeasurements; var summary = ReactDefaultPerfAnalysis.getExclusiveSummary(measurements); console.table(summary.map(function(item) { return { 'Component class name': item.componentName, 'Total inclusive time (ms)': roundFloat(item.inclusive), 'Total exclusive time (ms)': roundFloat(item.exclusive), 'Exclusive time per instance (ms)': roundFloat(item.exclusive / item.count), 'Instances': item.count }; })); console.log( 'Total time:', ReactDefaultPerfAnalysis.getTotalTime(measurements).toFixed(2) + ' ms' ); }, printInclusive: function(measurements) { measurements = measurements || ReactDefaultPerf._allMeasurements; var summary = ReactDefaultPerfAnalysis.getInclusiveSummary(measurements); console.table(summary.map(function(item) { return { 'Owner > component': item.componentName, 'Inclusive time (ms)': roundFloat(item.time), 'Instances': item.count }; })); console.log( 'Total time:', ReactDefaultPerfAnalysis.getTotalTime(measurements).toFixed(2) + ' ms' ); }, printWasted: function(measurements) { measurements = measurements || ReactDefaultPerf._allMeasurements; var summary = ReactDefaultPerfAnalysis.getInclusiveSummary( measurements, true ); console.table(summary.map(function(item) { return { 'Owner > component': item.componentName, 'Wasted time (ms)': item.time, 'Instances': item.count }; })); console.log( 'Total time:', ReactDefaultPerfAnalysis.getTotalTime(measurements).toFixed(2) + ' ms' ); }, printDOM: function(measurements) { measurements = measurements || ReactDefaultPerf._allMeasurements; var summary = ReactDefaultPerfAnalysis.getDOMSummary(measurements); console.table(summary.map(function(item) { var result = {}; result[DOMProperty.ID_ATTRIBUTE_NAME] = item.id; result['type'] = item.type; result['args'] = JSON.stringify(item.args); return result; })); console.log( 'Total time:', ReactDefaultPerfAnalysis.getTotalTime(measurements).toFixed(2) + ' ms' ); }, _recordWrite: function(id, fnName, totalTime, args) { // TODO: totalTime isn't that useful since it doesn't count paints/reflows var writes = ReactDefaultPerf ._allMeasurements[ReactDefaultPerf._allMeasurements.length - 1] .writes; writes[id] = writes[id] || []; writes[id].push({ type: fnName, time: totalTime, args: args }); }, measure: function(moduleName, fnName, func) { return function() {var args=Array.prototype.slice.call(arguments,0); var totalTime; var rv; var start; if (fnName === '_renderNewRootComponent' || fnName === 'flushBatchedUpdates') { // A "measurement" is a set of metrics recorded for each flush. We want // to group the metrics for a given flush together so we can look at the // components that rendered and the DOM operations that actually // happened to determine the amount of "wasted work" performed. ReactDefaultPerf._allMeasurements.push({ exclusive: {}, inclusive: {}, counts: {}, writes: {}, displayNames: {}, totalTime: 0 }); start = performanceNow(); rv = func.apply(this, args); ReactDefaultPerf._allMeasurements[ ReactDefaultPerf._allMeasurements.length - 1 ].totalTime = performanceNow() - start; return rv; } else if (moduleName === 'ReactDOMIDOperations' || moduleName === 'ReactComponentBrowserEnvironment') { start = performanceNow(); rv = func.apply(this, args); totalTime = performanceNow() - start; if (fnName === 'mountImageIntoNode') { var mountID = ReactMount.getID(args[1]); ReactDefaultPerf._recordWrite(mountID, fnName, totalTime, args[0]); } else if (fnName === 'dangerouslyProcessChildrenUpdates') { // special format args[0].forEach(function(update) { var writeArgs = {}; if (update.fromIndex !== null) { writeArgs.fromIndex = update.fromIndex; } if (update.toIndex !== null) { writeArgs.toIndex = update.toIndex; } if (update.textContent !== null) { writeArgs.textContent = update.textContent; } if (update.markupIndex !== null) { writeArgs.markup = args[1][update.markupIndex]; } ReactDefaultPerf._recordWrite( update.parentID, update.type, totalTime, writeArgs ); }); } else { // basic format ReactDefaultPerf._recordWrite( args[0], fnName, totalTime, Array.prototype.slice.call(args, 1) ); } return rv; } else if (moduleName === 'ReactCompositeComponent' && ( fnName === 'mountComponent' || fnName === 'updateComponent' || // TODO: receiveComponent()? fnName === '_renderValidatedComponent')) { var rootNodeID = fnName === 'mountComponent' ? args[0] : this._rootNodeID; var isRender = fnName === '_renderValidatedComponent'; var entry = ReactDefaultPerf._allMeasurements[ ReactDefaultPerf._allMeasurements.length - 1 ]; if (isRender) { entry.counts[rootNodeID] = entry.counts[rootNodeID] || 0; entry.counts[rootNodeID] += 1; } start = performanceNow(); rv = func.apply(this, args); totalTime = performanceNow() - start; var typeOfLog = isRender ? entry.exclusive : entry.inclusive; typeOfLog[rootNodeID] = typeOfLog[rootNodeID] || 0; typeOfLog[rootNodeID] += totalTime; entry.displayNames[rootNodeID] = { current: this.constructor.displayName, owner: this._owner ? this._owner.constructor.displayName : '<root>' }; return rv; } else { return func.apply(this, args); } }; } }; module.exports = ReactDefaultPerf; },{"./DOMProperty":8,"./ReactDefaultPerfAnalysis":46,"./ReactMount":55,"./ReactPerf":60,"./performanceNow":129}],46:[function(_dereq_,module,exports){ /** * Copyright 2013-2014 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. * * @providesModule ReactDefaultPerfAnalysis */ var merge = _dereq_("./merge"); // Don't try to save users less than 1.2ms (a number I made up) var DONT_CARE_THRESHOLD = 1.2; var DOM_OPERATION_TYPES = { 'mountImageIntoNode': 'set innerHTML', INSERT_MARKUP: 'set innerHTML', MOVE_EXISTING: 'move', REMOVE_NODE: 'remove', TEXT_CONTENT: 'set textContent', 'updatePropertyByID': 'update attribute', 'deletePropertyByID': 'delete attribute', 'updateStylesByID': 'update styles', 'updateInnerHTMLByID': 'set innerHTML', 'dangerouslyReplaceNodeWithMarkupByID': 'replace' }; function getTotalTime(measurements) { // TODO: return number of DOM ops? could be misleading. // TODO: measure dropped frames after reconcile? // TODO: log total time of each reconcile and the top-level component // class that triggered it. var totalTime = 0; for (var i = 0; i < measurements.length; i++) { var measurement = measurements[i]; totalTime += measurement.totalTime; } return totalTime; } function getDOMSummary(measurements) { var items = []; for (var i = 0; i < measurements.length; i++) { var measurement = measurements[i]; var id; for (id in measurement.writes) { measurement.writes[id].forEach(function(write) { items.push({ id: id, type: DOM_OPERATION_TYPES[write.type] || write.type, args: write.args }); }); } } return items; } function getExclusiveSummary(measurements) { var candidates = {}; var displayName; for (var i = 0; i < measurements.length; i++) { var measurement = measurements[i]; var allIDs = merge(measurement.exclusive, measurement.inclusive); for (var id in allIDs) { displayName = measurement.displayNames[id].current; candidates[displayName] = candidates[displayName] || { componentName: displayName, inclusive: 0, exclusive: 0, count: 0 }; if (measurement.exclusive[id]) { candidates[displayName].exclusive += measurement.exclusive[id]; } if (measurement.inclusive[id]) { candidates[displayName].inclusive += measurement.inclusive[id]; } if (measurement.counts[id]) { candidates[displayName].count += measurement.counts[id]; } } } // Now make a sorted array with the results. var arr = []; for (displayName in candidates) { if (candidates[displayName].exclusive >= DONT_CARE_THRESHOLD) { arr.push(candidates[displayName]); } } arr.sort(function(a, b) { return b.exclusive - a.exclusive; }); return arr; } function getInclusiveSummary(measurements, onlyClean) { var candidates = {}; var inclusiveKey; for (var i = 0; i < measurements.length; i++) { var measurement = measurements[i]; var allIDs = merge(measurement.exclusive, measurement.inclusive); var cleanComponents; if (onlyClean) { cleanComponents = getUnchangedComponents(measurement); } for (var id in allIDs) { if (onlyClean && !cleanComponents[id]) { continue; } var displayName = measurement.displayNames[id]; // Inclusive time is not useful for many components without knowing where // they are instantiated. So we aggregate inclusive time with both the // owner and current displayName as the key. inclusiveKey = displayName.owner + ' > ' + displayName.current; candidates[inclusiveKey] = candidates[inclusiveKey] || { componentName: inclusiveKey, time: 0, count: 0 }; if (measurement.inclusive[id]) { candidates[inclusiveKey].time += measurement.inclusive[id]; } if (measurement.counts[id]) { candidates[inclusiveKey].count += measurement.counts[id]; } } } // Now make a sorted array with the results. var arr = []; for (inclusiveKey in candidates) { if (candidates[inclusiveKey].time >= DONT_CARE_THRESHOLD) { arr.push(candidates[inclusiveKey]); } } arr.sort(function(a, b) { return b.time - a.time; }); return arr; } function getUnchangedComponents(measurement) { // For a given reconcile, look at which components did not actually // render anything to the DOM and return a mapping of their ID to // the amount of time it took to render the entire subtree. var cleanComponents = {}; var dirtyLeafIDs = Object.keys(measurement.writes); var allIDs = merge(measurement.exclusive, measurement.inclusive); for (var id in allIDs) { var isDirty = false; // For each component that rendered, see if a component that triggerd // a DOM op is in its subtree. for (var i = 0; i < dirtyLeafIDs.length; i++) { if (dirtyLeafIDs[i].indexOf(id) === 0) { isDirty = true; break; } } if (!isDirty && measurement.counts[id] > 0) { cleanComponents[id] = true; } } return cleanComponents; } var ReactDefaultPerfAnalysis = { getExclusiveSummary: getExclusiveSummary, getInclusiveSummary: getInclusiveSummary, getDOMSummary: getDOMSummary, getTotalTime: getTotalTime }; module.exports = ReactDefaultPerfAnalysis; },{"./merge":121}],47:[function(_dereq_,module,exports){ /** * Copyright 2013-2014 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. * * @providesModule ReactErrorUtils * @typechecks */ "use strict"; var ReactErrorUtils = { /** * Creates a guarded version of a function. This is supposed to make debugging * of event handlers easier. To aid debugging with the browser's debugger, * this currently simply returns the original function. * * @param {function} func Function to be executed * @param {string} name The name of the guard * @return {function} */ guard: function(func, name) { return func; } }; module.exports = ReactErrorUtils; },{}],48:[function(_dereq_,module,exports){ /** * Copyright 2013-2014 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. * * @providesModule ReactEventEmitter * @typechecks static-only */ "use strict"; var EventConstants = _dereq_("./EventConstants"); var EventListener = _dereq_("./EventListener"); var EventPluginHub = _dereq_("./EventPluginHub"); var EventPluginRegistry = _dereq_("./EventPluginRegistry"); var ExecutionEnvironment = _dereq_("./ExecutionEnvironment"); var ReactEventEmitterMixin = _dereq_("./ReactEventEmitterMixin"); var ViewportMetrics = _dereq_("./ViewportMetrics"); var invariant = _dereq_("./invariant"); var isEventSupported = _dereq_("./isEventSupported"); var merge = _dereq_("./merge"); /** * Summary of `ReactEventEmitter` event handling: * * - Top-level delegation is used to trap native browser events. We normalize * and de-duplicate events to account for browser quirks. * * - 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 | . * +------------+ . +-----------+ * + . +--------+|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 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 = { topBlur: 'blur', 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', topFocus: 'focus', topInput: 'input', topKeyDown: 'keydown', topKeyPress: 'keypress', topKeyUp: 'keyup', topMouseDown: 'mousedown', topMouseMove: 'mousemove', topMouseOut: 'mouseout', topMouseOver: 'mouseover', topMouseUp: 'mouseup', topPaste: 'paste', topScroll: 'scroll', topSelectionChange: 'selectionchange', topTouchCancel: 'touchcancel', topTouchEnd: 'touchend', topTouchMove: 'touchmove', topTouchStart: 'touchstart', 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) { if (mountAt[topListenersIDKey] == null) { mountAt[topListenersIDKey] = reactTopListenersCounter++; alreadyListeningTo[mountAt[topListenersIDKey]] = {}; } return alreadyListeningTo[mountAt[topListenersIDKey]]; } /** * Traps top-level events by using event bubbling. * * @param {string} topLevelType Record from `EventConstants`. * @param {string} handlerBaseName Event name (e.g. "click"). * @param {DOMEventTarget} element Element on which to attach listener. * @internal */ function trapBubbledEvent(topLevelType, handlerBaseName, element) { EventListener.listen( element, handlerBaseName, ReactEventEmitter.TopLevelCallbackCreator.createTopLevelCallback( 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 {DOMEventTarget} element Element on which to attach listener. * @internal */ function trapCapturedEvent(topLevelType, handlerBaseName, element) { EventListener.capture( element, handlerBaseName, ReactEventEmitter.TopLevelCallbackCreator.createTopLevelCallback( topLevelType ) ); } /** * `ReactEventEmitter` is used to attach top-level event listeners. For example: * * ReactEventEmitter.putListener('myID', 'onClick', myFunction); * * This would allocate a "registration" of `('onClick', myFunction)` on 'myID'. * * @internal */ var ReactEventEmitter = merge(ReactEventEmitterMixin, { /** * React references `ReactEventTopLevelCallback` using this property in order * to allow dependency injection. */ TopLevelCallbackCreator: null, injection: { /** * @param {function} TopLevelCallbackCreator */ injectTopLevelCallbackCreator: function(TopLevelCallbackCreator) { ReactEventEmitter.TopLevelCallbackCreator = TopLevelCallbackCreator; } }, /** * Sets whether or not any created callbacks should be enabled. * * @param {boolean} enabled True if callbacks should be enabled. */ setEnabled: function(enabled) { ("production" !== "development" ? invariant( ExecutionEnvironment.canUseDOM, 'setEnabled(...): Cannot toggle event listening in a Worker thread. ' + 'This is likely a bug in the framework. Please report immediately.' ) : invariant(ExecutionEnvironment.canUseDOM)); if (ReactEventEmitter.TopLevelCallbackCreator) { ReactEventEmitter.TopLevelCallbackCreator.setEnabled(enabled); } }, /** * @return {boolean} True if callbacks are enabled. */ isEnabled: function() { return !!( ReactEventEmitter.TopLevelCallbackCreator && ReactEventEmitter.TopLevelCallbackCreator.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 {DOMDocument} contentDocument Document which owns the container */ listenTo: function(registrationName, contentDocument) { var mountAt = contentDocument; var isListening = getListeningForDocument(mountAt); var dependencies = EventPluginRegistry. registrationNameDependencies[registrationName]; var topLevelTypes = EventConstants.topLevelTypes; for (var i = 0, l = dependencies.length; i < l; i++) { var dependency = dependencies[i]; if (!isListening[dependency]) { var topLevelType = topLevelTypes[dependency]; if (topLevelType === topLevelTypes.topWheel) { if (isEventSupported('wheel')) { trapBubbledEvent(topLevelTypes.topWheel, 'wheel', mountAt); } else if (isEventSupported('mousewheel')) { trapBubbledEvent(topLevelTypes.topWheel, 'mousewheel', mountAt); } else { // Firefox needs to capture a different mouse scroll event. // @see http://www.quirksmode.org/dom/events/tests/scroll.html trapBubbledEvent( topLevelTypes.topWheel, 'DOMMouseScroll', mountAt); } } else if (topLevelType === topLevelTypes.topScroll) { if (isEventSupported('scroll', true)) { trapCapturedEvent(topLevelTypes.topScroll, 'scroll', mountAt); } else { trapBubbledEvent(topLevelTypes.topScroll, 'scroll', window); } } else if (topLevelType === topLevelTypes.topFocus || topLevelType === topLevelTypes.topBlur) { if (isEventSupported('focus', true)) { trapCapturedEvent(topLevelTypes.topFocus, 'focus', mountAt); trapCapturedEvent(topLevelTypes.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 trapBubbledEvent(topLevelTypes.topFocus, 'focusin', mountAt); trapBubbledEvent(topLevelTypes.topBlur, 'focusout', mountAt); } // to make sure blur and focus event listeners are only attached once isListening[topLevelTypes.topBlur] = true; isListening[topLevelTypes.topFocus] = true; } else if (topEventMapping[dependency]) { trapBubbledEvent(topLevelType, topEventMapping[dependency], mountAt); } isListening[dependency] = true; } } }, /** * Listens to window scroll and resize events. We cache scroll values so that * application code can access them without triggering reflows. * * NOTE: Scroll events do not bubble. * * @see http://www.quirksmode.org/dom/events/scroll.html */ ensureScrollValueMonitoring: function(){ if (!isMonitoringScrollValue) { var refresh = ViewportMetrics.refreshScrollValues; EventListener.listen(window, 'scroll', refresh); EventListener.listen(window, 'resize', refresh); isMonitoringScrollValue = true; } }, eventNameDispatchConfigs: EventPluginHub.eventNameDispatchConfigs, registrationNameModules: EventPluginHub.registrationNameModules, putListener: EventPluginHub.putListener, getListener: EventPluginHub.getListener, deleteListener: EventPluginHub.deleteListener, deleteAllListeners: EventPluginHub.deleteAllListeners, trapBubbledEvent: trapBubbledEvent, trapCapturedEvent: trapCapturedEvent }); module.exports = ReactEventEmitter; },{"./EventConstants":14,"./EventListener":15,"./EventPluginHub":16,"./EventPluginRegistry":17,"./ExecutionEnvironment":20,"./ReactEventEmitterMixin":49,"./ViewportMetrics":86,"./invariant":112,"./isEventSupported":113,"./merge":121}],49:[function(_dereq_,module,exports){ /** * Copyright 2013-2014 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. * * @providesModule ReactEventEmitterMixin */ "use strict"; var EventPluginHub = _dereq_("./EventPluginHub"); var ReactUpdates = _dereq_("./ReactUpdates"); function runEventQueueInBatch(events) { EventPluginHub.enqueueEvents(events); EventPluginHub.processEventQueue(); } var ReactEventEmitterMixin = { /** * Streams a fired top-level event to `EventPluginHub` where plugins have the * opportunity to create `ReactEvent`s to be dispatched. * * @param {string} topLevelType Record from `EventConstants`. * @param {object} topLevelTarget The listening component root node. * @param {string} topLevelTargetID ID of `topLevelTarget`. * @param {object} nativeEvent Native environment event. */ handleTopLevel: function( topLevelType, topLevelTarget, topLevelTargetID, nativeEvent) { var events = EventPluginHub.extractEvents( topLevelType, topLevelTarget, topLevelTargetID, nativeEvent ); // Event queue being processed in the same cycle allows `preventDefault`. ReactUpdates.batchedUpdates(runEventQueueInBatch, events); } }; module.exports = ReactEventEmitterMixin; },{"./EventPluginHub":16,"./ReactUpdates":71}],50:[function(_dereq_,module,exports){ /** * Copyright 2013-2014 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. * * @providesModule ReactEventTopLevelCallback * @typechecks static-only */ "use strict"; var PooledClass = _dereq_("./PooledClass"); var ReactEventEmitter = _dereq_("./ReactEventEmitter"); var ReactInstanceHandles = _dereq_("./ReactInstanceHandles"); var ReactMount = _dereq_("./ReactMount"); var getEventTarget = _dereq_("./getEventTarget"); var mixInto = _dereq_("./mixInto"); /** * @type {boolean} * @private */ var _topLevelListenersEnabled = true; /** * Finds the parent React component of `node`. * * @param {*} node * @return {?DOMEventTarget} Parent container, or `null` if the specified node * is not nested. */ function findParent(node) { // 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. var nodeID = ReactMount.getID(node); var rootID = ReactInstanceHandles.getReactRootIDFromNodeID(nodeID); var container = ReactMount.findReactContainerForID(rootID); var parent = ReactMount.getFirstReactDOM(container); return parent; } /** * Calls ReactEventEmitter.handleTopLevel for each node stored in bookKeeping's * ancestor list. Separated from createTopLevelCallback to avoid try/finally * deoptimization. * * @param {string} topLevelType * @param {DOMEvent} nativeEvent * @param {TopLevelCallbackBookKeeping} bookKeeping */ function handleTopLevelImpl(topLevelType, nativeEvent, bookKeeping) { var topLevelTarget = ReactMount.getFirstReactDOM( getEventTarget(nativeEvent) ) || window; // 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 = topLevelTarget; while (ancestor) { bookKeeping.ancestors.push(ancestor); ancestor = findParent(ancestor); } for (var i = 0, l = bookKeeping.ancestors.length; i < l; i++) { topLevelTarget = bookKeeping.ancestors[i]; var topLevelTargetID = ReactMount.getID(topLevelTarget) || ''; ReactEventEmitter.handleTopLevel( topLevelType, topLevelTarget, topLevelTargetID, nativeEvent ); } } // Used to store ancestor hierarchy in top level callback function TopLevelCallbackBookKeeping() { this.ancestors = []; } mixInto(TopLevelCallbackBookKeeping, { destructor: function() { this.ancestors.length = 0; } }); PooledClass.addPoolingTo(TopLevelCallbackBookKeeping); /** * Top-level callback creator used to implement event handling using delegation. * This is used via dependency injection. */ var ReactEventTopLevelCallback = { /** * Sets whether or not any created callbacks should be enabled. * * @param {boolean} enabled True if callbacks should be enabled. */ setEnabled: function(enabled) { _topLevelListenersEnabled = !!enabled; }, /** * @return {boolean} True if callbacks are enabled. */ isEnabled: function() { return _topLevelListenersEnabled; }, /** * Creates a callback for the supplied `topLevelType` that could be added as * a listener to the document. The callback computes a `topLevelTarget` which * should be the root node of a mounted React component where the listener * is attached. * * @param {string} topLevelType Record from `EventConstants`. * @return {function} Callback for handling top-level events. */ createTopLevelCallback: function(topLevelType) { return function(nativeEvent) { if (!_topLevelListenersEnabled) { return; } var bookKeeping = TopLevelCallbackBookKeeping.getPooled(); try { handleTopLevelImpl(topLevelType, nativeEvent, bookKeeping); } finally { TopLevelCallbackBookKeeping.release(bookKeeping); } }; } }; module.exports = ReactEventTopLevelCallback; },{"./PooledClass":23,"./ReactEventEmitter":48,"./ReactInstanceHandles":53,"./ReactMount":55,"./getEventTarget":104,"./mixInto":124}],51:[function(_dereq_,module,exports){ /** * Copyright 2013-2014 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. * * @providesModule ReactInjection */ "use strict"; var DOMProperty = _dereq_("./DOMProperty"); var EventPluginHub = _dereq_("./EventPluginHub"); var ReactComponent = _dereq_("./ReactComponent"); var ReactCompositeComponent = _dereq_("./ReactCompositeComponent"); var ReactDOM = _dereq_("./ReactDOM"); var ReactEventEmitter = _dereq_("./ReactEventEmitter"); var ReactPerf = _dereq_("./ReactPerf"); var ReactRootIndex = _dereq_("./ReactRootIndex"); var ReactUpdates = _dereq_("./ReactUpdates"); var ReactInjection = { Component: ReactComponent.injection, CompositeComponent: ReactCompositeComponent.injection, DOMProperty: DOMProperty.injection, EventPluginHub: EventPluginHub.injection, DOM: ReactDOM.injection, EventEmitter: ReactEventEmitter.injection, Perf: ReactPerf.injection, RootIndex: ReactRootIndex.injection, Updates: ReactUpdates.injection }; module.exports = ReactInjection; },{"./DOMProperty":8,"./EventPluginHub":16,"./ReactComponent":27,"./ReactCompositeComponent":29,"./ReactDOM":32,"./ReactEventEmitter":48,"./ReactPerf":60,"./ReactRootIndex":67,"./ReactUpdates":71}],52:[function(_dereq_,module,exports){ /** * Copyright 2013-2014 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. * * @providesModule ReactInputSelection */ "use strict"; var ReactDOMSelection = _dereq_("./ReactDOMSelection"); var containsNode = _dereq_("./containsNode"); var focusNode = _dereq_("./focusNode"); var getActiveElement = _dereq_("./getActiveElement"); 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) { return elem && ( (elem.nodeName === 'INPUT' && elem.type === 'text') || elem.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 ); } focusNode(priorFocusedElem); } }, /** * @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') { // 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 (typeof 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') { 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; },{"./ReactDOMSelection":41,"./containsNode":89,"./focusNode":100,"./getActiveElement":102}],53:[function(_dereq_,module,exports){ /** * Copyright 2013-2014 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. * * @providesModule ReactInstanceHandles * @typechecks static-only */ "use strict"; var ReactRootIndex = _dereq_("./ReactRootIndex"); var invariant = _dereq_("./invariant"); var SEPARATOR = '.'; var SEPARATOR_LENGTH = SEPARATOR.length; /** * Maximum depth of traversals before we consider the possibility of a bad ID. */ var MAX_TREE_DEPTH = 100; /** * Creates a DOM ID prefix to use when mounting React components. * * @param {number} index A unique integer * @return {string} React root ID. * @internal */ function getReactRootIDString(index) { return SEPARATOR + index.toString(36); } /** * Checks if a character in the supplied ID is a separator or the end. * * @param {string} id A React DOM ID. * @param {number} index Index of the character to check. * @return {boolean} True if the character is a separator or end of the ID. * @private */ function isBoundary(id, index) { return id.charAt(index) === SEPARATOR || index === id.length; } /** * Checks if the supplied string is a valid React DOM ID. * * @param {string} id A React DOM ID, maybe. * @return {boolean} True if the string is a valid React DOM ID. * @private */ function isValidID(id) { return id === '' || ( id.charAt(0) === SEPARATOR && id.charAt(id.length - 1) !== SEPARATOR ); } /** * Checks if the first ID is an ancestor of or equal to the second ID. * * @param {string} ancestorID * @param {string} descendantID * @return {boolean} True if `ancestorID` is an ancestor of `descendantID`. * @internal */ function isAncestorIDOf(ancestorID, descendantID) { return ( descendantID.indexOf(ancestorID) === 0 && isBoundary(descendantID, ancestorID.length) ); } /** * Gets the parent ID of the supplied React DOM ID, `id`. * * @param {string} id ID of a component. * @return {string} ID of the parent, or an empty string. * @private */ function getParentID(id) { return id ? id.substr(0, id.lastIndexOf(SEPARATOR)) : ''; } /** * Gets the next DOM ID on the tree path from the supplied `ancestorID` to the * supplied `destinationID`. If they are equal, the ID is returned. * * @param {string} ancestorID ID of an ancestor node of `destinationID`. * @param {string} destinationID ID of the destination node. * @return {string} Next ID on the path from `ancestorID` to `destinationID`. * @private */ function getNextDescendantID(ancestorID, destinationID) { ("production" !== "development" ? invariant( isValidID(ancestorID) && isValidID(destinationID), 'getNextDescendantID(%s, %s): Received an invalid React DOM ID.', ancestorID, destinationID ) : invariant(isValidID(ancestorID) && isValidID(destinationID))); ("production" !== "development" ? invariant( isAncestorIDOf(ancestorID, destinationID), 'getNextDescendantID(...): React has made an invalid assumption about ' + 'the DOM hierarchy. Expected `%s` to be an ancestor of `%s`.', ancestorID, destinationID ) : invariant(isAncestorIDOf(ancestorID, destinationID))); if (ancestorID === destinationID) { return ancestorID; } // Skip over the ancestor and the immediate separator. Traverse until we hit // another separator or we reach the end of `destinationID`. var start = ancestorID.length + SEPARATOR_LENGTH; for (var i = start; i < destinationID.length; i++) { if (isBoundary(destinationID, i)) { break; } } return destinationID.substr(0, i); } /** * Gets the nearest common ancestor ID of two IDs. * * Using this ID scheme, the nearest common ancestor ID is the longest common * prefix of the two IDs that immediately preceded a "marker" in both strings. * * @param {string} oneID * @param {string} twoID * @return {string} Nearest common ancestor ID, or the empty string if none. * @private */ function getFirstCommonAncestorID(oneID, twoID) { var minLength = Math.min(oneID.length, twoID.length); if (minLength === 0) { return ''; } var lastCommonMarkerIndex = 0; // Use `<=` to traverse until the "EOL" of the shorter string. for (var i = 0; i <= minLength; i++) { if (isBoundary(oneID, i) && isBoundary(twoID, i)) { lastCommonMarkerIndex = i; } else if (oneID.charAt(i) !== twoID.charAt(i)) { break; } } var longestCommonID = oneID.substr(0, lastCommonMarkerIndex); ("production" !== "development" ? invariant( isValidID(longestCommonID), 'getFirstCommonAncestorID(%s, %s): Expected a valid React DOM ID: %s', oneID, twoID, longestCommonID ) : invariant(isValidID(longestCommonID))); return longestCommonID; } /** * Traverses the parent path between two IDs (either up or down). The IDs must * not be the same, and there must exist a parent path between them. If the * callback returns `false`, traversal is stopped. * * @param {?string} start ID at which to start traversal. * @param {?string} stop ID at which to end traversal. * @param {function} cb Callback to invoke each ID with. * @param {?boolean} skipFirst Whether or not to skip the first node. * @param {?boolean} skipLast Whether or not to skip the last node. * @private */ function traverseParentPath(start, stop, cb, arg, skipFirst, skipLast) { start = start || ''; stop = stop || ''; ("production" !== "development" ? invariant( start !== stop, 'traverseParentPath(...): Cannot traverse from and to the same ID, `%s`.', start ) : invariant(start !== stop)); var traverseUp = isAncestorIDOf(stop, start); ("production" !== "development" ? invariant( traverseUp || isAncestorIDOf(start, stop), 'traverseParentPath(%s, %s, ...): Cannot traverse from two IDs that do ' + 'not have a parent path.', start, stop ) : invariant(traverseUp || isAncestorIDOf(start, stop))); // Traverse from `start` to `stop` one depth at a time. var depth = 0; var traverse = traverseUp ? getParentID : getNextDescendantID; for (var id = start; /* until break */; id = traverse(id, stop)) { var ret; if ((!skipFirst || id !== start) && (!skipLast || id !== stop)) { ret = cb(id, traverseUp, arg); } if (ret === false || id === stop) { // Only break //after// visiting `stop`. break; } ("production" !== "development" ? invariant( depth++ < MAX_TREE_DEPTH, 'traverseParentPath(%s, %s, ...): Detected an infinite loop while ' + 'traversing the React DOM ID tree. This may be due to malformed IDs: %s', start, stop ) : invariant(depth++ < MAX_TREE_DEPTH)); } } /** * Manages the IDs assigned to DOM representations of React components. This * uses a specific scheme in order to traverse the DOM efficiently (e.g. in * order to simulate events). * * @internal */ var ReactInstanceHandles = { /** * Constructs a React root ID * @return {string} A React root ID. */ createReactRootID: function() { return getReactRootIDString(ReactRootIndex.createReactRootIndex()); }, /** * Constructs a React ID by joining a root ID with a name. * * @param {string} rootID Root ID of a parent component. * @param {string} name A component's name (as flattened children). * @return {string} A React ID. * @internal */ createReactID: function(rootID, name) { return rootID + name; }, /** * Gets the DOM ID of the React component that is the root of the tree that * contains the React component with the supplied DOM ID. * * @param {string} id DOM ID of a React component. * @return {?string} DOM ID of the React component that is the root. * @internal */ getReactRootIDFromNodeID: function(id) { if (id && id.charAt(0) === SEPARATOR && id.length > 1) { var index = id.indexOf(SEPARATOR, 1); return index > -1 ? id.substr(0, index) : id; } return null; }, /** * Traverses the ID hierarchy and invokes the supplied `cb` on any IDs that * should would receive a `mouseEnter` or `mouseLeave` event. * * NOTE: Does not invoke the callback on the nearest common ancestor because * nothing "entered" or "left" that element. * * @param {string} leaveID ID being left. * @param {string} enterID ID being entered. * @param {function} cb Callback to invoke on each entered/left ID. * @param {*} upArg Argument to invoke the callback with on left IDs. * @param {*} downArg Argument to invoke the callback with on entered IDs. * @internal */ traverseEnterLeave: function(leaveID, enterID, cb, upArg, downArg) { var ancestorID = getFirstCommonAncestorID(leaveID, enterID); if (ancestorID !== leaveID) { traverseParentPath(leaveID, ancestorID, cb, upArg, false, true); } if (ancestorID !== enterID) { traverseParentPath(ancestorID, enterID, cb, downArg, true, false); } }, /** * Simulates the traversal of a two-phase, capture/bubble event dispatch. * * NOTE: This traversal happens on IDs without touching the DOM. * * @param {string} targetID ID of the target node. * @param {function} cb Callback to invoke. * @param {*} arg Argument to invoke the callback with. * @internal */ traverseTwoPhase: function(targetID, cb, arg) { if (targetID) { traverseParentPath('', targetID, cb, arg, true, false); traverseParentPath(targetID, '', cb, arg, false, true); } }, /** * Traverse a node ID, calling the supplied `cb` for each ancestor ID. For * example, passing `.0.$row-0.1` would result in `cb` getting called * with `.0`, `.0.$row-0`, and `.0.$row-0.1`. * * NOTE: This traversal happens on IDs without touching the DOM. * * @param {string} targetID ID of the target node. * @param {function} cb Callback to invoke. * @param {*} arg Argument to invoke the callback with. * @internal */ traverseAncestors: function(targetID, cb, arg) { traverseParentPath('', targetID, cb, arg, true, false); }, /** * Exposed for unit testing. * @private */ _getFirstCommonAncestorID: getFirstCommonAncestorID, /** * Exposed for unit testing. * @private */ _getNextDescendantID: getNextDescendantID, isAncestorIDOf: isAncestorIDOf, SEPARATOR: SEPARATOR }; module.exports = ReactInstanceHandles; },{"./ReactRootIndex":67,"./invariant":112}],54:[function(_dereq_,module,exports){ /** * Copyright 2013-2014 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. * * @providesModule ReactMarkupChecksum */ "use strict"; var adler32 = _dereq_("./adler32"); 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); return markup.replace( '>', ' ' + 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; },{"./adler32":88}],55:[function(_dereq_,module,exports){ /** * Copyright 2013-2014 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. * * @providesModule ReactMount */ "use strict"; var DOMProperty = _dereq_("./DOMProperty"); var ReactEventEmitter = _dereq_("./ReactEventEmitter"); var ReactInstanceHandles = _dereq_("./ReactInstanceHandles"); var ReactPerf = _dereq_("./ReactPerf"); var containsNode = _dereq_("./containsNode"); var getReactRootElementInContainer = _dereq_("./getReactRootElementInContainer"); var instantiateReactComponent = _dereq_("./instantiateReactComponent"); var invariant = _dereq_("./invariant"); var shouldUpdateReactComponent = _dereq_("./shouldUpdateReactComponent"); var SEPARATOR = ReactInstanceHandles.SEPARATOR; var ATTR_NAME = DOMProperty.ID_ATTRIBUTE_NAME; var nodeCache = {}; var ELEMENT_NODE_TYPE = 1; var DOC_NODE_TYPE = 9; /** Mapping from reactRootID to React component instance. */ var instancesByReactRootID = {}; /** Mapping from reactRootID to `container` nodes. */ var containersByReactRootID = {}; if ("production" !== "development") { /** __DEV__-only mapping from reactRootID to root elements. */ var rootElementsByReactRootID = {}; } // Used to store breadth-first search state in findComponentRoot. var findComponentRootReusableArray = []; /** * @param {DOMElement} container DOM element that may contain a React component. * @return {?string} A "reactRoot" ID, if a React component is rendered. */ function getReactRootID(container) { var rootElement = getReactRootElementInContainer(container); return rootElement && ReactMount.getID(rootElement); } /** * Accessing node[ATTR_NAME] or calling getAttribute(ATTR_NAME) on a form * element can return its control whose name or ID equals ATTR_NAME. All * DOM nodes support `getAttributeNode` but this can also get called on * other objects so just return '' if we're given something other than a * DOM node (such as window). * * @param {?DOMElement|DOMWindow|DOMDocument|DOMTextNode} node DOM node. * @return {string} ID of the supplied `domNode`. */ function getID(node) { var id = internalGetID(node); if (id) { if (nodeCache.hasOwnProperty(id)) { var cached = nodeCache[id]; if (cached !== node) { ("production" !== "development" ? invariant( !isValid(cached, id), 'ReactMount: Two valid but unequal nodes with the same `%s`: %s', ATTR_NAME, id ) : invariant(!isValid(cached, id))); nodeCache[id] = node; } } else { nodeCache[id] = node; } } return id; } function internalGetID(node) { // If node is something like a window, document, or text node, none of // which support attributes or a .getAttribute method, gracefully return // the empty string, as if the attribute were missing. return node && node.getAttribute && node.getAttribute(ATTR_NAME) || ''; } /** * Sets the React-specific ID of the given node. * * @param {DOMElement} node The DOM node whose ID will be set. * @param {string} id The value of the ID attribute. */ function setID(node, id) { var oldID = internalGetID(node); if (oldID !== id) { delete nodeCache[oldID]; } node.setAttribute(ATTR_NAME, id); nodeCache[id] = node; } /** * Finds the node with the supplied React-generated DOM ID. * * @param {string} id A React-generated DOM ID. * @return {DOMElement} DOM node with the suppled `id`. * @internal */ function getNode(id) { if (!nodeCache.hasOwnProperty(id) || !isValid(nodeCache[id], id)) { nodeCache[id] = ReactMount.findReactNodeByID(id); } return nodeCache[id]; } /** * A node is "valid" if it is contained by a currently mounted container. * * This means that the node does not have to be contained by a document in * order to be considered valid. * * @param {?DOMElement} node The candidate DOM node. * @param {string} id The expected ID of the node. * @return {boolean} Whether the node is contained by a mounted container. */ function isValid(node, id) { if (node) { ("production" !== "development" ? invariant( internalGetID(node) === id, 'ReactMount: Unexpected modification of `%s`', ATTR_NAME ) : invariant(internalGetID(node) === id)); var container = ReactMount.findReactContainerForID(id); if (container && containsNode(container, node)) { return true; } } return false; } /** * Causes the cache to forget about one React-specific ID. * * @param {string} id The ID to forget. */ function purgeID(id) { delete nodeCache[id]; } var deepestNodeSoFar = null; function findDeepestCachedAncestorImpl(ancestorID) { var ancestor = nodeCache[ancestorID]; if (ancestor && isValid(ancestor, ancestorID)) { deepestNodeSoFar = ancestor; } else { // This node isn't populated in the cache, so presumably none of its // descendants are. Break out of the loop. return false; } } /** * Return the deepest cached node whose ID is a prefix of `targetID`. */ function findDeepestCachedAncestor(targetID) { deepestNodeSoFar = null; ReactInstanceHandles.traverseAncestors( targetID, findDeepestCachedAncestorImpl ); var foundNode = deepestNodeSoFar; deepestNodeSoFar = null; return foundNode; } /** * Mounting is the process of initializing a React component by creatings its * representative DOM elements and inserting them into a supplied `container`. * Any prior content inside `container` is destroyed in the process. * * ReactMount.renderComponent( * component, * document.getElementById('container') * ); * * <div id="container"> <-- Supplied `container`. * <div data-reactid=".3"> <-- Rendered reactRoot of React * // ... component. * </div> * </div> * * Inside of `container`, the first element rendered is the "reactRoot". */ var ReactMount = { /** Time spent generating markup. */ totalInstantiationTime: 0, /** Time spent inserting markup into the DOM. */ totalInjectionTime: 0, /** Whether support for touch events should be initialized. */ useTouchEvents: false, /** Exposed for debugging purposes **/ _instancesByReactRootID: instancesByReactRootID, /** * This is a hook provided to support rendering React components while * ensuring that the apparent scroll position of its `container` does not * change. * * @param {DOMElement} container The `container` being rendered into. * @param {function} renderCallback This must be called once to do the render. */ scrollMonitor: function(container, renderCallback) { renderCallback(); }, /** * Take a component that's already mounted into the DOM and replace its props * @param {ReactComponent} prevComponent component instance already in the DOM * @param {ReactComponent} nextComponent component instance to render * @param {DOMElement} container container to render into * @param {?function} callback function triggered on completion */ _updateRootComponent: function( prevComponent, nextComponent, container, callback) { var nextProps = nextComponent.props; ReactMount.scrollMonitor(container, function() { prevComponent.replaceProps(nextProps, callback); }); if ("production" !== "development") { // Record the root element in case it later gets transplanted. rootElementsByReactRootID[getReactRootID(container)] = getReactRootElementInContainer(container); } return prevComponent; }, /** * Register a component into the instance map and starts scroll value * monitoring * @param {ReactComponent} nextComponent component instance to render * @param {DOMElement} container container to render into * @return {string} reactRoot ID prefix */ _registerComponent: function(nextComponent, container) { ("production" !== "development" ? invariant( container && ( container.nodeType === ELEMENT_NODE_TYPE || container.nodeType === DOC_NODE_TYPE ), '_registerComponent(...): Target container is not a DOM element.' ) : invariant(container && ( container.nodeType === ELEMENT_NODE_TYPE || container.nodeType === DOC_NODE_TYPE ))); ReactEventEmitter.ensureScrollValueMonitoring(); var reactRootID = ReactMount.registerContainer(container); instancesByReactRootID[reactRootID] = nextComponent; return reactRootID; }, /** * Render a new component into the DOM. * @param {ReactComponent} nextComponent component instance to render * @param {DOMElement} container container to render into * @param {boolean} shouldReuseMarkup if we should skip the markup insertion * @return {ReactComponent} nextComponent */ _renderNewRootComponent: ReactPerf.measure( 'ReactMount', '_renderNewRootComponent', function( nextComponent, container, shouldReuseMarkup) { var componentInstance = instantiateReactComponent(nextComponent); var reactRootID = ReactMount._registerComponent( componentInstance, container ); componentInstance.mountComponentIntoNode( reactRootID, container, shouldReuseMarkup ); if ("production" !== "development") { // Record the root element in case it later gets transplanted. rootElementsByReactRootID[reactRootID] = getReactRootElementInContainer(container); } return componentInstance; } ), /** * Renders a React component into the DOM in the supplied `container`. * * If the React component was previously rendered into `container`, this will * perform an update on it and only mutate the DOM as necessary to reflect the * latest React component. * * @param {ReactComponent} nextComponent Component instance to render. * @param {DOMElement} container DOM element to render into. * @param {?function} callback function triggered on completion * @return {ReactComponent} Component instance rendered in `container`. */ renderComponent: function(nextComponent, container, callback) { var prevComponent = instancesByReactRootID[getReactRootID(container)]; if (prevComponent) { if (shouldUpdateReactComponent(prevComponent, nextComponent)) { return ReactMount._updateRootComponent( prevComponent, nextComponent, container, callback ); } else { ReactMount.unmountComponentAtNode(container); } } var reactRootElement = getReactRootElementInContainer(container); var containerHasReactMarkup = reactRootElement && ReactMount.isRenderedByReact(reactRootElement); var shouldReuseMarkup = containerHasReactMarkup && !prevComponent; var component = ReactMount._renderNewRootComponent( nextComponent, container, shouldReuseMarkup ); callback && callback.call(component); return component; }, /** * Constructs a component instance of `constructor` with `initialProps` and * renders it into the supplied `container`. * * @param {function} constructor React component constructor. * @param {?object} props Initial props of the component instance. * @param {DOMElement} container DOM element to render into. * @return {ReactComponent} Component instance rendered in `container`. */ constructAndRenderComponent: function(constructor, props, container) { return ReactMount.renderComponent(constructor(props), container); }, /** * Constructs a component instance of `constructor` with `initialProps` and * renders it into a container node identified by supplied `id`. * * @param {function} componentConstructor React component constructor * @param {?object} props Initial props of the component instance. * @param {string} id ID of the DOM element to render into. * @return {ReactComponent} Component instance rendered in the container node. */ constructAndRenderComponentByID: function(constructor, props, id) { var domNode = document.getElementById(id); ("production" !== "development" ? invariant( domNode, 'Tried to get element with id of "%s" but it is not present on the page.', id ) : invariant(domNode)); return ReactMount.constructAndRenderComponent(constructor, props, domNode); }, /** * Registers a container node into which React components will be rendered. * This also creates the "reactRoot" ID that will be assigned to the element * rendered within. * * @param {DOMElement} container DOM element to register as a container. * @return {string} The "reactRoot" ID of elements rendered within. */ registerContainer: function(container) { var reactRootID = getReactRootID(container); if (reactRootID) { // If one exists, make sure it is a valid "reactRoot" ID. reactRootID = ReactInstanceHandles.getReactRootIDFromNodeID(reactRootID); } if (!reactRootID) { // No valid "reactRoot" ID found, create one. reactRootID = ReactInstanceHandles.createReactRootID(); } containersByReactRootID[reactRootID] = container; return reactRootID; }, /** * Unmounts and destroys the React component rendered in the `container`. * * @param {DOMElement} container DOM element containing a React component. * @return {boolean} True if a component was found in and unmounted from * `container` */ unmountComponentAtNode: function(container) { var reactRootID = getReactRootID(container); var component = instancesByReactRootID[reactRootID]; if (!component) { return false; } ReactMount.unmountComponentFromNode(component, container); delete instancesByReactRootID[reactRootID]; delete containersByReactRootID[reactRootID]; if ("production" !== "development") { delete rootElementsByReactRootID[reactRootID]; } return true; }, /** * Unmounts a component and removes it from the DOM. * * @param {ReactComponent} instance React component instance. * @param {DOMElement} container DOM element to unmount from. * @final * @internal * @see {ReactMount.unmountComponentAtNode} */ unmountComponentFromNode: function(instance, container) { instance.unmountComponent(); if (container.nodeType === DOC_NODE_TYPE) { container = container.documentElement; } // http://jsperf.com/emptying-a-node while (container.lastChild) { container.removeChild(container.lastChild); } }, /** * Finds the container DOM element that contains React component to which the * supplied DOM `id` belongs. * * @param {string} id The ID of an element rendered by a React component. * @return {?DOMElement} DOM element that contains the `id`. */ findReactContainerForID: function(id) { var reactRootID = ReactInstanceHandles.getReactRootIDFromNodeID(id); var container = containersByReactRootID[reactRootID]; if ("production" !== "development") { var rootElement = rootElementsByReactRootID[reactRootID]; if (rootElement && rootElement.parentNode !== container) { ("production" !== "development" ? invariant( // Call internalGetID here because getID calls isValid which calls // findReactContainerForID (this function). internalGetID(rootElement) === reactRootID, 'ReactMount: Root element ID differed from reactRootID.' ) : invariant(// Call internalGetID here because getID calls isValid which calls // findReactContainerForID (this function). internalGetID(rootElement) === reactRootID)); var containerChild = container.firstChild; if (containerChild && reactRootID === internalGetID(containerChild)) { // If the container has a new child with the same ID as the old // root element, then rootElementsByReactRootID[reactRootID] is // just stale and needs to be updated. The case that deserves a // warning is when the container is empty. rootElementsByReactRootID[reactRootID] = containerChild; } else { console.warn( 'ReactMount: Root element has been removed from its original ' + 'container. New container:', rootElement.parentNode ); } } } return container; }, /** * Finds an element rendered by React with the supplied ID. * * @param {string} id ID of a DOM node in the React component. * @return {DOMElement} Root DOM node of the React component. */ findReactNodeByID: function(id) { var reactRoot = ReactMount.findReactContainerForID(id); return ReactMount.findComponentRoot(reactRoot, id); }, /** * True if the supplied `node` is rendered by React. * * @param {*} node DOM Element to check. * @return {boolean} True if the DOM Element appears to be rendered by React. * @internal */ isRenderedByReact: function(node) { if (node.nodeType !== 1) { // Not a DOMElement, therefore not a React component return false; } var id = ReactMount.getID(node); return id ? id.charAt(0) === SEPARATOR : false; }, /** * Traverses up the ancestors of the supplied node to find a node that is a * DOM representation of a React component. * * @param {*} node * @return {?DOMEventTarget} * @internal */ getFirstReactDOM: function(node) { var current = node; while (current && current.parentNode !== current) { if (ReactMount.isRenderedByReact(current)) { return current; } current = current.parentNode; } return null; }, /** * Finds a node with the supplied `targetID` inside of the supplied * `ancestorNode`. Exploits the ID naming scheme to perform the search * quickly. * * @param {DOMEventTarget} ancestorNode Search from this root. * @pararm {string} targetID ID of the DOM representation of the component. * @return {DOMEventTarget} DOM node with the supplied `targetID`. * @internal */ findComponentRoot: function(ancestorNode, targetID) { var firstChildren = findComponentRootReusableArray; var childIndex = 0; var deepestAncestor = findDeepestCachedAncestor(targetID) || ancestorNode; firstChildren[0] = deepestAncestor.firstChild; firstChildren.length = 1; while (childIndex < firstChildren.length) { var child = firstChildren[childIndex++]; var targetChild; while (child) { var childID = ReactMount.getID(child); if (childID) { // Even if we find the node we're looking for, we finish looping // through its siblings to ensure they're cached so that we don't have // to revisit this node again. Otherwise, we make n^2 calls to getID // when visiting the many children of a single node in order. if (targetID === childID) { targetChild = child; } else if (ReactInstanceHandles.isAncestorIDOf(childID, targetID)) { // If we find a child whose ID is an ancestor of the given ID, // then we can be sure that we only want to search the subtree // rooted at this child, so we can throw out the rest of the // search state. firstChildren.length = childIndex = 0; firstChildren.push(child.firstChild); } } else { // If this child had no ID, then there's a chance that it was // injected automatically by the browser, as when a `<table>` // element sprouts an extra `<tbody>` child as a side effect of // `.innerHTML` parsing. Optimistically continue down this // branch, but not before examining the other siblings. firstChildren.push(child.firstChild); } child = child.nextSibling; } if (targetChild) { // Emptying firstChildren/findComponentRootReusableArray is // not necessary for correctness, but it helps the GC reclaim // any nodes that were left at the end of the search. firstChildren.length = 0; return targetChild; } } firstChildren.length = 0; ("production" !== "development" ? invariant( false, 'findComponentRoot(..., %s): Unable to find element. This probably ' + 'means the DOM was unexpectedly mutated (e.g., by the browser), ' + 'usually due to forgetting a <tbody> when using tables or nesting <p> ' + 'or <a> tags. Try inspecting the child nodes of the element with React ' + 'ID `%s`.', targetID, ReactMount.getID(ancestorNode) ) : invariant(false)); }, /** * React ID utilities. */ getReactRootID: getReactRootID, getID: getID, setID: setID, getNode: getNode, purgeID: purgeID }; module.exports = ReactMount; },{"./DOMProperty":8,"./ReactEventEmitter":48,"./ReactInstanceHandles":53,"./ReactPerf":60,"./containsNode":89,"./getReactRootElementInContainer":107,"./instantiateReactComponent":111,"./invariant":112,"./shouldUpdateReactComponent":131}],56:[function(_dereq_,module,exports){ /** * Copyright 2013-2014 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. * * @providesModule ReactMountReady */ "use strict"; var PooledClass = _dereq_("./PooledClass"); var mixInto = _dereq_("./mixInto"); /** * 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 `ReactMountReady.getPooled()`. * * @param {?array<function>} initialCollection * @class ReactMountReady * @implements PooledClass * @internal */ function ReactMountReady(initialCollection) { this._queue = initialCollection || null; } mixInto(ReactMountReady, { /** * Enqueues a callback to be invoked when `notifyAll` is invoked. This is used * to enqueue calls to `componentDidMount` and `componentDidUpdate`. * * @param {ReactComponent} component Component being rendered. * @param {function(DOMElement)} callback Invoked when `notifyAll` is invoked. * @internal */ enqueue: function(component, callback) { this._queue = this._queue || []; this._queue.push({component: component, callback: callback}); }, /** * Invokes all enqueued callbacks and clears the queue. This is invoked after * the DOM representation of a component has been created or updated. * * @internal */ notifyAll: function() { var queue = this._queue; if (queue) { this._queue = null; for (var i = 0, l = queue.length; i < l; i++) { var component = queue[i].component; var callback = queue[i].callback; callback.call(component); } queue.length = 0; } }, /** * Resets the internal queue. * * @internal */ reset: function() { this._queue = null; }, /** * `PooledClass` looks for this. */ destructor: function() { this.reset(); } }); PooledClass.addPoolingTo(ReactMountReady); module.exports = ReactMountReady; },{"./PooledClass":23,"./mixInto":124}],57:[function(_dereq_,module,exports){ /** * Copyright 2013-2014 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. * * @providesModule ReactMultiChild * @typechecks static-only */ "use strict"; var ReactComponent = _dereq_("./ReactComponent"); var ReactMultiChildUpdateTypes = _dereq_("./ReactMultiChildUpdateTypes"); var flattenChildren = _dereq_("./flattenChildren"); var instantiateReactComponent = _dereq_("./instantiateReactComponent"); var shouldUpdateReactComponent = _dereq_("./shouldUpdateReactComponent"); /** * Updating children of a component may trigger recursive updates. The depth is * used to batch recursive updates to render markup more efficiently. * * @type {number} * @private */ var updateDepth = 0; /** * Queue of update configuration objects. * * Each object has a `type` property that is in `ReactMultiChildUpdateTypes`. * * @type {array<object>} * @private */ var updateQueue = []; /** * Queue of markup to be rendered. * * @type {array<string>} * @private */ var markupQueue = []; /** * Enqueues markup to be rendered and inserted at a supplied index. * * @param {string} parentID ID of the parent component. * @param {string} markup Markup that renders into an element. * @param {number} toIndex Destination index. * @private */ function enqueueMarkup(parentID, markup, toIndex) { // NOTE: Null values reduce hidden classes. updateQueue.push({ parentID: parentID, parentNode: null, type: ReactMultiChildUpdateTypes.INSERT_MARKUP, markupIndex: markupQueue.push(markup) - 1, textContent: null, fromIndex: null, toIndex: toIndex }); } /** * Enqueues moving an existing element to another index. * * @param {string} parentID ID of the parent component. * @param {number} fromIndex Source index of the existing element. * @param {number} toIndex Destination index of the element. * @private */ function enqueueMove(parentID, fromIndex, toIndex) { // NOTE: Null values reduce hidden classes. updateQueue.push({ parentID: parentID, parentNode: null, type: ReactMultiChildUpdateTypes.MOVE_EXISTING, markupIndex: null, textContent: null, fromIndex: fromIndex, toIndex: toIndex }); } /** * Enqueues removing an element at an index. * * @param {string} parentID ID of the parent component. * @param {number} fromIndex Index of the element to remove. * @private */ function enqueueRemove(parentID, fromIndex) { // NOTE: Null values reduce hidden classes. updateQueue.push({ parentID: parentID, parentNode: null, type: ReactMultiChildUpdateTypes.REMOVE_NODE, markupIndex: null, textContent: null, fromIndex: fromIndex, toIndex: null }); } /** * Enqueues setting the text content. * * @param {string} parentID ID of the parent component. * @param {string} textContent Text content to set. * @private */ function enqueueTextContent(parentID, textContent) { // NOTE: Null values reduce hidden classes. updateQueue.push({ parentID: parentID, parentNode: null, type: ReactMultiChildUpdateTypes.TEXT_CONTENT, markupIndex: null, textContent: textContent, fromIndex: null, toIndex: null }); } /** * Processes any enqueued updates. * * @private */ function processQueue() { if (updateQueue.length) { ReactComponent.BackendIDOperations.dangerouslyProcessChildrenUpdates( updateQueue, markupQueue ); clearQueue(); } } /** * Clears any enqueued updates. * * @private */ function clearQueue() { updateQueue.length = 0; markupQueue.length = 0; } /** * ReactMultiChild are capable of reconciling multiple children. * * @class ReactMultiChild * @internal */ var ReactMultiChild = { /** * Provides common functionality for components that must reconcile multiple * children. This is used by `ReactDOMComponent` to mount, update, and * unmount child components. * * @lends {ReactMultiChild.prototype} */ Mixin: { /** * 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) { var children = flattenChildren(nestedChildren); var mountImages = []; var index = 0; this._renderedChildren = children; for (var name in children) { var child = children[name]; if (children.hasOwnProperty(name)) { // The rendered children must be turned into instances as they're // mounted. var childInstance = instantiateReactComponent(child); children[name] = childInstance; // Inlined for performance, see `ReactInstanceHandles.createReactID`. var rootID = this._rootNodeID + name; var mountImage = childInstance.mountComponent( rootID, transaction, this._mountDepth + 1 ); childInstance._mountIndex = index; mountImages.push(mountImage); index++; } } return mountImages; }, /** * Replaces any rendered children with a text content string. * * @param {string} nextContent String of content. * @internal */ updateTextContent: function(nextContent) { updateDepth++; var errorThrown = true; try { var prevChildren = this._renderedChildren; // Remove any rendered children. for (var name in prevChildren) { if (prevChildren.hasOwnProperty(name)) { this._unmountChildByName(prevChildren[name], name); } } // Set new text content. this.setTextContent(nextContent); errorThrown = false; } finally { updateDepth--; if (!updateDepth) { errorThrown ? clearQueue() : processQueue(); } } }, /** * Updates the rendered children with new children. * * @param {?object} nextNestedChildren Nested child maps. * @param {ReactReconcileTransaction} transaction * @internal */ updateChildren: function(nextNestedChildren, transaction) { updateDepth++; var errorThrown = true; try { this._updateChildren(nextNestedChildren, transaction); errorThrown = false; } finally { updateDepth--; if (!updateDepth) { errorThrown ? clearQueue() : processQueue(); } } }, /** * Improve performance by isolating this hot code path from the try/catch * block in `updateChildren`. * * @param {?object} nextNestedChildren Nested child maps. * @param {ReactReconcileTransaction} transaction * @final * @protected */ _updateChildren: function(nextNestedChildren, transaction) { var nextChildren = flattenChildren(nextNestedChildren); var prevChildren = this._renderedChildren; if (!nextChildren && !prevChildren) { return; } var name; // `nextIndex` will increment for each child in `nextChildren`, but // `lastIndex` will be the last index visited in `prevChildren`. var lastIndex = 0; var nextIndex = 0; for (name in nextChildren) { if (!nextChildren.hasOwnProperty(name)) { continue; } var prevChild = prevChildren && prevChildren[name]; var nextChild = nextChildren[name]; if (shouldUpdateReactComponent(prevChild, nextChild)) { this.moveChild(prevChild, nextIndex, lastIndex); lastIndex = Math.max(prevChild._mountIndex, lastIndex); prevChild.receiveComponent(nextChild, transaction); prevChild._mountIndex = nextIndex; } else { if (prevChild) { // Update `lastIndex` before `_mountIndex` gets unset by unmounting. lastIndex = Math.max(prevChild._mountIndex, lastIndex); this._unmountChildByName(prevChild, name); } // The child must be instantiated before it's mounted. var nextChildInstance = instantiateReactComponent(nextChild); this._mountChildByNameAtIndex( nextChildInstance, name, nextIndex, transaction ); } nextIndex++; } // Remove children that are no longer present. for (name in prevChildren) { if (prevChildren.hasOwnProperty(name) && !(nextChildren && nextChildren[name])) { this._unmountChildByName(prevChildren[name], name); } } }, /** * Unmounts all rendered children. This should be used to clean up children * when this component is unmounted. * * @internal */ unmountChildren: function() { var renderedChildren = this._renderedChildren; for (var name in renderedChildren) { var renderedChild = renderedChildren[name]; // TODO: When is this not true? if (renderedChild.unmountComponent) { renderedChild.unmountComponent(); } } 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, 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) { enqueueMove(this._rootNodeID, child._mountIndex, toIndex); } }, /** * Creates a child component. * * @param {ReactComponent} child Component to create. * @param {string} mountImage Markup to insert. * @protected */ createChild: function(child, mountImage) { enqueueMarkup(this._rootNodeID, mountImage, child._mountIndex); }, /** * Removes a child component. * * @param {ReactComponent} child Child to remove. * @protected */ removeChild: function(child) { enqueueRemove(this._rootNodeID, child._mountIndex); }, /** * Sets this text content string. * * @param {string} textContent Text content to set. * @protected */ setTextContent: function(textContent) { enqueueTextContent(this._rootNodeID, textContent); }, /** * 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 */ _mountChildByNameAtIndex: function(child, name, index, transaction) { // Inlined for performance, see `ReactInstanceHandles.createReactID`. var rootID = this._rootNodeID + name; var mountImage = child.mountComponent( rootID, transaction, this._mountDepth + 1 ); child._mountIndex = index; this.createChild(child, mountImage); this._renderedChildren = this._renderedChildren || {}; this._renderedChildren[name] = child; }, /** * Unmounts a rendered child by name. * * NOTE: This is part of `updateChildren` and is here for readability. * * @param {ReactComponent} child Component to unmount. * @param {string} name Name of the child in `this._renderedChildren`. * @private */ _unmountChildByName: function(child, name) { // TODO: When is this not true? if (ReactComponent.isValidComponent(child)) { this.removeChild(child); child._mountIndex = null; child.unmountComponent(); delete this._renderedChildren[name]; } } } }; module.exports = ReactMultiChild; },{"./ReactComponent":27,"./ReactMultiChildUpdateTypes":58,"./flattenChildren":99,"./instantiateReactComponent":111,"./shouldUpdateReactComponent":131}],58:[function(_dereq_,module,exports){ /** * Copyright 2013-2014 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. * * @providesModule ReactMultiChildUpdateTypes */ "use strict"; var keyMirror = _dereq_("./keyMirror"); /** * When a component's children are updated, a series of update configuration * objects are created in order to batch and serialize the required changes. * * Enumerates all the possible types of update configurations. * * @internal */ var ReactMultiChildUpdateTypes = keyMirror({ INSERT_MARKUP: null, MOVE_EXISTING: null, REMOVE_NODE: null, TEXT_CONTENT: null }); module.exports = ReactMultiChildUpdateTypes; },{"./keyMirror":118}],59:[function(_dereq_,module,exports){ /** * Copyright 2013-2014 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. * * @providesModule ReactOwner */ "use strict"; var emptyObject = _dereq_("./emptyObject"); var invariant = _dereq_("./invariant"); /** * 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 = { /** * @param {?object} object * @return {boolean} True if `object` is a valid owner. * @final */ isValidOwner: function(object) { return !!( object && typeof object.attachRef === 'function' && typeof object.detachRef === 'function' ); }, /** * 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) { ("production" !== "development" ? invariant( ReactOwner.isValidOwner(owner), 'addComponentAsRefTo(...): Only a ReactOwner can have refs. This ' + 'usually means that you\'re trying to add a ref to a component that ' + 'doesn\'t have an owner (that is, was not created inside of another ' + 'component\'s `render` method). Try rendering this component inside of ' + 'a new top-level component which will hold the ref.' ) : invariant(ReactOwner.isValidOwner(owner))); 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) { ("production" !== "development" ? invariant( ReactOwner.isValidOwner(owner), 'removeComponentAsRefFrom(...): Only a ReactOwner can have refs. This ' + 'usually means that you\'re trying to remove a ref to a component that ' + 'doesn\'t have an owner (that is, was not created inside of another ' + 'component\'s `render` method). Try rendering this component inside of ' + 'a new top-level component which will hold the ref.' ) : invariant(ReactOwner.isValidOwner(owner))); // Check that `component` is still the current ref because we do not want to // detach the ref if another component stole it. if (owner.refs[ref] === component) { owner.detachRef(ref); } }, /** * A ReactComponent must mix this in to have refs. * * @lends {ReactOwner.prototype} */ Mixin: { construct: function() { this.refs = emptyObject; }, /** * 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) { ("production" !== "development" ? invariant( component.isOwnedBy(this), 'attachRef(%s, ...): Only a component\'s owner can store a ref to it.', ref ) : invariant(component.isOwnedBy(this))); var refs = this.refs === emptyObject ? (this.refs = {}) : this.refs; refs[ref] = component; }, /** * Detaches a reference name. * * @param {string} ref Name to dereference. * @final * @private */ detachRef: function(ref) { delete this.refs[ref]; } } }; module.exports = ReactOwner; },{"./emptyObject":97,"./invariant":112}],60:[function(_dereq_,module,exports){ /** * Copyright 2013-2014 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. * * @providesModule ReactPerf * @typechecks static-only */ "use strict"; /** * ReactPerf is a general AOP system designed to measure performance. This * module only has the hooks: see ReactDefaultPerf for the analysis tool. */ var ReactPerf = { /** * Boolean to enable/disable measurement. Set to false by default to prevent * accidental logging and perf loss. */ enableMeasure: false, /** * Holds onto the measure function in use. By default, don't measure * anything, but we'll override this if we inject a measure function. */ storedMeasure: _noMeasure, /** * Use this to wrap methods you want to measure. Zero overhead in production. * * @param {string} objName * @param {string} fnName * @param {function} func * @return {function} */ measure: function(objName, fnName, func) { if ("production" !== "development") { var measuredFunc = null; return function() { if (ReactPerf.enableMeasure) { if (!measuredFunc) { measuredFunc = ReactPerf.storedMeasure(objName, fnName, func); } return measuredFunc.apply(this, arguments); } return func.apply(this, arguments); }; } return func; }, injection: { /** * @param {function} measure */ injectMeasure: function(measure) { ReactPerf.storedMeasure = measure; } } }; /** * Simply passes through the measured function, without measuring it. * * @param {string} objName * @param {string} fnName * @param {function} func * @return {function} */ function _noMeasure(objName, fnName, func) { return func; } module.exports = ReactPerf; },{}],61:[function(_dereq_,module,exports){ /** * Copyright 2013-2014 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. * * @providesModule ReactPropTransferer */ "use strict"; var emptyFunction = _dereq_("./emptyFunction"); var invariant = _dereq_("./invariant"); var joinClasses = _dereq_("./joinClasses"); var merge = _dereq_("./merge"); /** * 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); } }; } /** * 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), /** * Never transfer the `key` prop. */ key: emptyFunction, /** * Never transfer the `ref` prop. */ ref: emptyFunction, /** * Transfer the `style` prop (which is an object) by merging them. */ style: createTransferStrategy(merge) }; /** * ReactPropTransferer are capable of transferring props to another component * using a `transferPropsTo` method. * * @class ReactPropTransferer */ var ReactPropTransferer = { TransferStrategies: TransferStrategies, /** * 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) { var props = merge(oldProps); 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; }, /** * @lends {ReactPropTransferer.prototype} */ Mixin: { /** * Transfer props from this component to a target component. * * Props that do not have an explicit transfer strategy will be transferred * only if the target component does not already have the prop set. * * This is usually used to pass down props to a returned root component. * * @param {ReactComponent} component Component receiving the properties. * @return {ReactComponent} The supplied `component`. * @final * @protected */ transferPropsTo: function(component) { ("production" !== "development" ? invariant( component._owner === this, '%s: You can\'t call transferPropsTo() on a component that you ' + 'don\'t own, %s. This usually means you are calling ' + 'transferPropsTo() on a component passed in as props or children.', this.constructor.displayName, component.constructor.displayName ) : invariant(component._owner === this)); component.props = ReactPropTransferer.mergeProps( component.props, this.props ); return component; } } }; module.exports = ReactPropTransferer; },{"./emptyFunction":96,"./invariant":112,"./joinClasses":117,"./merge":121}],62:[function(_dereq_,module,exports){ /** * Copyright 2013-2014 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. * * @providesModule ReactPropTypeLocationNames */ "use strict"; var ReactPropTypeLocationNames = {}; if ("production" !== "development") { ReactPropTypeLocationNames = { prop: 'prop', context: 'context', childContext: 'child context' }; } module.exports = ReactPropTypeLocationNames; },{}],63:[function(_dereq_,module,exports){ /** * Copyright 2013-2014 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. * * @providesModule ReactPropTypeLocations */ "use strict"; var keyMirror = _dereq_("./keyMirror"); var ReactPropTypeLocations = keyMirror({ prop: null, context: null, childContext: null }); module.exports = ReactPropTypeLocations; },{"./keyMirror":118}],64:[function(_dereq_,module,exports){ /** * Copyright 2013-2014 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. * * @providesModule ReactPropTypes */ "use strict"; var ReactComponent = _dereq_("./ReactComponent"); var ReactPropTypeLocationNames = _dereq_("./ReactPropTypeLocationNames"); var warning = _dereq_("./warning"); var createObjectFrom = _dereq_("./createObjectFrom"); /** * Collection of methods that allow declaration and validation of props that are * supplied to React components. Example usage: * * var Props = require('ReactPropTypes'); * var MyArticle = React.createClass({ * propTypes: { * // An optional string prop named "description". * description: Props.string, * * // A required enum prop named "category". * category: Props.oneOf(['News','Photos']).isRequired, * * // A prop named "dialog" that requires an instance of Dialog. * dialog: Props.instanceOf(Dialog).isRequired * }, * render: function() { ... } * }); * * A more formal specification of how these methods are used: * * type := array|bool|func|object|number|string|oneOf([...])|instanceOf(...) * decl := ReactPropTypes.{type}(.isRequired)? * * Each and every declaration produces a function with the same signature. This * allows the creation of custom validation functions. For example: * * var Props = require('ReactPropTypes'); * var MyLink = React.createClass({ * propTypes: { * // An optional string or URI prop named "href". * href: function(props, propName, componentName) { * var propValue = props[propName]; * warning( * propValue == null || * typeof propValue === 'string' || * propValue instanceof URI, * 'Invalid `%s` supplied to `%s`, expected string or URI.', * propName, * componentName * ); * } * }, * render: function() { ... } * }); * * @internal */ var Props = { array: createPrimitiveTypeChecker('array'), bool: createPrimitiveTypeChecker('boolean'), func: createPrimitiveTypeChecker('function'), number: createPrimitiveTypeChecker('number'), object: createPrimitiveTypeChecker('object'), string: createPrimitiveTypeChecker('string'), shape: createShapeTypeChecker, oneOf: createEnumTypeChecker, oneOfType: createUnionTypeChecker, arrayOf: createArrayOfTypeChecker, instanceOf: createInstanceTypeChecker, renderable: createRenderableTypeChecker(), component: createComponentTypeChecker(), any: createAnyTypeChecker() }; var ANONYMOUS = '<<anonymous>>'; function isRenderable(propValue) { switch(typeof propValue) { case 'number': case 'string': return true; case 'object': if (Array.isArray(propValue)) { return propValue.every(isRenderable); } if (ReactComponent.isValidComponent(propValue)) { return true; } for (var k in propValue) { if (!isRenderable(propValue[k])) { return false; } } return true; default: return false; } } // Equivalent of typeof but with special handling for arrays function getPropType(propValue) { var propType = typeof propValue; if (propType === 'object' && Array.isArray(propValue)) { return 'array'; } return propType; } function createAnyTypeChecker() { function validateAnyType( shouldWarn, propValue, propName, componentName, location ) { return true; // is always valid } return createChainableTypeChecker(validateAnyType); } function createPrimitiveTypeChecker(expectedType) { function validatePrimitiveType( shouldWarn, propValue, propName, componentName, location ) { var propType = getPropType(propValue); var isValid = propType === expectedType; if (shouldWarn) { ("production" !== "development" ? warning( isValid, 'Invalid %s `%s` of type `%s` supplied to `%s`, expected `%s`.', ReactPropTypeLocationNames[location], propName, propType, componentName, expectedType ) : null); } return isValid; } return createChainableTypeChecker(validatePrimitiveType); } function createEnumTypeChecker(expectedValues) { var expectedEnum = createObjectFrom(expectedValues); function validateEnumType( shouldWarn, propValue, propName, componentName, location ) { var isValid = expectedEnum[propValue]; if (shouldWarn) { ("production" !== "development" ? warning( isValid, 'Invalid %s `%s` supplied to `%s`, expected one of %s.', ReactPropTypeLocationNames[location], propName, componentName, JSON.stringify(Object.keys(expectedEnum)) ) : null); } return isValid; } return createChainableTypeChecker(validateEnumType); } function createShapeTypeChecker(shapeTypes) { function validateShapeType( shouldWarn, propValue, propName, componentName, location ) { var propType = getPropType(propValue); var isValid = propType === 'object'; if (isValid) { for (var key in shapeTypes) { var checker = shapeTypes[key]; if (checker && !checker(propValue, key, componentName, location)) { return false; } } } if (shouldWarn) { ("production" !== "development" ? warning( isValid, 'Invalid %s `%s` of type `%s` supplied to `%s`, expected `object`.', ReactPropTypeLocationNames[location], propName, propType, componentName ) : null); } return isValid; } return createChainableTypeChecker(validateShapeType); } function createInstanceTypeChecker(expectedClass) { function validateInstanceType( shouldWarn, propValue, propName, componentName, location ) { var isValid = propValue instanceof expectedClass; if (shouldWarn) { ("production" !== "development" ? warning( isValid, 'Invalid %s `%s` supplied to `%s`, expected instance of `%s`.', ReactPropTypeLocationNames[location], propName, componentName, expectedClass.name || ANONYMOUS ) : null); } return isValid; } return createChainableTypeChecker(validateInstanceType); } function createArrayOfTypeChecker(propTypeChecker) { function validateArrayType( shouldWarn, propValue, propName, componentName, location ) { var isValid = Array.isArray(propValue); if (isValid) { for (var i = 0; i < propValue.length; i++) { if (!propTypeChecker(propValue, i, componentName, location)) { return false; } } } if (shouldWarn) { ("production" !== "development" ? warning( isValid, 'Invalid %s `%s` supplied to `%s`, expected an array.', ReactPropTypeLocationNames[location], propName, componentName ) : null); } return isValid; } return createChainableTypeChecker(validateArrayType); } function createRenderableTypeChecker() { function validateRenderableType( shouldWarn, propValue, propName, componentName, location ) { var isValid = isRenderable(propValue); if (shouldWarn) { ("production" !== "development" ? warning( isValid, 'Invalid %s `%s` supplied to `%s`, expected a renderable prop.', ReactPropTypeLocationNames[location], propName, componentName ) : null); } return isValid; } return createChainableTypeChecker(validateRenderableType); } function createComponentTypeChecker() { function validateComponentType( shouldWarn, propValue, propName, componentName, location ) { var isValid = ReactComponent.isValidComponent(propValue); if (shouldWarn) { ("production" !== "development" ? warning( isValid, 'Invalid %s `%s` supplied to `%s`, expected a React component.', ReactPropTypeLocationNames[location], propName, componentName ) : null); } return isValid; } return createChainableTypeChecker(validateComponentType); } function createUnionTypeChecker(arrayOfValidators) { return function(props, propName, componentName, location) { var isValid = false; for (var ii = 0; ii < arrayOfValidators.length; ii++) { var validate = arrayOfValidators[ii]; if (typeof validate.weak === 'function') { validate = validate.weak; } if (validate(props, propName, componentName, location)) { isValid = true; break; } } ("production" !== "development" ? warning( isValid, 'Invalid %s `%s` supplied to `%s`.', ReactPropTypeLocationNames[location], propName, componentName || ANONYMOUS ) : null); return isValid; }; } function createChainableTypeChecker(validate) { function checkType( isRequired, shouldWarn, props, propName, componentName, location ) { var propValue = props[propName]; if (propValue != null) { // Only validate if there is a value to check. return validate( shouldWarn, propValue, propName, componentName || ANONYMOUS, location ); } else { var isValid = !isRequired; if (shouldWarn) { ("production" !== "development" ? warning( isValid, 'Required %s `%s` was not specified in `%s`.', ReactPropTypeLocationNames[location], propName, componentName || ANONYMOUS ) : null); } return isValid; } } var checker = checkType.bind(null, false, true); checker.weak = checkType.bind(null, false, false); checker.isRequired = checkType.bind(null, true, true); checker.weak.isRequired = checkType.bind(null, true, false); checker.isRequired.weak = checker.weak.isRequired; return checker; } module.exports = Props; },{"./ReactComponent":27,"./ReactPropTypeLocationNames":62,"./createObjectFrom":94,"./warning":134}],65:[function(_dereq_,module,exports){ /** * Copyright 2013-2014 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. * * @providesModule ReactPutListenerQueue */ "use strict"; var PooledClass = _dereq_("./PooledClass"); var ReactEventEmitter = _dereq_("./ReactEventEmitter"); var mixInto = _dereq_("./mixInto"); function ReactPutListenerQueue() { this.listenersToPut = []; } mixInto(ReactPutListenerQueue, { enqueuePutListener: function(rootNodeID, propKey, propValue) { this.listenersToPut.push({ rootNodeID: rootNodeID, propKey: propKey, propValue: propValue }); }, putListeners: function() { for (var i = 0; i < this.listenersToPut.length; i++) { var listenerToPut = this.listenersToPut[i]; ReactEventEmitter.putListener( listenerToPut.rootNodeID, listenerToPut.propKey, listenerToPut.propValue ); } }, reset: function() { this.listenersToPut.length = 0; }, destructor: function() { this.reset(); } }); PooledClass.addPoolingTo(ReactPutListenerQueue); module.exports = ReactPutListenerQueue; },{"./PooledClass":23,"./ReactEventEmitter":48,"./mixInto":124}],66:[function(_dereq_,module,exports){ /** * Copyright 2013-2014 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. * * @providesModule ReactReconcileTransaction * @typechecks static-only */ "use strict"; var PooledClass = _dereq_("./PooledClass"); var ReactEventEmitter = _dereq_("./ReactEventEmitter"); var ReactInputSelection = _dereq_("./ReactInputSelection"); var ReactMountReady = _dereq_("./ReactMountReady"); var ReactPutListenerQueue = _dereq_("./ReactPutListenerQueue"); var Transaction = _dereq_("./Transaction"); var mixInto = _dereq_("./mixInto"); /** * 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 `ReactEventEmitter` before the * reconciliation. */ initialize: function() { var currentlyEnabled = ReactEventEmitter.isEnabled(); ReactEventEmitter.setEnabled(false); return currentlyEnabled; }, /** * @param {boolean} previouslyEnabled Enabled status of `ReactEventEmitter` * before the reconciliation occured. `close` restores the previous value. */ close: function(previouslyEnabled) { ReactEventEmitter.setEnabled(previouslyEnabled); } }; /** * Provides a `ReactMountReady` queue for collecting `onDOMReady` callbacks * during the performing of 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(); } }; var PUT_LISTENER_QUEUEING = { initialize: function() { this.putListenerQueue.reset(); }, close: function() { this.putListenerQueue.putListeners(); } }; /** * 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 = [ PUT_LISTENER_QUEUEING, SELECTION_RESTORATION, EVENT_SUPPRESSION, ON_DOM_READY_QUEUEING ]; /** * 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() { 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 // `ReactTextComponent` checks it in `mountComponent`.` this.renderToStaticMarkup = false; this.reactMountReady = ReactMountReady.getPooled(null); this.putListenerQueue = ReactPutListenerQueue.getPooled(); } var Mixin = { /** * @see Transaction * @abstract * @final * @return {array<object>} List of operation wrap proceedures. * TODO: convert to array<TransactionWrapper> */ getTransactionWrappers: function() { return TRANSACTION_WRAPPERS; }, /** * @return {object} The queue to collect `onDOMReady` callbacks with. * TODO: convert to ReactMountReady */ getReactMountReady: function() { return this.reactMountReady; }, getPutListenerQueue: function() { return this.putListenerQueue; }, /** * `PooledClass` looks for this, and will invoke this before allowing this * instance to be resused. */ destructor: function() { ReactMountReady.release(this.reactMountReady); this.reactMountReady = null; ReactPutListenerQueue.release(this.putListenerQueue); this.putListenerQueue = null; } }; mixInto(ReactReconcileTransaction, Transaction.Mixin); mixInto(ReactReconcileTransaction, Mixin); PooledClass.addPoolingTo(ReactReconcileTransaction); module.exports = ReactReconcileTransaction; },{"./PooledClass":23,"./ReactEventEmitter":48,"./ReactInputSelection":52,"./ReactMountReady":56,"./ReactPutListenerQueue":65,"./Transaction":85,"./mixInto":124}],67:[function(_dereq_,module,exports){ /** * Copyright 2013-2014 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. * * @providesModule ReactRootIndex * @typechecks */ "use strict"; var ReactRootIndexInjection = { /** * @param {function} _createReactRootIndex */ injectCreateReactRootIndex: function(_createReactRootIndex) { ReactRootIndex.createReactRootIndex = _createReactRootIndex; } }; var ReactRootIndex = { createReactRootIndex: null, injection: ReactRootIndexInjection }; module.exports = ReactRootIndex; },{}],68:[function(_dereq_,module,exports){ /** * Copyright 2013-2014 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 static-only * @providesModule ReactServerRendering */ "use strict"; var ReactComponent = _dereq_("./ReactComponent"); var ReactInstanceHandles = _dereq_("./ReactInstanceHandles"); var ReactMarkupChecksum = _dereq_("./ReactMarkupChecksum"); var ReactServerRenderingTransaction = _dereq_("./ReactServerRenderingTransaction"); var instantiateReactComponent = _dereq_("./instantiateReactComponent"); var invariant = _dereq_("./invariant"); /** * @param {ReactComponent} component * @return {string} the HTML markup */ function renderComponentToString(component) { ("production" !== "development" ? invariant( ReactComponent.isValidComponent(component), 'renderComponentToString(): You must pass a valid ReactComponent.' ) : invariant(ReactComponent.isValidComponent(component))); ("production" !== "development" ? invariant( !(arguments.length === 2 && typeof arguments[1] === 'function'), 'renderComponentToString(): This function became synchronous and now ' + 'returns the generated markup. Please remove the second parameter.' ) : invariant(!(arguments.length === 2 && typeof arguments[1] === 'function'))); var transaction; try { var id = ReactInstanceHandles.createReactRootID(); transaction = ReactServerRenderingTransaction.getPooled(false); return transaction.perform(function() { var componentInstance = instantiateReactComponent(component); var markup = componentInstance.mountComponent(id, transaction, 0); return ReactMarkupChecksum.addChecksumToMarkup(markup); }, null); } finally { ReactServerRenderingTransaction.release(transaction); } } /** * @param {ReactComponent} component * @return {string} the HTML markup, without the extra React ID and checksum * (for generating static pages) */ function renderComponentToStaticMarkup(component) { ("production" !== "development" ? invariant( ReactComponent.isValidComponent(component), 'renderComponentToStaticMarkup(): You must pass a valid ReactComponent.' ) : invariant(ReactComponent.isValidComponent(component))); var transaction; try { var id = ReactInstanceHandles.createReactRootID(); transaction = ReactServerRenderingTransaction.getPooled(true); return transaction.perform(function() { var componentInstance = instantiateReactComponent(component); return componentInstance.mountComponent(id, transaction, 0); }, null); } finally { ReactServerRenderingTransaction.release(transaction); } } module.exports = { renderComponentToString: renderComponentToString, renderComponentToStaticMarkup: renderComponentToStaticMarkup }; },{"./ReactComponent":27,"./ReactInstanceHandles":53,"./ReactMarkupChecksum":54,"./ReactServerRenderingTransaction":69,"./instantiateReactComponent":111,"./invariant":112}],69:[function(_dereq_,module,exports){ /** * Copyright 2014 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. * * @providesModule ReactServerRenderingTransaction * @typechecks */ "use strict"; var PooledClass = _dereq_("./PooledClass"); var ReactMountReady = _dereq_("./ReactMountReady"); var ReactPutListenerQueue = _dereq_("./ReactPutListenerQueue"); var Transaction = _dereq_("./Transaction"); var emptyFunction = _dereq_("./emptyFunction"); var mixInto = _dereq_("./mixInto"); /** * Provides a `ReactMountReady` queue for collecting `onDOMReady` callbacks * during the performing of the transaction. */ var ON_DOM_READY_QUEUEING = { /** * Initializes the internal `onDOMReady` queue. */ initialize: function() { this.reactMountReady.reset(); }, close: emptyFunction }; var PUT_LISTENER_QUEUEING = { initialize: function() { this.putListenerQueue.reset(); }, close: emptyFunction }; /** * 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 = [ PUT_LISTENER_QUEUEING, ON_DOM_READY_QUEUEING ]; /** * @class ReactServerRenderingTransaction * @param {boolean} renderToStaticMarkup */ function ReactServerRenderingTransaction(renderToStaticMarkup) { this.reinitializeTransaction(); this.renderToStaticMarkup = renderToStaticMarkup; this.reactMountReady = ReactMountReady.getPooled(null); this.putListenerQueue = ReactPutListenerQueue.getPooled(); } var Mixin = { /** * @see Transaction * @abstract * @final * @return {array} Empty list of operation wrap proceedures. */ getTransactionWrappers: function() { return TRANSACTION_WRAPPERS; }, /** * @return {object} The queue to collect `onDOMReady` callbacks with. * TODO: convert to ReactMountReady */ getReactMountReady: function() { return this.reactMountReady; }, getPutListenerQueue: function() { return this.putListenerQueue; }, /** * `PooledClass` looks for this, and will invoke this before allowing this * instance to be resused. */ destructor: function() { ReactMountReady.release(this.reactMountReady); this.reactMountReady = null; ReactPutListenerQueue.release(this.putListenerQueue); this.putListenerQueue = null; } }; mixInto(ReactServerRenderingTransaction, Transaction.Mixin); mixInto(ReactServerRenderingTransaction, Mixin); PooledClass.addPoolingTo(ReactServerRenderingTransaction); module.exports = ReactServerRenderingTransaction; },{"./PooledClass":23,"./ReactMountReady":56,"./ReactPutListenerQueue":65,"./Transaction":85,"./emptyFunction":96,"./mixInto":124}],70:[function(_dereq_,module,exports){ /** * Copyright 2013-2014 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. * * @providesModule ReactTextComponent * @typechecks static-only */ "use strict"; var DOMPropertyOperations = _dereq_("./DOMPropertyOperations"); var ReactBrowserComponentMixin = _dereq_("./ReactBrowserComponentMixin"); var ReactComponent = _dereq_("./ReactComponent"); var escapeTextForBrowser = _dereq_("./escapeTextForBrowser"); var mixInto = _dereq_("./mixInto"); /** * 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 in elements 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 ReactTextComponent * @extends ReactComponent * @internal */ var ReactTextComponent = function(initialText) { this.construct({text: initialText}); }; /** * Used to clone the text descriptor object before it's mounted. * * @param {object} props * @return {object} A new ReactTextComponent instance */ ReactTextComponent.ConvenienceConstructor = function(props) { return new ReactTextComponent(props.text); }; mixInto(ReactTextComponent, ReactComponent.Mixin); mixInto(ReactTextComponent, ReactBrowserComponentMixin); mixInto(ReactTextComponent, { /** * Creates the markup for this text node. This node is not intended to have * any features besides containing text content. * * @param {string} rootID DOM ID of the root node. * @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction * @param {number} mountDepth number of components in the owner hierarchy * @return {string} Markup for this text node. * @internal */ mountComponent: function(rootID, transaction, mountDepth) { ReactComponent.Mixin.mountComponent.call( this, rootID, transaction, mountDepth ); var escapedText = escapeTextForBrowser(this.props.text); if (transaction.renderToStaticMarkup) { // Normally we'd wrap this in a `span` 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 ( '<span ' + DOMPropertyOperations.createMarkupForID(rootID) + '>' + escapedText + '</span>' ); }, /** * Updates this component by updating the text content. * * @param {object} nextComponent Contains the next text content. * @param {ReactReconcileTransaction} transaction * @internal */ receiveComponent: function(nextComponent, transaction) { var nextProps = nextComponent.props; if (nextProps.text !== this.props.text) { this.props.text = nextProps.text; ReactComponent.BackendIDOperations.updateTextContentByID( this._rootNodeID, nextProps.text ); } } }); // Expose the constructor on itself and the prototype for consistency with other // descriptors. ReactTextComponent.type = ReactTextComponent; ReactTextComponent.prototype.type = ReactTextComponent; module.exports = ReactTextComponent; },{"./DOMPropertyOperations":9,"./ReactBrowserComponentMixin":25,"./ReactComponent":27,"./escapeTextForBrowser":98,"./mixInto":124}],71:[function(_dereq_,module,exports){ /** * Copyright 2013-2014 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. * * @providesModule ReactUpdates */ "use strict"; var ReactPerf = _dereq_("./ReactPerf"); var invariant = _dereq_("./invariant"); var dirtyComponents = []; var batchingStrategy = null; function ensureBatchingStrategy() { ("production" !== "development" ? invariant(batchingStrategy, 'ReactUpdates: must inject a batching strategy') : invariant(batchingStrategy)); } function batchedUpdates(callback, param) { ensureBatchingStrategy(); batchingStrategy.batchedUpdates(callback, param); } /** * Array comparator for ReactComponents by owner depth * * @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 mountDepthComparator(c1, c2) { return c1._mountDepth - c2._mountDepth; } function runBatchedUpdates() { // 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(mountDepthComparator); for (var i = 0; i < dirtyComponents.length; i++) { // If a component is unmounted before pending changes apply, ignore them // TODO: Queue unmounts in the same list to avoid this happening at all var component = dirtyComponents[i]; if (component.isMounted()) { // If performUpdateIfNecessary happens to enqueue any new updates, we // shouldn't execute the callbacks until the next render happens, so // stash the callbacks first var callbacks = component._pendingCallbacks; component._pendingCallbacks = null; component.performUpdateIfNecessary(); if (callbacks) { for (var j = 0; j < callbacks.length; j++) { callbacks[j].call(component); } } } } } function clearDirtyComponents() { dirtyComponents.length = 0; } var flushBatchedUpdates = ReactPerf.measure( 'ReactUpdates', 'flushBatchedUpdates', function() { // Run these in separate functions so the JIT can optimize try { runBatchedUpdates(); } finally { clearDirtyComponents(); } } ); /** * 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, callback) { ("production" !== "development" ? invariant( !callback || typeof callback === "function", 'enqueueUpdate(...): You called `setProps`, `replaceProps`, ' + '`setState`, `replaceState`, or `forceUpdate` with a callback that ' + 'isn\'t callable.' ) : invariant(!callback || typeof callback === "function")); ensureBatchingStrategy(); if (!batchingStrategy.isBatchingUpdates) { component.performUpdateIfNecessary(); callback && callback.call(component); return; } dirtyComponents.push(component); if (callback) { if (component._pendingCallbacks) { component._pendingCallbacks.push(callback); } else { component._pendingCallbacks = [callback]; } } } var ReactUpdatesInjection = { injectBatchingStrategy: function(_batchingStrategy) { ("production" !== "development" ? invariant( _batchingStrategy, 'ReactUpdates: must provide a batching strategy' ) : invariant(_batchingStrategy)); ("production" !== "development" ? invariant( typeof _batchingStrategy.batchedUpdates === 'function', 'ReactUpdates: must provide a batchedUpdates() function' ) : invariant(typeof _batchingStrategy.batchedUpdates === 'function')); ("production" !== "development" ? invariant( typeof _batchingStrategy.isBatchingUpdates === 'boolean', 'ReactUpdates: must provide an isBatchingUpdates boolean attribute' ) : invariant(typeof _batchingStrategy.isBatchingUpdates === 'boolean')); batchingStrategy = _batchingStrategy; } }; var ReactUpdates = { batchedUpdates: batchedUpdates, enqueueUpdate: enqueueUpdate, flushBatchedUpdates: flushBatchedUpdates, injection: ReactUpdatesInjection }; module.exports = ReactUpdates; },{"./ReactPerf":60,"./invariant":112}],72:[function(_dereq_,module,exports){ /** * Copyright 2013-2014 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. * * @providesModule SelectEventPlugin */ "use strict"; var EventConstants = _dereq_("./EventConstants"); var EventPropagators = _dereq_("./EventPropagators"); var ReactInputSelection = _dereq_("./ReactInputSelection"); var SyntheticEvent = _dereq_("./SyntheticEvent"); var getActiveElement = _dereq_("./getActiveElement"); var isTextInputElement = _dereq_("./isTextInputElement"); var keyOf = _dereq_("./keyOf"); var shallowEqual = _dereq_("./shallowEqual"); var topLevelTypes = EventConstants.topLevelTypes; var eventTypes = { select: { phasedRegistrationNames: { bubbled: keyOf({onSelect: null}), captured: keyOf({onSelectCapture: null}) }, dependencies: [ topLevelTypes.topBlur, topLevelTypes.topContextMenu, topLevelTypes.topFocus, topLevelTypes.topKeyDown, topLevelTypes.topMouseDown, topLevelTypes.topMouseUp, topLevelTypes.topSelectionChange ] } }; var activeElement = null; var activeElementID = null; var lastSelection = null; var mouseDown = false; /** * 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 * @param {object} */ function getSelection(node) { if ('selectionStart' in node && ReactInputSelection.hasSelectionCapabilities(node)) { return { start: node.selectionStart, end: node.selectionEnd }; } else if (document.selection) { var range = document.selection.createRange(); return { parentElement: range.parentElement(), text: range.text, top: range.boundingTop, left: range.boundingLeft }; } else { var selection = window.getSelection(); return { anchorNode: selection.anchorNode, anchorOffset: selection.anchorOffset, focusNode: selection.focusNode, focusOffset: selection.focusOffset }; } } /** * Poll selection to see whether it's changed. * * @param {object} nativeEvent * @return {?SyntheticEvent} */ function constructSelectEvent(nativeEvent) { // 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; } // Only fire when selection has actually changed. var currentSelection = getSelection(activeElement); if (!lastSelection || !shallowEqual(lastSelection, currentSelection)) { lastSelection = currentSelection; var syntheticEvent = SyntheticEvent.getPooled( eventTypes.select, activeElementID, nativeEvent ); syntheticEvent.type = 'select'; syntheticEvent.target = activeElement; EventPropagators.accumulateTwoPhaseDispatches(syntheticEvent); return syntheticEvent; } } /** * 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, /** * @param {string} topLevelType Record from `EventConstants`. * @param {DOMEventTarget} topLevelTarget The listening component root node. * @param {string} topLevelTargetID ID of `topLevelTarget`. * @param {object} nativeEvent Native browser event. * @return {*} An accumulation of synthetic events. * @see {EventPluginHub.extractEvents} */ extractEvents: function( topLevelType, topLevelTarget, topLevelTargetID, nativeEvent) { switch (topLevelType) { // Track the input node that has focus. case topLevelTypes.topFocus: if (isTextInputElement(topLevelTarget) || topLevelTarget.contentEditable === 'true') { activeElement = topLevelTarget; activeElementID = topLevelTargetID; lastSelection = null; } break; case topLevelTypes.topBlur: activeElement = null; activeElementID = null; lastSelection = null; break; // Don't fire the event while the user is dragging. This matches the // semantics of the native select event. case topLevelTypes.topMouseDown: mouseDown = true; break; case topLevelTypes.topContextMenu: case topLevelTypes.topMouseUp: mouseDown = false; return constructSelectEvent(nativeEvent); // Chrome and IE fire non-standard event when selection is changed (and // sometimes when it hasn't). // 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. case topLevelTypes.topSelectionChange: case topLevelTypes.topKeyDown: case topLevelTypes.topKeyUp: return constructSelectEvent(nativeEvent); } } }; module.exports = SelectEventPlugin; },{"./EventConstants":14,"./EventPropagators":19,"./ReactInputSelection":52,"./SyntheticEvent":78,"./getActiveElement":102,"./isTextInputElement":115,"./keyOf":119,"./shallowEqual":130}],73:[function(_dereq_,module,exports){ /** * Copyright 2013-2014 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. * * @providesModule ServerReactRootIndex * @typechecks */ "use strict"; /** * Size of the reactRoot ID space. We generate random numbers for React root * IDs and if there's a collision the events and DOM update system will * get confused. In the future we need a way to generate GUIDs but for * now this will work on a smaller scale. */ var GLOBAL_MOUNT_POINT_MAX = Math.pow(2, 53); var ServerReactRootIndex = { createReactRootIndex: function() { return Math.ceil(Math.random() * GLOBAL_MOUNT_POINT_MAX); } }; module.exports = ServerReactRootIndex; },{}],74:[function(_dereq_,module,exports){ /** * Copyright 2013-2014 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. * * @providesModule SimpleEventPlugin */ "use strict"; var EventConstants = _dereq_("./EventConstants"); var EventPluginUtils = _dereq_("./EventPluginUtils"); var EventPropagators = _dereq_("./EventPropagators"); var SyntheticClipboardEvent = _dereq_("./SyntheticClipboardEvent"); var SyntheticEvent = _dereq_("./SyntheticEvent"); var SyntheticFocusEvent = _dereq_("./SyntheticFocusEvent"); var SyntheticKeyboardEvent = _dereq_("./SyntheticKeyboardEvent"); var SyntheticMouseEvent = _dereq_("./SyntheticMouseEvent"); var SyntheticDragEvent = _dereq_("./SyntheticDragEvent"); var SyntheticTouchEvent = _dereq_("./SyntheticTouchEvent"); var SyntheticUIEvent = _dereq_("./SyntheticUIEvent"); var SyntheticWheelEvent = _dereq_("./SyntheticWheelEvent"); var invariant = _dereq_("./invariant"); var keyOf = _dereq_("./keyOf"); var topLevelTypes = EventConstants.topLevelTypes; var eventTypes = { blur: { phasedRegistrationNames: { bubbled: keyOf({onBlur: true}), captured: keyOf({onBlurCapture: true}) } }, click: { phasedRegistrationNames: { bubbled: keyOf({onClick: true}), captured: keyOf({onClickCapture: true}) } }, contextMenu: { phasedRegistrationNames: { bubbled: keyOf({onContextMenu: true}), captured: keyOf({onContextMenuCapture: true}) } }, copy: { phasedRegistrationNames: { bubbled: keyOf({onCopy: true}), captured: keyOf({onCopyCapture: true}) } }, cut: { phasedRegistrationNames: { bubbled: keyOf({onCut: true}), captured: keyOf({onCutCapture: true}) } }, doubleClick: { phasedRegistrationNames: { bubbled: keyOf({onDoubleClick: true}), captured: keyOf({onDoubleClickCapture: true}) } }, drag: { phasedRegistrationNames: { bubbled: keyOf({onDrag: true}), captured: keyOf({onDragCapture: true}) } }, dragEnd: { phasedRegistrationNames: { bubbled: keyOf({onDragEnd: true}), captured: keyOf({onDragEndCapture: true}) } }, dragEnter: { phasedRegistrationNames: { bubbled: keyOf({onDragEnter: true}), captured: keyOf({onDragEnterCapture: true}) } }, dragExit: { phasedRegistrationNames: { bubbled: keyOf({onDragExit: true}), captured: keyOf({onDragExitCapture: true}) } }, dragLeave: { phasedRegistrationNames: { bubbled: keyOf({onDragLeave: true}), captured: keyOf({onDragLeaveCapture: true}) } }, dragOver: { phasedRegistrationNames: { bubbled: keyOf({onDragOver: true}), captured: keyOf({onDragOverCapture: true}) } }, dragStart: { phasedRegistrationNames: { bubbled: keyOf({onDragStart: true}), captured: keyOf({onDragStartCapture: true}) } }, drop: { phasedRegistrationNames: { bubbled: keyOf({onDrop: true}), captured: keyOf({onDropCapture: true}) } }, focus: { phasedRegistrationNames: { bubbled: keyOf({onFocus: true}), captured: keyOf({onFocusCapture: true}) } }, input: { phasedRegistrationNames: { bubbled: keyOf({onInput: true}), captured: keyOf({onInputCapture: true}) } }, keyDown: { phasedRegistrationNames: { bubbled: keyOf({onKeyDown: true}), captured: keyOf({onKeyDownCapture: true}) } }, keyPress: { phasedRegistrationNames: { bubbled: keyOf({onKeyPress: true}), captured: keyOf({onKeyPressCapture: true}) } }, keyUp: { phasedRegistrationNames: { bubbled: keyOf({onKeyUp: true}), captured: keyOf({onKeyUpCapture: true}) } }, load: { phasedRegistrationNames: { bubbled: keyOf({onLoad: true}), captured: keyOf({onLoadCapture: true}) } }, error: { phasedRegistrationNames: { bubbled: keyOf({onError: true}), captured: keyOf({onErrorCapture: true}) } }, // Note: We do not allow listening to mouseOver events. Instead, use the // onMouseEnter/onMouseLeave created by `EnterLeaveEventPlugin`. mouseDown: { phasedRegistrationNames: { bubbled: keyOf({onMouseDown: true}), captured: keyOf({onMouseDownCapture: true}) } }, mouseMove: { phasedRegistrationNames: { bubbled: keyOf({onMouseMove: true}), captured: keyOf({onMouseMoveCapture: true}) } }, mouseOut: { phasedRegistrationNames: { bubbled: keyOf({onMouseOut: true}), captured: keyOf({onMouseOutCapture: true}) } }, mouseOver: { phasedRegistrationNames: { bubbled: keyOf({onMouseOver: true}), captured: keyOf({onMouseOverCapture: true}) } }, mouseUp: { phasedRegistrationNames: { bubbled: keyOf({onMouseUp: true}), captured: keyOf({onMouseUpCapture: true}) } }, paste: { phasedRegistrationNames: { bubbled: keyOf({onPaste: true}), captured: keyOf({onPasteCapture: true}) } }, reset: { phasedRegistrationNames: { bubbled: keyOf({onReset: true}), captured: keyOf({onResetCapture: true}) } }, scroll: { phasedRegistrationNames: { bubbled: keyOf({onScroll: true}), captured: keyOf({onScrollCapture: true}) } }, submit: { phasedRegistrationNames: { bubbled: keyOf({onSubmit: true}), captured: keyOf({onSubmitCapture: true}) } }, touchCancel: { phasedRegistrationNames: { bubbled: keyOf({onTouchCancel: true}), captured: keyOf({onTouchCancelCapture: true}) } }, touchEnd: { phasedRegistrationNames: { bubbled: keyOf({onTouchEnd: true}), captured: keyOf({onTouchEndCapture: true}) } }, touchMove: { phasedRegistrationNames: { bubbled: keyOf({onTouchMove: true}), captured: keyOf({onTouchMoveCapture: true}) } }, touchStart: { phasedRegistrationNames: { bubbled: keyOf({onTouchStart: true}), captured: keyOf({onTouchStartCapture: true}) } }, wheel: { phasedRegistrationNames: { bubbled: keyOf({onWheel: true}), captured: keyOf({onWheelCapture: true}) } } }; var topLevelEventsToDispatchConfig = { topBlur: eventTypes.blur, topClick: eventTypes.click, topContextMenu: eventTypes.contextMenu, topCopy: eventTypes.copy, topCut: eventTypes.cut, topDoubleClick: eventTypes.doubleClick, topDrag: eventTypes.drag, topDragEnd: eventTypes.dragEnd, topDragEnter: eventTypes.dragEnter, topDragExit: eventTypes.dragExit, topDragLeave: eventTypes.dragLeave, topDragOver: eventTypes.dragOver, topDragStart: eventTypes.dragStart, topDrop: eventTypes.drop, topError: eventTypes.error, topFocus: eventTypes.focus, topInput: eventTypes.input, topKeyDown: eventTypes.keyDown, topKeyPress: eventTypes.keyPress, topKeyUp: eventTypes.keyUp, topLoad: eventTypes.load, topMouseDown: eventTypes.mouseDown, topMouseMove: eventTypes.mouseMove, topMouseOut: eventTypes.mouseOut, topMouseOver: eventTypes.mouseOver, topMouseUp: eventTypes.mouseUp, topPaste: eventTypes.paste, topReset: eventTypes.reset, topScroll: eventTypes.scroll, topSubmit: eventTypes.submit, topTouchCancel: eventTypes.touchCancel, topTouchEnd: eventTypes.touchEnd, topTouchMove: eventTypes.touchMove, topTouchStart: eventTypes.touchStart, topWheel: eventTypes.wheel }; for (var topLevelType in topLevelEventsToDispatchConfig) { topLevelEventsToDispatchConfig[topLevelType].dependencies = [topLevelType]; } var SimpleEventPlugin = { eventTypes: eventTypes, /** * Same as the default implementation, except cancels the event when return * value is false. * * @param {object} Event to be dispatched. * @param {function} Application-level callback. * @param {string} domID DOM ID to pass to the callback. */ executeDispatch: function(event, listener, domID) { var returnValue = EventPluginUtils.executeDispatch(event, listener, domID); if (returnValue === false) { event.stopPropagation(); event.preventDefault(); } }, /** * @param {string} topLevelType Record from `EventConstants`. * @param {DOMEventTarget} topLevelTarget The listening component root node. * @param {string} topLevelTargetID ID of `topLevelTarget`. * @param {object} nativeEvent Native browser event. * @return {*} An accumulation of synthetic events. * @see {EventPluginHub.extractEvents} */ extractEvents: function( topLevelType, topLevelTarget, topLevelTargetID, nativeEvent) { var dispatchConfig = topLevelEventsToDispatchConfig[topLevelType]; if (!dispatchConfig) { return null; } var EventConstructor; switch (topLevelType) { case topLevelTypes.topInput: case topLevelTypes.topLoad: case topLevelTypes.topError: case topLevelTypes.topReset: case topLevelTypes.topSubmit: // HTML Events // @see http://www.w3.org/TR/html5/index.html#events-0 EventConstructor = SyntheticEvent; break; case topLevelTypes.topKeyDown: case topLevelTypes.topKeyPress: case topLevelTypes.topKeyUp: EventConstructor = SyntheticKeyboardEvent; break; case topLevelTypes.topBlur: case topLevelTypes.topFocus: EventConstructor = SyntheticFocusEvent; break; case topLevelTypes.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 topLevelTypes.topContextMenu: case topLevelTypes.topDoubleClick: case topLevelTypes.topMouseDown: case topLevelTypes.topMouseMove: case topLevelTypes.topMouseOut: case topLevelTypes.topMouseOver: case topLevelTypes.topMouseUp: EventConstructor = SyntheticMouseEvent; break; case topLevelTypes.topDrag: case topLevelTypes.topDragEnd: case topLevelTypes.topDragEnter: case topLevelTypes.topDragExit: case topLevelTypes.topDragLeave: case topLevelTypes.topDragOver: case topLevelTypes.topDragStart: case topLevelTypes.topDrop: EventConstructor = SyntheticDragEvent; break; case topLevelTypes.topTouchCancel: case topLevelTypes.topTouchEnd: case topLevelTypes.topTouchMove: case topLevelTypes.topTouchStart: EventConstructor = SyntheticTouchEvent; break; case topLevelTypes.topScroll: EventConstructor = SyntheticUIEvent; break; case topLevelTypes.topWheel: EventConstructor = SyntheticWheelEvent; break; case topLevelTypes.topCopy: case topLevelTypes.topCut: case topLevelTypes.topPaste: EventConstructor = SyntheticClipboardEvent; break; } ("production" !== "development" ? invariant( EventConstructor, 'SimpleEventPlugin: Unhandled event type, `%s`.', topLevelType ) : invariant(EventConstructor)); var event = EventConstructor.getPooled( dispatchConfig, topLevelTargetID, nativeEvent ); EventPropagators.accumulateTwoPhaseDispatches(event); return event; } }; module.exports = SimpleEventPlugin; },{"./EventConstants":14,"./EventPluginUtils":18,"./EventPropagators":19,"./SyntheticClipboardEvent":75,"./SyntheticDragEvent":77,"./SyntheticEvent":78,"./SyntheticFocusEvent":79,"./SyntheticKeyboardEvent":80,"./SyntheticMouseEvent":81,"./SyntheticTouchEvent":82,"./SyntheticUIEvent":83,"./SyntheticWheelEvent":84,"./invariant":112,"./keyOf":119}],75:[function(_dereq_,module,exports){ /** * Copyright 2013-2014 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. * * @providesModule SyntheticClipboardEvent * @typechecks static-only */ "use strict"; var SyntheticEvent = _dereq_("./SyntheticEvent"); /** * @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) { SyntheticEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent); } SyntheticEvent.augmentClass(SyntheticClipboardEvent, ClipboardEventInterface); module.exports = SyntheticClipboardEvent; },{"./SyntheticEvent":78}],76:[function(_dereq_,module,exports){ /** * Copyright 2013-2014 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. * * @providesModule SyntheticCompositionEvent * @typechecks static-only */ "use strict"; var SyntheticEvent = _dereq_("./SyntheticEvent"); /** * @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) { SyntheticEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent); } SyntheticEvent.augmentClass( SyntheticCompositionEvent, CompositionEventInterface ); module.exports = SyntheticCompositionEvent; },{"./SyntheticEvent":78}],77:[function(_dereq_,module,exports){ /** * Copyright 2013-2014 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. * * @providesModule SyntheticDragEvent * @typechecks static-only */ "use strict"; var SyntheticMouseEvent = _dereq_("./SyntheticMouseEvent"); /** * @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) { SyntheticMouseEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent); } SyntheticMouseEvent.augmentClass(SyntheticDragEvent, DragEventInterface); module.exports = SyntheticDragEvent; },{"./SyntheticMouseEvent":81}],78:[function(_dereq_,module,exports){ /** * Copyright 2013-2014 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. * * @providesModule SyntheticEvent * @typechecks static-only */ "use strict"; var PooledClass = _dereq_("./PooledClass"); var emptyFunction = _dereq_("./emptyFunction"); var getEventTarget = _dereq_("./getEventTarget"); var merge = _dereq_("./merge"); var mergeInto = _dereq_("./mergeInto"); /** * @interface Event * @see http://www.w3.org/TR/DOM-Level-3-Events/ */ var EventInterface = { type: null, target: getEventTarget, // 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 {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native browser event. */ function SyntheticEvent(dispatchConfig, dispatchMarker, nativeEvent) { this.dispatchConfig = dispatchConfig; this.dispatchMarker = dispatchMarker; this.nativeEvent = nativeEvent; var Interface = this.constructor.Interface; for (var propName in Interface) { if (!Interface.hasOwnProperty(propName)) { continue; } var normalize = Interface[propName]; if (normalize) { this[propName] = normalize(nativeEvent); } 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; } mergeInto(SyntheticEvent.prototype, { preventDefault: function() { this.defaultPrevented = true; var event = this.nativeEvent; event.preventDefault ? event.preventDefault() : event.returnValue = false; this.isDefaultPrevented = emptyFunction.thatReturnsTrue; }, stopPropagation: function() { var event = this.nativeEvent; event.stopPropagation ? event.stopPropagation() : 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) { this[propName] = null; } this.dispatchConfig = null; this.dispatchMarker = null; this.nativeEvent = null; } }); SyntheticEvent.Interface = EventInterface; /** * Helper to reduce boilerplate when creating subclasses. * * @param {function} Class * @param {?object} Interface */ SyntheticEvent.augmentClass = function(Class, Interface) { var Super = this; var prototype = Object.create(Super.prototype); mergeInto(prototype, Class.prototype); Class.prototype = prototype; Class.prototype.constructor = Class; Class.Interface = merge(Super.Interface, Interface); Class.augmentClass = Super.augmentClass; PooledClass.addPoolingTo(Class, PooledClass.threeArgumentPooler); }; PooledClass.addPoolingTo(SyntheticEvent, PooledClass.threeArgumentPooler); module.exports = SyntheticEvent; },{"./PooledClass":23,"./emptyFunction":96,"./getEventTarget":104,"./merge":121,"./mergeInto":123}],79:[function(_dereq_,module,exports){ /** * Copyright 2013-2014 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. * * @providesModule SyntheticFocusEvent * @typechecks static-only */ "use strict"; var SyntheticUIEvent = _dereq_("./SyntheticUIEvent"); /** * @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) { SyntheticUIEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent); } SyntheticUIEvent.augmentClass(SyntheticFocusEvent, FocusEventInterface); module.exports = SyntheticFocusEvent; },{"./SyntheticUIEvent":83}],80:[function(_dereq_,module,exports){ /** * Copyright 2013-2014 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. * * @providesModule SyntheticKeyboardEvent * @typechecks static-only */ "use strict"; var SyntheticUIEvent = _dereq_("./SyntheticUIEvent"); var getEventKey = _dereq_("./getEventKey"); /** * @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, // Legacy Interface 'char': null, charCode: null, keyCode: null, which: 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 SyntheticKeyboardEvent(dispatchConfig, dispatchMarker, nativeEvent) { SyntheticUIEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent); } SyntheticUIEvent.augmentClass(SyntheticKeyboardEvent, KeyboardEventInterface); module.exports = SyntheticKeyboardEvent; },{"./SyntheticUIEvent":83,"./getEventKey":103}],81:[function(_dereq_,module,exports){ /** * Copyright 2013-2014 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. * * @providesModule SyntheticMouseEvent * @typechecks static-only */ "use strict"; var SyntheticUIEvent = _dereq_("./SyntheticUIEvent"); var ViewportMetrics = _dereq_("./ViewportMetrics"); /** * @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, 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) { SyntheticUIEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent); } SyntheticUIEvent.augmentClass(SyntheticMouseEvent, MouseEventInterface); module.exports = SyntheticMouseEvent; },{"./SyntheticUIEvent":83,"./ViewportMetrics":86}],82:[function(_dereq_,module,exports){ /** * Copyright 2013-2014 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. * * @providesModule SyntheticTouchEvent * @typechecks static-only */ "use strict"; var SyntheticUIEvent = _dereq_("./SyntheticUIEvent"); /** * @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 }; /** * @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) { SyntheticUIEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent); } SyntheticUIEvent.augmentClass(SyntheticTouchEvent, TouchEventInterface); module.exports = SyntheticTouchEvent; },{"./SyntheticUIEvent":83}],83:[function(_dereq_,module,exports){ /** * Copyright 2013-2014 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. * * @providesModule SyntheticUIEvent * @typechecks static-only */ "use strict"; var SyntheticEvent = _dereq_("./SyntheticEvent"); /** * @interface UIEvent * @see http://www.w3.org/TR/DOM-Level-3-Events/ */ var UIEventInterface = { view: null, detail: 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 SyntheticUIEvent(dispatchConfig, dispatchMarker, nativeEvent) { SyntheticEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent); } SyntheticEvent.augmentClass(SyntheticUIEvent, UIEventInterface); module.exports = SyntheticUIEvent; },{"./SyntheticEvent":78}],84:[function(_dereq_,module,exports){ /** * Copyright 2013-2014 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. * * @providesModule SyntheticWheelEvent * @typechecks static-only */ "use strict"; var SyntheticMouseEvent = _dereq_("./SyntheticMouseEvent"); /** * @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) { SyntheticMouseEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent); } SyntheticMouseEvent.augmentClass(SyntheticWheelEvent, WheelEventInterface); module.exports = SyntheticWheelEvent; },{"./SyntheticMouseEvent":81}],85:[function(_dereq_,module,exports){ /** * Copyright 2013-2014 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. * * @providesModule Transaction */ "use strict"; var invariant = _dereq_("./invariant"); /** * `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> * * Bonus: * - Reports timing metrics by method name and wrapper index. * * 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 upates. * * 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 Mixin = { /** * 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 = []; } else { this.wrapperInitData.length = 0; } if (!this.timingMetrics) { this.timingMetrics = {}; } this.timingMetrics.methodInvocationTime = 0; if (!this.timingMetrics.wrapperInitTimes) { this.timingMetrics.wrapperInitTimes = []; } else { this.timingMetrics.wrapperInitTimes.length = 0; } if (!this.timingMetrics.wrapperCloseTimes) { this.timingMetrics.wrapperCloseTimes = []; } else { this.timingMetrics.wrapperCloseTimes.length = 0; } 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. * * @param {function} method Member of scope to call. * @param {Object} scope Scope to invoke from. * @param {Object?=} args... Arguments to pass to the method (optional). * Helps prevent need to bind in many cases. * @return Return value from `method`. */ perform: function(method, scope, a, b, c, d, e, f) { ("production" !== "development" ? invariant( !this.isInTransaction(), 'Transaction.perform(...): Cannot initialize a transaction when there ' + 'is already an outstanding transaction.' ) : invariant(!this.isInTransaction())); var memberStart = Date.now(); 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 { var memberEnd = Date.now(); this.methodInvocationTime += (memberEnd - memberStart); 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; var wrapperInitTimes = this.timingMetrics.wrapperInitTimes; for (var i = startIndex; i < transactionWrappers.length; i++) { var initStart = Date.now(); 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] = Transaction.OBSERVED_ERROR; this.wrapperInitData[i] = wrapper.initialize ? wrapper.initialize.call(this) : null; } finally { var curInitTime = wrapperInitTimes[i]; var initEnd = Date.now(); wrapperInitTimes[i] = (curInitTime || 0) + (initEnd - initStart); if (this.wrapperInitData[i] === Transaction.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) { ("production" !== "development" ? invariant( this.isInTransaction(), 'Transaction.closeAll(): Cannot close transaction when none are open.' ) : invariant(this.isInTransaction())); var transactionWrappers = this.transactionWrappers; var wrapperCloseTimes = this.timingMetrics.wrapperCloseTimes; for (var i = startIndex; i < transactionWrappers.length; i++) { var wrapper = transactionWrappers[i]; var closeStart = Date.now(); 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 !== Transaction.OBSERVED_ERROR) { wrapper.close && wrapper.close.call(this, initData); } errorThrown = false; } finally { var closeEnd = Date.now(); var curCloseTime = wrapperCloseTimes[i]; wrapperCloseTimes[i] = (curCloseTime || 0) + (closeEnd - closeStart); 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; } }; var Transaction = { Mixin: Mixin, /** * Token to look for to determine if an error occured. */ OBSERVED_ERROR: {} }; module.exports = Transaction; },{"./invariant":112}],86:[function(_dereq_,module,exports){ /** * Copyright 2013-2014 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. * * @providesModule ViewportMetrics */ "use strict"; var getUnboundedScrollPosition = _dereq_("./getUnboundedScrollPosition"); var ViewportMetrics = { currentScrollLeft: 0, currentScrollTop: 0, refreshScrollValues: function() { var scrollPosition = getUnboundedScrollPosition(window); ViewportMetrics.currentScrollLeft = scrollPosition.x; ViewportMetrics.currentScrollTop = scrollPosition.y; } }; module.exports = ViewportMetrics; },{"./getUnboundedScrollPosition":109}],87:[function(_dereq_,module,exports){ /** * Copyright 2013-2014 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. * * @providesModule accumulate */ "use strict"; var invariant = _dereq_("./invariant"); /** * Accumulates items that must not be null or undefined. * * This is used to conserve memory by avoiding array allocations. * * @return {*|array<*>} An accumulation of items. */ function accumulate(current, next) { ("production" !== "development" ? invariant( next != null, 'accumulate(...): Accumulated items must be not be null or undefined.' ) : invariant(next != null)); if (current == null) { return next; } else { // 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). var currentIsArray = Array.isArray(current); var nextIsArray = Array.isArray(next); if (currentIsArray) { return current.concat(next); } else { if (nextIsArray) { return [current].concat(next); } else { return [current, next]; } } } } module.exports = accumulate; },{"./invariant":112}],88:[function(_dereq_,module,exports){ /** * Copyright 2013-2014 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. * * @providesModule adler32 */ /* jslint bitwise:true */ "use strict"; var MOD = 65521; // This is a clean-room implementation of adler32 designed for detecting // if markup is not what we expect it to be. It does not need to be // cryptographically strong, only reasonable good at detecting if markup // generated on the server is different than that on the client. function adler32(data) { var a = 1; var b = 0; for (var i = 0; i < data.length; i++) { a = (a + data.charCodeAt(i)) % MOD; b = (b + a) % MOD; } return a | (b << 16); } module.exports = adler32; },{}],89:[function(_dereq_,module,exports){ /** * Copyright 2013-2014 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. * * @providesModule containsNode * @typechecks */ var isTextNode = _dereq_("./isTextNode"); /*jslint bitwise:true */ /** * Checks if a given DOM node contains or is another DOM node. * * @param {?DOMNode} outerNode Outer DOM node. * @param {?DOMNode} innerNode Inner DOM node. * @return {boolean} True if `outerNode` contains or is `innerNode`. */ 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 (outerNode.contains) { return outerNode.contains(innerNode); } else if (outerNode.compareDocumentPosition) { return !!(outerNode.compareDocumentPosition(innerNode) & 16); } else { return false; } } module.exports = containsNode; },{"./isTextNode":116}],90:[function(_dereq_,module,exports){ /** * Copyright 2013-2014 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. * * @providesModule copyProperties */ /** * Copy properties from one or more objects (up to 5) into the first object. * This is a shallow copy. It mutates the first object and also returns it. * * NOTE: `arguments` has a very significant performance penalty, which is why * we don't support unlimited arguments. */ function copyProperties(obj, a, b, c, d, e, f) { obj = obj || {}; if ("production" !== "development") { if (f) { throw new Error('Too many arguments passed to copyProperties'); } } var args = [a, b, c, d, e]; var ii = 0, v; while (args[ii]) { v = args[ii++]; for (var k in v) { obj[k] = v[k]; } // IE ignores toString in object iteration.. See: // webreflection.blogspot.com/2007/07/quick-fix-internet-explorer-and.html if (v.hasOwnProperty && v.hasOwnProperty('toString') && (typeof v.toString != 'undefined') && (obj.toString !== v.toString)) { obj.toString = v.toString; } } return obj; } module.exports = copyProperties; },{}],91:[function(_dereq_,module,exports){ /** * Copyright 2013-2014 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. * * @providesModule createArrayFrom * @typechecks */ var toArray = _dereq_("./toArray"); /** * 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 (// HTMLCollection/NodeList (Array.isArray(obj) || // arguments ('callee' in obj) || '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 createArrayFrom = require('createArrayFrom'); * * function takesOneOrMoreThings(things) { * things = createArrayFrom(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 createArrayFrom(obj) { if (!hasArrayNature(obj)) { return [obj]; } else if (Array.isArray(obj)) { return obj.slice(); } else { return toArray(obj); } } module.exports = createArrayFrom; },{"./toArray":132}],92:[function(_dereq_,module,exports){ /** * Copyright 2013-2014 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. * * @providesModule createFullPageComponent * @typechecks */ "use strict"; // Defeat circular references by requiring this directly. var ReactCompositeComponent = _dereq_("./ReactCompositeComponent"); var invariant = _dereq_("./invariant"); /** * Create a component that will throw an exception when unmounted. * * 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. * * @param {function} componentClass convenience constructor to wrap * @return {function} convenience constructor of new component */ function createFullPageComponent(componentClass) { var FullPageComponent = ReactCompositeComponent.createClass({ displayName: 'ReactFullPageComponent' + ( componentClass.componentConstructor.displayName || '' ), componentWillUnmount: function() { ("production" !== "development" ? 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.constructor.displayName ) : invariant(false)); }, render: function() { return this.transferPropsTo(componentClass(null, this.props.children)); } }); return FullPageComponent; } module.exports = createFullPageComponent; },{"./ReactCompositeComponent":29,"./invariant":112}],93:[function(_dereq_,module,exports){ /** * Copyright 2013-2014 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. * * @providesModule createNodesFromMarkup * @typechecks */ /*jslint evil: true, sub: true */ var ExecutionEnvironment = _dereq_("./ExecutionEnvironment"); var createArrayFrom = _dereq_("./createArrayFrom"); var getMarkupWrap = _dereq_("./getMarkupWrap"); var invariant = _dereq_("./invariant"); /** * 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; ("production" !== "development" ? invariant(!!dummyNode, 'createNodesFromMarkup dummy not initialized') : invariant(!!dummyNode)); 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) { ("production" !== "development" ? invariant( handleScript, 'createNodesFromMarkup(...): Unexpected <script> element rendered.' ) : invariant(handleScript)); createArrayFrom(scripts).forEach(handleScript); } var nodes = createArrayFrom(node.childNodes); while (node.lastChild) { node.removeChild(node.lastChild); } return nodes; } module.exports = createNodesFromMarkup; },{"./ExecutionEnvironment":20,"./createArrayFrom":91,"./getMarkupWrap":105,"./invariant":112}],94:[function(_dereq_,module,exports){ /** * Copyright 2013-2014 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. * * @providesModule createObjectFrom */ /** * Construct an object from an array of keys * and optionally specified value or list of values. * * >>> createObjectFrom(['a','b','c']); * {a: true, b: true, c: true} * * >>> createObjectFrom(['a','b','c'], false); * {a: false, b: false, c: false} * * >>> createObjectFrom(['a','b','c'], 'monkey'); * {c:'monkey', b:'monkey' c:'monkey'} * * >>> createObjectFrom(['a','b','c'], [1,2,3]); * {a: 1, b: 2, c: 3} * * >>> createObjectFrom(['women', 'men'], [true, false]); * {women: true, men: false} * * @param Array list of keys * @param mixed optional value or value array. defaults true. * @returns object */ function createObjectFrom(keys, values /* = true */) { if ("production" !== "development") { if (!Array.isArray(keys)) { throw new TypeError('Must pass an array of keys.'); } } var object = {}; var isArray = Array.isArray(values); if (typeof values == 'undefined') { values = true; } for (var ii = keys.length; ii--;) { object[keys[ii]] = isArray ? values[ii] : values; } return object; } module.exports = createObjectFrom; },{}],95:[function(_dereq_,module,exports){ /** * Copyright 2013-2014 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. * * @providesModule dangerousStyleValue * @typechecks static-only */ "use strict"; var CSSProperty = _dereq_("./CSSProperty"); /** * Convert a value into the proper css writable value. The `styleName` name * name should be logical (no hyphens), as specified * in `CSSProperty.isUnitlessNumber`. * * @param {string} styleName CSS property name such as `topMargin`. * @param {*} value CSS property value such as `10px`. * @return {string} Normalized style value with dimensions applied. */ function dangerousStyleValue(styleName, value) { // 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 ''; } var isNonNumeric = isNaN(value); if (isNonNumeric || value === 0 || CSSProperty.isUnitlessNumber[styleName]) { return '' + value; // cast to string } return value + 'px'; } module.exports = dangerousStyleValue; },{"./CSSProperty":2}],96:[function(_dereq_,module,exports){ /** * Copyright 2013-2014 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. * * @providesModule emptyFunction */ var copyProperties = _dereq_("./copyProperties"); 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() {} copyProperties(emptyFunction, { thatReturns: makeEmptyFunction, thatReturnsFalse: makeEmptyFunction(false), thatReturnsTrue: makeEmptyFunction(true), thatReturnsNull: makeEmptyFunction(null), thatReturnsThis: function() { return this; }, thatReturnsArgument: function(arg) { return arg; } }); module.exports = emptyFunction; },{"./copyProperties":90}],97:[function(_dereq_,module,exports){ /** * Copyright 2013-2014 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. * * @providesModule emptyObject */ "use strict"; var emptyObject = {}; if ("production" !== "development") { Object.freeze(emptyObject); } module.exports = emptyObject; },{}],98:[function(_dereq_,module,exports){ /** * Copyright 2013-2014 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. * * @providesModule escapeTextForBrowser * @typechecks static-only */ "use strict"; var ESCAPE_LOOKUP = { "&": "&amp;", ">": "&gt;", "<": "&lt;", "\"": "&quot;", "'": "&#x27;", "/": "&#x2f;" }; var ESCAPE_REGEX = /[&><"'\/]/g; function escaper(match) { return ESCAPE_LOOKUP[match]; } /** * Escapes text to prevent scripting attacks. * * @param {*} text Text value to escape. * @return {string} An escaped string. */ function escapeTextForBrowser(text) { return ('' + text).replace(ESCAPE_REGEX, escaper); } module.exports = escapeTextForBrowser; },{}],99:[function(_dereq_,module,exports){ /** * Copyright 2013-2014 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. * * @providesModule flattenChildren */ "use strict"; var invariant = _dereq_("./invariant"); var traverseAllChildren = _dereq_("./traverseAllChildren"); /** * @param {function} traverseContext Context passed through traversal. * @param {?ReactComponent} child React child component. * @param {!string} name String name of key path to child. */ function flattenSingleChildIntoContext(traverseContext, child, name) { // We found a component instance. var result = traverseContext; ("production" !== "development" ? invariant( !result.hasOwnProperty(name), 'flattenChildren(...): Encountered two children with the same key, `%s`. ' + 'Children keys must be unique.', name ) : invariant(!result.hasOwnProperty(name))); if (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) { if (children == null) { return children; } var result = {}; traverseAllChildren(children, flattenSingleChildIntoContext, result); return result; } module.exports = flattenChildren; },{"./invariant":112,"./traverseAllChildren":133}],100:[function(_dereq_,module,exports){ /** * Copyright 2014 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. * * @providesModule focusNode */ "use strict"; /** * IE8 throws if an input/textarea is disabled and we try to focus it. * Focus only when necessary. * * @param {DOMElement} node input/textarea to focus */ function focusNode(node) { if (!node.disabled) { node.focus(); } } module.exports = focusNode; },{}],101:[function(_dereq_,module,exports){ /** * Copyright 2013-2014 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. * * @providesModule forEachAccumulated */ "use strict"; /** * @param {array} 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). */ var forEachAccumulated = function(arr, cb, scope) { if (Array.isArray(arr)) { arr.forEach(cb, scope); } else if (arr) { cb.call(scope, arr); } }; module.exports = forEachAccumulated; },{}],102:[function(_dereq_,module,exports){ /** * Copyright 2013-2014 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. * * @providesModule getActiveElement * @typechecks */ /** * 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 body is not yet defined. */ function getActiveElement() /*?DOMElement*/ { try { return document.activeElement || document.body; } catch (e) { return document.body; } } module.exports = getActiveElement; },{}],103:[function(_dereq_,module,exports){ /** * Copyright 2013-2014 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. * * @providesModule getEventKey * @typechecks static-only */ "use strict"; /** * 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 "which/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) { return 'key' in nativeEvent ? normalizeKey[nativeEvent.key] || nativeEvent.key : translateToKey[nativeEvent.which || nativeEvent.keyCode] || 'Unidentified'; } module.exports = getEventKey; },{}],104:[function(_dereq_,module,exports){ /** * Copyright 2013-2014 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. * * @providesModule getEventTarget * @typechecks static-only */ "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; // 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; },{}],105:[function(_dereq_,module,exports){ /** * Copyright 2013-2014 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. * * @providesModule getMarkupWrap */ var ExecutionEnvironment = _dereq_("./ExecutionEnvironment"); var invariant = _dereq_("./invariant"); /** * 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 = { // Force wrapping for SVG elements because if they get created inside a <div>, // they will be initialized in the wrong namespace (and will not display). 'circle': true, 'defs': true, 'g': true, 'line': true, 'linearGradient': true, 'path': true, 'polygon': true, 'polyline': true, 'radialGradient': true, 'rect': true, 'stop': true, 'text': true }; 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>', '</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, 'circle': svgWrap, 'defs': svgWrap, 'g': svgWrap, 'line': svgWrap, 'linearGradient': svgWrap, 'path': svgWrap, 'polygon': svgWrap, 'polyline': svgWrap, 'radialGradient': svgWrap, 'rect': svgWrap, 'stop': svgWrap, 'text': svgWrap }; /** * 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) { ("production" !== "development" ? invariant(!!dummyNode, 'Markup wrapping node not initialized') : invariant(!!dummyNode)); 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; },{"./ExecutionEnvironment":20,"./invariant":112}],106:[function(_dereq_,module,exports){ /** * Copyright 2013-2014 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. * * @providesModule getNodeForCharacterOffset */ "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; },{}],107:[function(_dereq_,module,exports){ /** * Copyright 2013-2014 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. * * @providesModule getReactRootElementInContainer */ "use strict"; var DOC_NODE_TYPE = 9; /** * @param {DOMElement|DOMDocument} container DOM element that may contain * a React component * @return {?*} DOM element that may have the reactRoot ID, or null. */ function getReactRootElementInContainer(container) { if (!container) { return null; } if (container.nodeType === DOC_NODE_TYPE) { return container.documentElement; } else { return container.firstChild; } } module.exports = getReactRootElementInContainer; },{}],108:[function(_dereq_,module,exports){ /** * Copyright 2013-2014 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. * * @providesModule getTextContentAccessor */ "use strict"; var ExecutionEnvironment = _dereq_("./ExecutionEnvironment"); 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.createElement('div') ? 'textContent' : 'innerText'; } return contentKey; } module.exports = getTextContentAccessor; },{"./ExecutionEnvironment":20}],109:[function(_dereq_,module,exports){ /** * Copyright 2013-2014 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. * * @providesModule getUnboundedScrollPosition * @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; },{}],110:[function(_dereq_,module,exports){ /** * Copyright 2013-2014 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. * * @providesModule hyphenate * @typechecks */ var _uppercasePattern = /([A-Z])/g; /** * Hyphenates a camelcased string, for example: * * > hyphenate('backgroundColor') * < "background-color" * * @param {string} string * @return {string} */ function hyphenate(string) { return string.replace(_uppercasePattern, '-$1').toLowerCase(); } module.exports = hyphenate; },{}],111:[function(_dereq_,module,exports){ /** * Copyright 2013-2014 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. * * @providesModule instantiateReactComponent * @typechecks static-only */ "use strict"; var warning = _dereq_("./warning"); /** * Validate a `componentDescriptor`. This should be exposed publicly in a follow * up diff. * * @param {object} descriptor * @return {boolean} Returns true if this is a valid descriptor of a Component. */ function isValidComponentDescriptor(descriptor) { return ( typeof descriptor.constructor === 'function' && typeof descriptor.constructor.prototype.construct === 'function' && typeof descriptor.constructor.prototype.mountComponent === 'function' && typeof descriptor.constructor.prototype.receiveComponent === 'function' ); } /** * Given a `componentDescriptor` create an instance that will actually be * mounted. Currently it just extracts an existing clone from composite * components but this is an implementation detail which will change. * * @param {object} descriptor * @return {object} A new instance of componentDescriptor's constructor. * @protected */ function instantiateReactComponent(descriptor) { if ("production" !== "development") { ("production" !== "development" ? warning( isValidComponentDescriptor(descriptor), 'Only React Components are valid for mounting.' ) : null); // We use the clone of a composite component instead of the original // instance. This allows us to warn you if you're are accessing the wrong // instance. var instance = descriptor.__realComponentInstance || descriptor; instance._descriptor = descriptor; return instance; } // In prod we don't clone, we simply use the same instance for unaffected // behavior. We have to keep the descriptor around for comparison later on. // This should ideally be accepted in the constructor of the instance but // since that is currently overloaded, we just manually attach it here. descriptor._descriptor = descriptor; return descriptor; } module.exports = instantiateReactComponent; },{"./warning":134}],112:[function(_dereq_,module,exports){ /** * Copyright 2013-2014 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. * * @providesModule invariant */ "use strict"; /** * Use invariant() to assert state which your program assumes to be true. * * Provide sprintf-style format (only %s is supported) and arguments * to provide information about what broke and what you were * expecting. * * The invariant message will be stripped in production, but the invariant * will remain to ensure logic does not differ in production. */ var invariant = function(condition) { if (!condition) { var error = new Error( 'Minified exception occured; use the non-minified dev environment for ' + 'the full error message and additional helpful warnings.' ); error.framesToPop = 1; throw error; } }; if ("production" !== "development") { invariant = function(condition, format, a, b, c, d, e, f) { if (format === undefined) { throw new Error('invariant requires an error message argument'); } if (!condition) { var args = [a, b, c, d, e, f]; var argIndex = 0; var error = new Error( 'Invariant Violation: ' + format.replace(/%s/g, function() { return args[argIndex++]; }) ); error.framesToPop = 1; // we don't care about invariant's own frame throw error; } }; } module.exports = invariant; },{}],113:[function(_dereq_,module,exports){ /** * Copyright 2013-2014 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. * * @providesModule isEventSupported */ "use strict"; var ExecutionEnvironment = _dereq_("./ExecutionEnvironment"); 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; },{"./ExecutionEnvironment":20}],114:[function(_dereq_,module,exports){ /** * Copyright 2013-2014 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. * * @providesModule isNode * @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; },{}],115:[function(_dereq_,module,exports){ /** * Copyright 2013-2014 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. * * @providesModule isTextInputElement */ "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) { return elem && ( (elem.nodeName === 'INPUT' && supportedInputTypes[elem.type]) || elem.nodeName === 'TEXTAREA' ); } module.exports = isTextInputElement; },{}],116:[function(_dereq_,module,exports){ /** * Copyright 2013-2014 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. * * @providesModule isTextNode * @typechecks */ var isNode = _dereq_("./isNode"); /** * @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; },{"./isNode":114}],117:[function(_dereq_,module,exports){ /** * Copyright 2013-2014 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. * * @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]; nextClass && (className += ' ' + nextClass); } } return className; } module.exports = joinClasses; },{}],118:[function(_dereq_,module,exports){ /** * Copyright 2013-2014 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. * * @providesModule keyMirror * @typechecks static-only */ "use strict"; var invariant = _dereq_("./invariant"); /** * Constructs an enumeration with keys equal to their value. * * For example: * * var COLORS = keyMirror({blue: null, red: null}); * var myColor = COLORS.blue; * var isColorValid = !!COLORS[myColor]; * * The last line could not be performed if the values of the generated enum were * not equal to their keys. * * Input: {key1: val1, key2: val2} * Output: {key1: key1, key2: key2} * * @param {object} obj * @return {object} */ var keyMirror = function(obj) { var ret = {}; var key; ("production" !== "development" ? invariant( obj instanceof Object && !Array.isArray(obj), 'keyMirror(...): Argument must be an object.' ) : invariant(obj instanceof Object && !Array.isArray(obj))); for (key in obj) { if (!obj.hasOwnProperty(key)) { continue; } ret[key] = key; } return ret; }; module.exports = keyMirror; },{"./invariant":112}],119:[function(_dereq_,module,exports){ /** * Copyright 2013-2014 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. * * @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; },{}],120:[function(_dereq_,module,exports){ /** * Copyright 2013-2014 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. * * @providesModule memoizeStringOnly * @typechecks static-only */ "use strict"; /** * Memoizes the return value of a function that accepts one string argument. * * @param {function} callback * @return {function} */ function memoizeStringOnly(callback) { var cache = {}; return function(string) { if (cache.hasOwnProperty(string)) { return cache[string]; } else { return cache[string] = callback.call(this, string); } }; } module.exports = memoizeStringOnly; },{}],121:[function(_dereq_,module,exports){ /** * Copyright 2013-2014 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. * * @providesModule merge */ "use strict"; var mergeInto = _dereq_("./mergeInto"); /** * Shallow merges two structures into a return value, without mutating either. * * @param {?object} one Optional object with properties to merge from. * @param {?object} two Optional object with properties to merge from. * @return {object} The shallow extension of one by two. */ var merge = function(one, two) { var result = {}; mergeInto(result, one); mergeInto(result, two); return result; }; module.exports = merge; },{"./mergeInto":123}],122:[function(_dereq_,module,exports){ /** * Copyright 2013-2014 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. * * @providesModule mergeHelpers * * requiresPolyfills: Array.isArray */ "use strict"; var invariant = _dereq_("./invariant"); var keyMirror = _dereq_("./keyMirror"); /** * Maximum number of levels to traverse. Will catch circular structures. * @const */ var MAX_MERGE_DEPTH = 36; /** * We won't worry about edge cases like new String('x') or new Boolean(true). * Functions are considered terminals, and arrays are not. * @param {*} o The item/object/value to test. * @return {boolean} true iff the argument is a terminal. */ var isTerminal = function(o) { return typeof o !== 'object' || o === null; }; var mergeHelpers = { MAX_MERGE_DEPTH: MAX_MERGE_DEPTH, isTerminal: isTerminal, /** * Converts null/undefined values into empty object. * * @param {?Object=} arg Argument to be normalized (nullable optional) * @return {!Object} */ normalizeMergeArg: function(arg) { return arg === undefined || arg === null ? {} : arg; }, /** * If merging Arrays, a merge strategy *must* be supplied. If not, it is * likely the caller's fault. If this function is ever called with anything * but `one` and `two` being `Array`s, it is the fault of the merge utilities. * * @param {*} one Array to merge into. * @param {*} two Array to merge from. */ checkMergeArrayArgs: function(one, two) { ("production" !== "development" ? invariant( Array.isArray(one) && Array.isArray(two), 'Tried to merge arrays, instead got %s and %s.', one, two ) : invariant(Array.isArray(one) && Array.isArray(two))); }, /** * @param {*} one Object to merge into. * @param {*} two Object to merge from. */ checkMergeObjectArgs: function(one, two) { mergeHelpers.checkMergeObjectArg(one); mergeHelpers.checkMergeObjectArg(two); }, /** * @param {*} arg */ checkMergeObjectArg: function(arg) { ("production" !== "development" ? invariant( !isTerminal(arg) && !Array.isArray(arg), 'Tried to merge an object, instead got %s.', arg ) : invariant(!isTerminal(arg) && !Array.isArray(arg))); }, /** * Checks that a merge was not given a circular object or an object that had * too great of depth. * * @param {number} Level of recursion to validate against maximum. */ checkMergeLevel: function(level) { ("production" !== "development" ? invariant( level < MAX_MERGE_DEPTH, 'Maximum deep merge depth exceeded. You may be attempting to merge ' + 'circular structures in an unsupported way.' ) : invariant(level < MAX_MERGE_DEPTH)); }, /** * Checks that the supplied merge strategy is valid. * * @param {string} Array merge strategy. */ checkArrayStrategy: function(strategy) { ("production" !== "development" ? invariant( strategy === undefined || strategy in mergeHelpers.ArrayStrategies, 'You must provide an array strategy to deep merge functions to ' + 'instruct the deep merge how to resolve merging two arrays.' ) : invariant(strategy === undefined || strategy in mergeHelpers.ArrayStrategies)); }, /** * Set of possible behaviors of merge algorithms when encountering two Arrays * that must be merged together. * - `clobber`: The left `Array` is ignored. * - `indexByIndex`: The result is achieved by recursively deep merging at * each index. (not yet supported.) */ ArrayStrategies: keyMirror({ Clobber: true, IndexByIndex: true }) }; module.exports = mergeHelpers; },{"./invariant":112,"./keyMirror":118}],123:[function(_dereq_,module,exports){ /** * Copyright 2013-2014 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. * * @providesModule mergeInto * @typechecks static-only */ "use strict"; var mergeHelpers = _dereq_("./mergeHelpers"); var checkMergeObjectArg = mergeHelpers.checkMergeObjectArg; /** * Shallow merges two structures by mutating the first parameter. * * @param {object} one Object to be merged into. * @param {?object} two Optional object with properties to merge from. */ function mergeInto(one, two) { checkMergeObjectArg(one); if (two != null) { checkMergeObjectArg(two); for (var key in two) { if (!two.hasOwnProperty(key)) { continue; } one[key] = two[key]; } } } module.exports = mergeInto; },{"./mergeHelpers":122}],124:[function(_dereq_,module,exports){ /** * Copyright 2013-2014 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. * * @providesModule mixInto */ "use strict"; /** * Simply copies properties to the prototype. */ var mixInto = function(constructor, methodBag) { var methodName; for (methodName in methodBag) { if (!methodBag.hasOwnProperty(methodName)) { continue; } constructor.prototype[methodName] = methodBag[methodName]; } }; module.exports = mixInto; },{}],125:[function(_dereq_,module,exports){ /** * Copyright 2014 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. * * @providesModule monitorCodeUse */ "use strict"; var invariant = _dereq_("./invariant"); /** * Provides open-source compatible instrumentation for monitoring certain API * uses before we're ready to issue a warning or refactor. It accepts an event * name which may only contain the characters [a-z0-9_] and an optional data * object with further information. */ function monitorCodeUse(eventName, data) { ("production" !== "development" ? invariant( eventName && !/[^a-z0-9_]/.test(eventName), 'You must provide an eventName using only the characters [a-z0-9_]' ) : invariant(eventName && !/[^a-z0-9_]/.test(eventName))); } module.exports = monitorCodeUse; },{"./invariant":112}],126:[function(_dereq_,module,exports){ /** * Copyright 2013-2014 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. * * @providesModule objMap */ "use strict"; /** * For each key/value pair, invokes callback func and constructs a resulting * object which contains, for every key in obj, values that are the result of * of invoking the function: * * func(value, key, iteration) * * @param {?object} obj Object to map keys over * @param {function} func Invoked for each key/val pair. * @param {?*} context * @return {?object} Result of mapping or null if obj is falsey */ function objMap(obj, func, context) { if (!obj) { return null; } var i = 0; var ret = {}; for (var key in obj) { if (obj.hasOwnProperty(key)) { ret[key] = func.call(context, obj[key], key, i++); } } return ret; } module.exports = objMap; },{}],127:[function(_dereq_,module,exports){ /** * Copyright 2013-2014 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. * * @providesModule objMapKeyVal */ "use strict"; /** * Behaves the same as `objMap` but invokes func with the key first, and value * second. Use `objMap` unless you need this special case. * Invokes func as: * * func(key, value, iteration) * * @param {?object} obj Object to map keys over * @param {!function} func Invoked for each key/val pair. * @param {?*} context * @return {?object} Result of mapping or null if obj is falsey */ function objMapKeyVal(obj, func, context) { if (!obj) { return null; } var i = 0; var ret = {}; for (var key in obj) { if (obj.hasOwnProperty(key)) { ret[key] = func.call(context, key, obj[key], i++); } } return ret; } module.exports = objMapKeyVal; },{}],128:[function(_dereq_,module,exports){ /** * Copyright 2013-2014 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. * * @providesModule onlyChild */ "use strict"; var ReactComponent = _dereq_("./ReactComponent"); var invariant = _dereq_("./invariant"); /** * Returns the first child in a collection of children and verifies that there * is only one child in the collection. The current implementation of this * function assumes that a single child gets passed without a wrapper, but the * purpose of this helper function is to abstract away the particular structure * of children. * * @param {?object} children Child collection structure. * @return {ReactComponent} The first and only `ReactComponent` contained in the * structure. */ function onlyChild(children) { ("production" !== "development" ? invariant( ReactComponent.isValidComponent(children), 'onlyChild must be passed a children with exactly one child.' ) : invariant(ReactComponent.isValidComponent(children))); return children; } module.exports = onlyChild; },{"./ReactComponent":27,"./invariant":112}],129:[function(_dereq_,module,exports){ /** * Copyright 2013-2014 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. * * @providesModule performanceNow * @typechecks static-only */ "use strict"; var ExecutionEnvironment = _dereq_("./ExecutionEnvironment"); /** * 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 due to Facebook's webdriver * infrastructure. */ var performance = null; if (ExecutionEnvironment.canUseDOM) { performance = window.performance || window.webkitPerformance; } if (!performance || !performance.now) { performance = Date; } var performanceNow = performance.now.bind(performance); module.exports = performanceNow; },{"./ExecutionEnvironment":20}],130:[function(_dereq_,module,exports){ /** * Copyright 2013-2014 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. * * @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'a keys missing from A. for (key in objB) { if (objB.hasOwnProperty(key) && !objA.hasOwnProperty(key)) { return false; } } return true; } module.exports = shallowEqual; },{}],131:[function(_dereq_,module,exports){ /** * Copyright 2013-2014 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. * * @providesModule shouldUpdateReactComponent * @typechecks static-only */ "use strict"; /** * Given a `prevComponentInstance` and `nextComponent`, determines if * `prevComponentInstance` should be updated as opposed to being destroyed or * replaced by a new instance. The second argument is a descriptor. Future * versions of the reconciler should only compare descriptors to other * descriptors. * * @param {?object} prevComponentInstance * @param {?object} nextDescriptor * @return {boolean} True if `prevComponentInstance` should be updated. * @protected */ function shouldUpdateReactComponent(prevComponentInstance, nextDescriptor) { // TODO: Remove warning after a release. if (prevComponentInstance && nextDescriptor && prevComponentInstance.constructor === nextDescriptor.constructor && ( (prevComponentInstance.props && prevComponentInstance.props.key) === (nextDescriptor.props && nextDescriptor.props.key) )) { if (prevComponentInstance._owner === nextDescriptor._owner) { return true; } else { if ("production" !== "development") { if (prevComponentInstance.state) { console.warn( 'A recent change to React has been found to impact your code. ' + 'A mounted component will now be unmounted and replaced by a ' + 'component (of the same class) if their owners are different. ' + 'Previously, ownership was not considered when updating.', prevComponentInstance, nextDescriptor ); } } } } return false; } module.exports = shouldUpdateReactComponent; },{}],132:[function(_dereq_,module,exports){ /** * Copyright 2014 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. * * @providesModule toArray * @typechecks */ var invariant = _dereq_("./invariant"); /** * Convert array-like objects to arrays. * * This API assumes the caller knows the contents of the data type. For less * well defined inputs use createArrayFrom. * * @param {object|function} obj * @return {array} */ function toArray(obj) { var length = obj.length; // Some browse builtin objects can report typeof 'function' (e.g. NodeList in // old versions of Safari). ("production" !== "development" ? invariant( !Array.isArray(obj) && (typeof obj === 'object' || typeof obj === 'function'), 'toArray: Array-like object expected' ) : invariant(!Array.isArray(obj) && (typeof obj === 'object' || typeof obj === 'function'))); ("production" !== "development" ? invariant( typeof length === 'number', 'toArray: Object needs a length property' ) : invariant(typeof length === 'number')); ("production" !== "development" ? invariant( length === 0 || (length - 1) in obj, 'toArray: Object should have keys for indices' ) : invariant(length === 0 || (length - 1) in obj)); // 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; } module.exports = toArray; },{"./invariant":112}],133:[function(_dereq_,module,exports){ /** * Copyright 2013-2014 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. * * @providesModule traverseAllChildren */ "use strict"; var ReactInstanceHandles = _dereq_("./ReactInstanceHandles"); var ReactTextComponent = _dereq_("./ReactTextComponent"); var invariant = _dereq_("./invariant"); var SEPARATOR = ReactInstanceHandles.SEPARATOR; var SUBSEPARATOR = ':'; /** * TODO: Test that: * 1. `mapChildren` transforms strings and numbers into `ReactTextComponent`. * 2. it('should fail when supplied duplicate key', function() { * 3. That a single child and an array with one item have the same key pattern. * }); */ var userProvidedKeyEscaperLookup = { '=': '=0', '.': '=1', ':': '=2' }; var userProvidedKeyEscapeRegex = /[=.:]/g; function userProvidedKeyEscaper(match) { return userProvidedKeyEscaperLookup[match]; } /** * 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) { if (component && component.props && component.props.key != null) { // Explicit key return wrapUserProvidedKey(component.props.key); } // Implicit key determined by the index in the set return index.toString(36); } /** * Escape a component key so that it is safe to use in a reactid. * * @param {*} key Component key to be escaped. * @return {string} An escaped string. */ function escapeUserProvidedKey(text) { return ('' + text).replace( userProvidedKeyEscapeRegex, userProvidedKeyEscaper ); } /** * Wrap a `key` value explicitly provided by the user to distinguish it from * implicitly-generated keys generated by a component's index in its parent. * * @param {string} key Value of a user-provided `key` attribute * @return {string} */ function wrapUserProvidedKey(key) { return '$' + escapeUserProvidedKey(key); } /** * @param {?*} children Children tree container. * @param {!string} nameSoFar Name of the key path so far. * @param {!number} indexSoFar Number of children encountered until this point. * @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. */ var traverseAllChildrenImpl = function(children, nameSoFar, indexSoFar, callback, traverseContext) { var subtreeCount = 0; // Count of children found in the current subtree. if (Array.isArray(children)) { for (var i = 0; i < children.length; i++) { var child = children[i]; var nextName = ( nameSoFar + (nameSoFar ? SUBSEPARATOR : SEPARATOR) + getComponentKey(child, i) ); var nextIndex = indexSoFar + subtreeCount; subtreeCount += traverseAllChildrenImpl( child, nextName, nextIndex, callback, traverseContext ); } } else { var type = typeof children; var isOnlyChild = nameSoFar === ''; // 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 var storageName = isOnlyChild ? SEPARATOR + getComponentKey(children, 0) : nameSoFar; if (children == null || type === 'boolean') { // All of the above are perceived as null. callback(traverseContext, null, storageName, indexSoFar); subtreeCount = 1; } else if (children.type && children.type.prototype && children.type.prototype.mountComponentIntoNode) { callback(traverseContext, children, storageName, indexSoFar); subtreeCount = 1; } else { if (type === 'object') { ("production" !== "development" ? invariant( !children || children.nodeType !== 1, 'traverseAllChildren(...): Encountered an invalid child; DOM ' + 'elements are not valid children of React components.' ) : invariant(!children || children.nodeType !== 1)); for (var key in children) { if (children.hasOwnProperty(key)) { subtreeCount += traverseAllChildrenImpl( children[key], ( nameSoFar + (nameSoFar ? SUBSEPARATOR : SEPARATOR) + wrapUserProvidedKey(key) + SUBSEPARATOR + getComponentKey(children[key], 0) ), indexSoFar + subtreeCount, callback, traverseContext ); } } } else if (type === 'string') { var normalizedText = new ReactTextComponent(children); callback(traverseContext, normalizedText, storageName, indexSoFar); subtreeCount += 1; } else if (type === 'number') { var normalizedNumber = new ReactTextComponent('' + children); callback(traverseContext, normalizedNumber, storageName, indexSoFar); subtreeCount += 1; } } } 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. */ function traverseAllChildren(children, callback, traverseContext) { if (children !== null && children !== undefined) { traverseAllChildrenImpl(children, '', 0, callback, traverseContext); } } module.exports = traverseAllChildren; },{"./ReactInstanceHandles":53,"./ReactTextComponent":70,"./invariant":112}],134:[function(_dereq_,module,exports){ /** * Copyright 2014 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. * * @providesModule warning */ "use strict"; var emptyFunction = _dereq_("./emptyFunction"); /** * 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" !== "development") { warning = function(condition, format ) {var args=Array.prototype.slice.call(arguments,2); if (format === undefined) { throw new Error( '`warning(condition, format, ...args)` requires a warning ' + 'message argument' ); } if (!condition) { var argIndex = 0; console.warn('Warning: ' + format.replace(/%s/g, function() {return args[argIndex++];})); } }; } module.exports = warning; },{"./emptyFunction":96}]},{},[24]) (24) });
angular.module("ngLocale", [], ["$provide", function($provide) { var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"}; $provide.value("$locale", { "DATETIME_FORMATS": { "AMPMS": { "0": "\u0635", "1": "\u0645" }, "DAY": { "0": "\u0627\u0644\u0623\u062d\u062f", "1": "\u0627\u0644\u0627\u062b\u0646\u064a\u0646", "2": "\u0627\u0644\u062b\u0644\u0627\u062b\u0627\u0621", "3": "\u0627\u0644\u0623\u0631\u0628\u0639\u0627\u0621", "4": "\u0627\u0644\u062e\u0645\u064a\u0633", "5": "\u0627\u0644\u062c\u0645\u0639\u0629", "6": "\u0627\u0644\u0633\u0628\u062a" }, "MONTH": { "0": "\u064a\u0646\u0627\u064a\u0631", "1": "\u0641\u0628\u0631\u0627\u064a\u0631", "2": "\u0645\u0627\u0631\u0633", "3": "\u0623\u0628\u0631\u064a\u0644", "4": "\u0645\u0627\u064a\u0648", "5": "\u064a\u0648\u0646\u064a\u0648", "6": "\u064a\u0648\u0644\u064a\u0648", "7": "\u0623\u063a\u0633\u0637\u0633", "8": "\u0633\u0628\u062a\u0645\u0628\u0631", "9": "\u0623\u0643\u062a\u0648\u0628\u0631", "10": "\u0646\u0648\u0641\u0645\u0628\u0631", "11": "\u062f\u064a\u0633\u0645\u0628\u0631" }, "SHORTDAY": { "0": "\u0627\u0644\u0623\u062d\u062f", "1": "\u0627\u0644\u0627\u062b\u0646\u064a\u0646", "2": "\u0627\u0644\u062b\u0644\u0627\u062b\u0627\u0621", "3": "\u0627\u0644\u0623\u0631\u0628\u0639\u0627\u0621", "4": "\u0627\u0644\u062e\u0645\u064a\u0633", "5": "\u0627\u0644\u062c\u0645\u0639\u0629", "6": "\u0627\u0644\u0633\u0628\u062a" }, "SHORTMONTH": { "0": "\u064a\u0646\u0627\u064a\u0631", "1": "\u0641\u0628\u0631\u0627\u064a\u0631", "2": "\u0645\u0627\u0631\u0633", "3": "\u0623\u0628\u0631\u064a\u0644", "4": "\u0645\u0627\u064a\u0648", "5": "\u064a\u0648\u0646\u064a\u0648", "6": "\u064a\u0648\u0644\u064a\u0648", "7": "\u0623\u063a\u0633\u0637\u0633", "8": "\u0633\u0628\u062a\u0645\u0628\u0631", "9": "\u0623\u0643\u062a\u0648\u0628\u0631", "10": "\u0646\u0648\u0641\u0645\u0628\u0631", "11": "\u062f\u064a\u0633\u0645\u0628\u0631" }, "fullDate": "EEEE\u060c d MMMM\u060c y", "longDate": "d MMMM\u060c y", "medium": "dd\u200f/MM\u200f/yyyy h:mm:ss a", "mediumDate": "dd\u200f/MM\u200f/yyyy", "mediumTime": "h:mm:ss a", "short": "d\u200f/M\u200f/yyyy h:mm a", "shortDate": "d\u200f/M\u200f/yyyy", "shortTime": "h:mm a" }, "NUMBER_FORMATS": { "CURRENCY_SYM": "\u00a3", "DECIMAL_SEP": "\u066b", "GROUP_SEP": "\u066c", "PATTERNS": { "0": { "gSize": 0, "lgSize": 0, "macFrac": 0, "maxFrac": 3, "minFrac": 0, "minInt": 1, "negPre": "", "negSuf": "-", "posPre": "", "posSuf": "" }, "1": { "gSize": 0, "lgSize": 0, "macFrac": 0, "maxFrac": 2, "minFrac": 2, "minInt": 1, "negPre": "\u00a4\u00a0", "negSuf": "-", "posPre": "\u00a4\u00a0", "posSuf": "" } } }, "id": "ar-ly", "pluralCat": function (n) { if (n == 0) { return PLURAL_CATEGORY.ZERO; } if (n == 1) { return PLURAL_CATEGORY.ONE; } if (n == 2) { return PLURAL_CATEGORY.TWO; } if (n == (n | 0) && n % 100 >= 3 && n % 100 <= 10) { return PLURAL_CATEGORY.FEW; } if (n == (n | 0) && n % 100 >= 11 && n % 100 <= 99) { return PLURAL_CATEGORY.MANY; } return PLURAL_CATEGORY.OTHER;} }); }]);
'use strict' module.exports = isExtraneous function isExtraneous (tree) { var result = !isNotExtraneous(tree) return result } function isNotRequired (tree) { return tree.requiredBy && tree.requiredBy.length === 0 } function parentHasNoPjson (tree) { return tree.parent && tree.parent.isTop && tree.parent.error } function topHasNoPjson (tree) { var top = tree while (!top.isTop) top = top.parent return top.error } function isNotExtraneous (tree, isCycle) { if (!isCycle) isCycle = {} if (tree.isTop || tree.userRequired) { return true } else if (isNotRequired(tree) && parentHasNoPjson(tree)) { return true } else if (isCycle[tree.path]) { return topHasNoPjson(tree) } else { isCycle[tree.path] = true return tree.requiredBy && tree.requiredBy.some(function (node) { return isNotExtraneous(node, Object.create(isCycle)) }) } }
!function(e){"object"==typeof exports?module.exports=e():"function"==typeof define&&define.amd?define(e):"undefined"!=typeof window?window.io=e():"undefined"!=typeof global?global.io=e():"undefined"!=typeof self&&(self.io=e())}(function(){var define,module,exports; return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){ module.exports = require('./lib/'); },{"./lib/":2}],2:[function(require,module,exports){ /** * Module dependencies. */ var url = require('./url'); var parser = require('socket.io-parser'); var Manager = require('./manager'); var debug = require('debug')('socket.io-client'); /** * Module exports. */ module.exports = exports = lookup; /** * Managers cache. */ var cache = exports.managers = {}; /** * Looks up an existing `Manager` for multiplexing. * If the user summons: * * `io('http://localhost/a');` * `io('http://localhost/b');` * * We reuse the existing instance based on same scheme/port/host, * and we initialize sockets for each namespace. * * @api public */ function lookup(uri, opts) { if (typeof uri == 'object') { opts = uri; uri = undefined; } opts = opts || {}; var parsed = url(uri); var source = parsed.source; var id = parsed.id; var io; if (opts.forceNew || false === opts.multiplex) { debug('ignoring socket cache for %s', source); io = Manager(source, opts); } else { if (!cache[id]) { debug('new io instance for %s', source); cache[id] = Manager(source, opts); } io = cache[id]; } return io.socket(parsed.path); } /** * Protocol version. * * @api public */ exports.protocol = parser.protocol; /** * `connect`. * * @param {String} uri * @api public */ exports.connect = lookup; /** * Expose constructors for standalone build. * * @api public */ exports.Manager = require('./manager'); exports.Socket = require('./socket'); },{"./manager":3,"./socket":5,"./url":6,"debug":9,"socket.io-parser":39}],3:[function(require,module,exports){ /** * Module dependencies. */ var url = require('./url'); var eio = require('engine.io-client'); var Socket = require('./socket'); var Emitter = require('emitter'); var parser = require('socket.io-parser'); var on = require('./on'); var bind = require('bind'); var object = require('object-component'); var debug = require('debug')('socket.io-client:manager'); /** * Module exports */ module.exports = Manager; /** * `Manager` constructor. * * @param {String} engine instance or engine uri/opts * @param {Object} options * @api public */ function Manager(uri, opts){ if (!(this instanceof Manager)) return new Manager(uri, opts); if ('object' == typeof uri) { opts = uri; uri = undefined; } opts = opts || {}; opts.path = opts.path || '/socket.io'; this.nsps = {}; this.subs = []; this.opts = opts; this.reconnection(opts.reconnection !== false); this.reconnectionAttempts(opts.reconnectionAttempts || Infinity); this.reconnectionDelay(opts.reconnectionDelay || 1000); this.reconnectionDelayMax(opts.reconnectionDelayMax || 5000); this.timeout(null == opts.timeout ? 20000 : opts.timeout); this.readyState = 'closed'; this.uri = uri; this.connected = 0; this.attempts = 0; this.encoding = false; this.packetBuffer = []; this.encoder = new parser.Encoder(); this.decoder = new parser.Decoder(); this.open(); } /** * Mix in `Emitter`. */ Emitter(Manager.prototype); /** * Sets the `reconnection` config. * * @param {Boolean} true/false if it should automatically reconnect * @return {Manager} self or value * @api public */ Manager.prototype.reconnection = function(v){ if (!arguments.length) return this._reconnection; this._reconnection = !!v; return this; }; /** * Sets the reconnection attempts config. * * @param {Number} max reconnection attempts before giving up * @return {Manager} self or value * @api public */ Manager.prototype.reconnectionAttempts = function(v){ if (!arguments.length) return this._reconnectionAttempts; this._reconnectionAttempts = v; return this; }; /** * Sets the delay between reconnections. * * @param {Number} delay * @return {Manager} self or value * @api public */ Manager.prototype.reconnectionDelay = function(v){ if (!arguments.length) return this._reconnectionDelay; this._reconnectionDelay = v; return this; }; /** * Sets the maximum delay between reconnections. * * @param {Number} delay * @return {Manager} self or value * @api public */ Manager.prototype.reconnectionDelayMax = function(v){ if (!arguments.length) return this._reconnectionDelayMax; this._reconnectionDelayMax = v; return this; }; /** * Sets the connection timeout. `false` to disable * * @return {Manager} self or value * @api public */ Manager.prototype.timeout = function(v){ if (!arguments.length) return this._timeout; this._timeout = v; return this; }; /** * Starts trying to reconnect if reconnection is enabled and we have not * started reconnecting yet * * @api private */ Manager.prototype.maybeReconnectOnOpen = function() { if (!this.openReconnect && !this.reconnecting && this._reconnection) { // keeps reconnection from firing twice for the same reconnection loop this.openReconnect = true; this.reconnect(); } }; /** * Sets the current transport `socket`. * * @param {Function} optional, callback * @return {Manager} self * @api public */ Manager.prototype.open = Manager.prototype.connect = function(fn){ debug('readyState %s', this.readyState); if (~this.readyState.indexOf('open')) return this; debug('opening %s', this.uri); this.engine = eio(this.uri, this.opts); var socket = this.engine; var self = this; this.readyState = 'opening'; // emit `open` var openSub = on(socket, 'open', function() { self.onopen(); fn && fn(); }); // emit `connect_error` var errorSub = on(socket, 'error', function(data){ debug('connect_error'); self.cleanup(); self.readyState = 'closed'; self.emit('connect_error', data); if (fn) { var err = new Error('Connection error'); err.data = data; fn(err); } self.maybeReconnectOnOpen(); }); // emit `connect_timeout` if (false !== this._timeout) { var timeout = this._timeout; debug('connect attempt will timeout after %d', timeout); // set timer var timer = setTimeout(function(){ debug('connect attempt timed out after %d', timeout); openSub.destroy(); socket.close(); socket.emit('error', 'timeout'); self.emit('connect_timeout', timeout); }, timeout); this.subs.push({ destroy: function(){ clearTimeout(timer); } }); } this.subs.push(openSub); this.subs.push(errorSub); return this; }; /** * Called upon transport open. * * @api private */ Manager.prototype.onopen = function(){ debug('open'); // clear old subs this.cleanup(); // mark as open this.readyState = 'open'; this.emit('open'); // add new subs var socket = this.engine; this.subs.push(on(socket, 'data', bind(this, 'ondata'))); this.subs.push(on(this.decoder, 'decoded', bind(this, 'ondecoded'))); this.subs.push(on(socket, 'error', bind(this, 'onerror'))); this.subs.push(on(socket, 'close', bind(this, 'onclose'))); }; /** * Called with data. * * @api private */ Manager.prototype.ondata = function(data){ this.decoder.add(data); }; /** * Called when parser fully decodes a packet. * * @api private */ Manager.prototype.ondecoded = function(packet) { this.emit('packet', packet); }; /** * Called upon socket error. * * @api private */ Manager.prototype.onerror = function(err){ debug('error', err); this.emit('error', err); }; /** * Creates a new socket for the given `nsp`. * * @return {Socket} * @api public */ Manager.prototype.socket = function(nsp){ var socket = this.nsps[nsp]; if (!socket) { socket = new Socket(this, nsp); this.nsps[nsp] = socket; var self = this; socket.on('connect', function(){ self.connected++; }); } return socket; }; /** * Called upon a socket close. * * @param {Socket} socket */ Manager.prototype.destroy = function(socket){ --this.connected || this.close(); }; /** * Writes a packet. * * @param {Object} packet * @api private */ Manager.prototype.packet = function(packet){ debug('writing packet %j', packet); var self = this; if (!self.encoding) { // encode, then write to engine with result self.encoding = true; this.encoder.encode(packet, function(encodedPackets) { for (var i = 0; i < encodedPackets.length; i++) { self.engine.write(encodedPackets[i]); } self.encoding = false; self.processPacketQueue(); }); } else { // add packet to the queue self.packetBuffer.push(packet); } }; /** * If packet buffer is non-empty, begins encoding the * next packet in line. * * @api private */ Manager.prototype.processPacketQueue = function() { if (this.packetBuffer.length > 0 && !this.encoding) { var pack = this.packetBuffer.shift(); this.packet(pack); } }; /** * Clean up transport subscriptions and packet buffer. * * @api private */ Manager.prototype.cleanup = function(){ var sub; while (sub = this.subs.shift()) sub.destroy(); this.packetBuffer = []; this.encoding = false; this.decoder.destroy(); }; /** * Close the current socket. * * @api private */ Manager.prototype.close = Manager.prototype.disconnect = function(){ this.skipReconnect = true; this.engine.close(); }; /** * Called upon engine close. * * @api private */ Manager.prototype.onclose = function(reason){ debug('close'); this.cleanup(); this.readyState = 'closed'; this.emit('close', reason); if (this._reconnection && !this.skipReconnect) { this.reconnect(); } }; /** * Attempt a reconnection. * * @api private */ Manager.prototype.reconnect = function(){ if (this.reconnecting) return this; var self = this; this.attempts++; if (this.attempts > this._reconnectionAttempts) { debug('reconnect failed'); this.emit('reconnect_failed'); this.reconnecting = false; } else { var delay = this.attempts * this.reconnectionDelay(); delay = Math.min(delay, this.reconnectionDelayMax()); debug('will wait %dms before reconnect attempt', delay); this.reconnecting = true; var timer = setTimeout(function(){ debug('attempting reconnect'); self.emit('reconnect_attempt'); self.open(function(err){ if (err) { debug('reconnect attempt error'); self.reconnecting = false; self.reconnect(); self.emit('reconnect_error', err.data); } else { debug('reconnect success'); self.onreconnect(); } }); }, delay); this.subs.push({ destroy: function(){ clearTimeout(timer); } }); } }; /** * Called upon successful reconnect. * * @api private */ Manager.prototype.onreconnect = function(){ var attempt = this.attempts; this.attempts = 0; this.reconnecting = false; this.emit('reconnect', attempt); }; },{"./on":4,"./socket":5,"./url":6,"bind":8,"debug":9,"emitter":10,"engine.io-client":11,"object-component":36,"socket.io-parser":39}],4:[function(require,module,exports){ /** * Module exports. */ module.exports = on; /** * Helper for subscriptions. * * @param {Object|EventEmitter} obj with `Emitter` mixin or `EventEmitter` * @param {String} event name * @param {Function} callback * @api public */ function on(obj, ev, fn) { obj.on(ev, fn); return { destroy: function(){ obj.removeListener(ev, fn); } }; } },{}],5:[function(require,module,exports){ /** * Module dependencies. */ var parser = require('socket.io-parser'); var Emitter = require('emitter'); var toArray = require('to-array'); var on = require('./on'); var bind = require('bind'); var debug = require('debug')('socket.io-client:socket'); var hasBin = require('has-binary-data'); var indexOf = require('indexof'); /** * Module exports. */ module.exports = exports = Socket; /** * Internal events (blacklisted). * These events can't be emitted by the user. * * @api private */ var events = { connect: 1, disconnect: 1, error: 1 }; /** * Shortcut to `Emitter#emit`. */ var emit = Emitter.prototype.emit; /** * `Socket` constructor. * * @api public */ function Socket(io, nsp){ this.io = io; this.nsp = nsp; this.json = this; // compat this.ids = 0; this.acks = {}; this.open(); this.buffer = []; this.connected = false; this.disconnected = true; } /** * Mix in `Emitter`. */ Emitter(Socket.prototype); /** * Called upon engine `open`. * * @api private */ Socket.prototype.open = Socket.prototype.connect = function(){ if (this.connected) return this; var io = this.io; io.open(); // ensure open this.subs = [ on(io, 'open', bind(this, 'onopen')), on(io, 'error', bind(this, 'onerror')), on(io, 'packet', bind(this, 'onpacket')), on(io, 'close', bind(this, 'onclose')) ]; if ('open' == this.io.readyState) this.onopen(); return this; }; /** * Sends a `message` event. * * @return {Socket} self * @api public */ Socket.prototype.send = function(){ var args = toArray(arguments); args.unshift('message'); this.emit.apply(this, args); return this; }; /** * Override `emit`. * If the event is in `events`, it's emitted normally. * * @param {String} event name * @return {Socket} self * @api public */ Socket.prototype.emit = function(ev){ if (events.hasOwnProperty(ev)) { emit.apply(this, arguments); return this; } var args = toArray(arguments); var parserType = parser.EVENT; // default if (hasBin(args)) { parserType = parser.BINARY_EVENT; } // binary var packet = { type: parserType, data: args }; // event ack callback if ('function' == typeof args[args.length - 1]) { debug('emitting packet with ack id %d', this.ids); this.acks[this.ids] = args.pop(); packet.id = this.ids++; } this.packet(packet); return this; }; /** * Sends a packet. * * @param {Object} packet * @api private */ Socket.prototype.packet = function(packet){ packet.nsp = this.nsp; this.io.packet(packet); }; /** * Called upon `error`. * * @param {Object} data * @api private */ Socket.prototype.onerror = function(data){ this.emit('error', data); }; /** * "Opens" the socket. * * @api private */ Socket.prototype.onopen = function(){ debug('transport is open - connecting'); // write connect packet if necessary if ('/' != this.nsp) { this.packet({ type: parser.CONNECT }); } }; /** * Called upon engine `close`. * * @param {String} reason * @api private */ Socket.prototype.onclose = function(reason){ debug('close (%s)', reason); this.connected = false; this.disconnected = true; this.emit('disconnect', reason); }; /** * Called with socket packet. * * @param {Object} packet * @api private */ Socket.prototype.onpacket = function(packet){ if (packet.nsp != this.nsp) return; switch (packet.type) { case parser.CONNECT: this.onconnect(); break; case parser.EVENT: this.onevent(packet); break; case parser.BINARY_EVENT: this.onevent(packet); break; case parser.ACK: this.onack(packet); break; case parser.DISCONNECT: this.ondisconnect(); break; case parser.ERROR: this.emit('error', packet.data); break; } }; /** * Called upon a server event. * * @param {Object} packet * @api private */ Socket.prototype.onevent = function(packet){ var args = packet.data || []; debug('emitting event %j', args); if (null != packet.id) { debug('attaching ack callback to event'); args.push(this.ack(packet.id)); } if (this.connected) { emit.apply(this, args); } else { this.buffer.push(args); } }; /** * Produces an ack callback to emit with an event. * * @api private */ Socket.prototype.ack = function(id){ var self = this; var sent = false; return function(){ // prevent double callbacks if (sent) return; sent = true; var args = toArray(arguments); debug('sending ack %j', args); self.packet({ type: parser.ACK, id: id, data: args }); }; }; /** * Called upon a server acknowlegement. * * @param {Object} packet * @api private */ Socket.prototype.onack = function(packet){ debug('calling ack %s with %j', packet.id, packet.data); var fn = this.acks[packet.id]; fn.apply(this, packet.data); delete this.acks[packet.id]; }; /** * Called upon server connect. * * @api private */ Socket.prototype.onconnect = function(){ this.connected = true; this.disconnected = false; this.emit('connect'); this.emitBuffered(); }; /** * Emit buffered events. * * @api private */ Socket.prototype.emitBuffered = function(){ for (var i = 0; i < this.buffer.length; i++) { emit.apply(this, this.buffer[i]); } this.buffer = []; }; /** * Called upon server disconnect. * * @api private */ Socket.prototype.ondisconnect = function(){ debug('server disconnect (%s)', this.nsp); this.destroy(); this.onclose('io server disconnect'); }; /** * Called upon forced client/server side disconnections, * this method ensures the manager stops tracking us and * that reconnections don't get triggered for this. * * @api private. */ Socket.prototype.destroy = function(){ // clean subscriptions to avoid reconnections for (var i = 0; i < this.subs.length; i++) { this.subs[i].destroy(); } this.io.destroy(this); }; /** * Disconnects the socket manually. * * @return {Socket} self * @api public */ Socket.prototype.close = Socket.prototype.disconnect = function(){ if (!this.connected) return this; debug('performing disconnect (%s)', this.nsp); this.packet({ type: parser.DISCONNECT }); // remove socket from pool this.destroy(); // fire events this.onclose('io client disconnect'); return this; }; },{"./on":4,"bind":8,"debug":9,"emitter":10,"has-binary-data":31,"indexof":35,"socket.io-parser":39,"to-array":42}],6:[function(require,module,exports){ var global=typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}; /** * Module dependencies. */ var parseuri = require('parseuri'); var debug = require('debug')('socket.io-client:url'); /** * Module exports. */ module.exports = url; /** * URL parser. * * @param {String} url * @param {Object} An object meant to mimic window.location. * Defaults to window.location. * @api public */ function url(uri, loc){ var obj = uri; // default to window.location var loc = loc || global.location; if (null == uri) uri = loc.protocol + '//' + loc.hostname; // relative path support if ('string' == typeof uri) { if ('/' == uri.charAt(0)) { if ('undefined' != typeof loc) { uri = loc.hostname + uri; } } if (!/^(https?|wss?):\/\//.test(uri)) { debug('protocol-less url %s', uri); if ('undefined' != typeof loc) { uri = loc.protocol + '//' + uri; } else { uri = 'https://' + uri; } } // parse debug('parse %s', uri); obj = parseuri(uri); } // make sure we treat `localhost:80` and `localhost` equally if ((/(http|ws)/.test(obj.protocol) && 80 == obj.port) || (/(http|ws)s/.test(obj.protocol) && 443 == obj.port)) { delete obj.port; } obj.path = obj.path || '/'; // define unique id obj.id = obj.protocol + obj.host + (obj.port ? (':' + obj.port) : ''); // define href obj.href = obj.protocol + '://' + obj.host + (obj.port ? (':' + obj.port) : ''); return obj; } },{"debug":9,"parseuri":37}],7:[function(require,module,exports){ /* * base64-arraybuffer * https://github.com/niklasvh/base64-arraybuffer * * Copyright (c) 2012 Niklas von Hertzen * Licensed under the MIT license. */ (function(chars){ "use strict"; exports.encode = function(arraybuffer) { var bytes = new Uint8Array(arraybuffer), i, len = bytes.buffer.byteLength, base64 = ""; for (i = 0; i < len; i+=3) { base64 += chars[bytes.buffer[i] >> 2]; base64 += chars[((bytes.buffer[i] & 3) << 4) | (bytes.buffer[i + 1] >> 4)]; base64 += chars[((bytes.buffer[i + 1] & 15) << 2) | (bytes.buffer[i + 2] >> 6)]; base64 += chars[bytes.buffer[i + 2] & 63]; } if ((len % 3) === 2) { base64 = base64.substring(0, base64.length - 1) + "="; } else if (len % 3 === 1) { base64 = base64.substring(0, base64.length - 2) + "=="; } return base64; }; exports.decode = function(base64) { var bufferLength = base64.length * 0.75, len = base64.length, i, p = 0, encoded1, encoded2, encoded3, encoded4; if (base64[base64.length - 1] === "=") { bufferLength--; if (base64[base64.length - 2] === "=") { bufferLength--; } } var arraybuffer = new ArrayBuffer(bufferLength), bytes = new Uint8Array(arraybuffer); for (i = 0; i < len; i+=4) { encoded1 = chars.indexOf(base64[i]); encoded2 = chars.indexOf(base64[i+1]); encoded3 = chars.indexOf(base64[i+2]); encoded4 = chars.indexOf(base64[i+3]); bytes[p++] = (encoded1 << 2) | (encoded2 >> 4); bytes[p++] = ((encoded2 & 15) << 4) | (encoded3 >> 2); bytes[p++] = ((encoded3 & 3) << 6) | (encoded4 & 63); } return arraybuffer; }; })("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"); },{}],8:[function(require,module,exports){ /** * Slice reference. */ var slice = [].slice; /** * Bind `obj` to `fn`. * * @param {Object} obj * @param {Function|String} fn or string * @return {Function} * @api public */ module.exports = function(obj, fn){ if ('string' == typeof fn) fn = obj[fn]; if ('function' != typeof fn) throw new Error('bind() requires a function'); var args = [].slice.call(arguments, 2); return function(){ return fn.apply(obj, args.concat(slice.call(arguments))); } }; },{}],9:[function(require,module,exports){ /** * Expose `debug()` as the module. */ module.exports = debug; /** * Create a debugger with the given `name`. * * @param {String} name * @return {Type} * @api public */ function debug(name) { if (!debug.enabled(name)) return function(){}; return function(fmt){ fmt = coerce(fmt); var curr = new Date; var ms = curr - (debug[name] || curr); debug[name] = curr; fmt = name + ' ' + fmt + ' +' + debug.humanize(ms); // This hackery is required for IE8 // where `console.log` doesn't have 'apply' window.console && console.log && Function.prototype.apply.call(console.log, console, arguments); } } /** * The currently active debug mode names. */ debug.names = []; debug.skips = []; /** * Enables a debug mode by name. This can include modes * separated by a colon and wildcards. * * @param {String} name * @api public */ debug.enable = function(name) { try { localStorage.debug = name; } catch(e){} var split = (name || '').split(/[\s,]+/) , len = split.length; for (var i = 0; i < len; i++) { name = split[i].replace('*', '.*?'); if (name[0] === '-') { debug.skips.push(new RegExp('^' + name.substr(1) + '$')); } else { debug.names.push(new RegExp('^' + name + '$')); } } }; /** * Disable debug output. * * @api public */ debug.disable = function(){ debug.enable(''); }; /** * Humanize the given `ms`. * * @param {Number} m * @return {String} * @api private */ debug.humanize = function(ms) { var sec = 1000 , min = 60 * 1000 , hour = 60 * min; if (ms >= hour) return (ms / hour).toFixed(1) + 'h'; if (ms >= min) return (ms / min).toFixed(1) + 'm'; if (ms >= sec) return (ms / sec | 0) + 's'; return ms + 'ms'; }; /** * Returns true if the given mode name is enabled, false otherwise. * * @param {String} name * @return {Boolean} * @api public */ debug.enabled = function(name) { for (var i = 0, len = debug.skips.length; i < len; i++) { if (debug.skips[i].test(name)) { return false; } } for (var i = 0, len = debug.names.length; i < len; i++) { if (debug.names[i].test(name)) { return true; } } return false; }; /** * Coerce `val`. */ function coerce(val) { if (val instanceof Error) return val.stack || val.message; return val; } // persist try { if (window.localStorage) debug.enable(localStorage.debug); } catch(e){} },{}],10:[function(require,module,exports){ /** * Module dependencies. */ var index = require('indexof'); /** * Expose `Emitter`. */ module.exports = Emitter; /** * Initialize a new `Emitter`. * * @api public */ function Emitter(obj) { if (obj) return mixin(obj); }; /** * Mixin the emitter properties. * * @param {Object} obj * @return {Object} * @api private */ function mixin(obj) { for (var key in Emitter.prototype) { obj[key] = Emitter.prototype[key]; } return obj; } /** * Listen on the given `event` with `fn`. * * @param {String} event * @param {Function} fn * @return {Emitter} * @api public */ Emitter.prototype.on = function(event, fn){ this._callbacks = this._callbacks || {}; (this._callbacks[event] = this._callbacks[event] || []) .push(fn); return this; }; /** * Adds an `event` listener that will be invoked a single * time then automatically removed. * * @param {String} event * @param {Function} fn * @return {Emitter} * @api public */ Emitter.prototype.once = function(event, fn){ var self = this; this._callbacks = this._callbacks || {}; function on() { self.off(event, on); fn.apply(this, arguments); } fn._off = on; this.on(event, on); return this; }; /** * Remove the given callback for `event` or all * registered callbacks. * * @param {String} event * @param {Function} fn * @return {Emitter} * @api public */ Emitter.prototype.off = Emitter.prototype.removeListener = Emitter.prototype.removeAllListeners = function(event, fn){ this._callbacks = this._callbacks || {}; // all if (0 == arguments.length) { this._callbacks = {}; return this; } // specific event var callbacks = this._callbacks[event]; if (!callbacks) return this; // remove all handlers if (1 == arguments.length) { delete this._callbacks[event]; return this; } // remove specific handler var i = index(callbacks, fn._off || fn); if (~i) callbacks.splice(i, 1); return this; }; /** * Emit `event` with the given args. * * @param {String} event * @param {Mixed} ... * @return {Emitter} */ Emitter.prototype.emit = function(event){ this._callbacks = this._callbacks || {}; var args = [].slice.call(arguments, 1) , callbacks = this._callbacks[event]; if (callbacks) { callbacks = callbacks.slice(0); for (var i = 0, len = callbacks.length; i < len; ++i) { callbacks[i].apply(this, args); } } return this; }; /** * Return array of callbacks for `event`. * * @param {String} event * @return {Array} * @api public */ Emitter.prototype.listeners = function(event){ this._callbacks = this._callbacks || {}; return this._callbacks[event] || []; }; /** * Check if this emitter has `event` handlers. * * @param {String} event * @return {Boolean} * @api public */ Emitter.prototype.hasListeners = function(event){ return !! this.listeners(event).length; }; },{"indexof":35}],11:[function(require,module,exports){ module.exports = require('./lib/'); },{"./lib/":13}],12:[function(require,module,exports){ /** * Module dependencies. */ var Emitter = require('emitter'); /** * Module exports. */ module.exports = Emitter; /** * Compatibility with `WebSocket#addEventListener`. * * @api public */ Emitter.prototype.addEventListener = Emitter.prototype.on; /** * Compatibility with `WebSocket#removeEventListener`. * * @api public */ Emitter.prototype.removeEventListener = Emitter.prototype.off; /** * Node-compatible `EventEmitter#removeListener` * * @api public */ Emitter.prototype.removeListener = Emitter.prototype.off; },{"emitter":10}],13:[function(require,module,exports){ module.exports = require('./socket'); /** * Exports parser * * @api public * */ module.exports.parser = require('engine.io-parser'); },{"./socket":14,"engine.io-parser":24}],14:[function(require,module,exports){ var global=typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {};/** * Module dependencies. */ var util = require('./util'); var transports = require('./transports'); var Emitter = require('./emitter'); var debug = require('debug')('engine.io-client:socket'); var index = require('indexof'); var parser = require('engine.io-parser'); var parseuri = require('parseuri'); var parsejson = require('parsejson'); /** * Module exports. */ module.exports = Socket; /** * Noop function. * * @api private */ function noop(){} /** * Socket constructor. * * @param {String|Object} uri or options * @param {Object} options * @api public */ function Socket(uri, opts){ if (!(this instanceof Socket)) return new Socket(uri, opts); opts = opts || {}; if (uri && 'object' == typeof uri) { opts = uri; uri = null; } if (uri) { uri = parseuri(uri); opts.host = uri.host; opts.secure = uri.protocol == 'https' || uri.protocol == 'wss'; opts.port = uri.port; if (uri.query) opts.query = uri.query; } this.secure = null != opts.secure ? opts.secure : (global.location && 'https:' == location.protocol); if (opts.host) { var pieces = opts.host.split(':'); opts.hostname = pieces.shift(); if (pieces.length) opts.port = pieces.pop(); } this.agent = opts.agent || false; this.hostname = opts.hostname || (global.location ? location.hostname : 'localhost'); this.port = opts.port || (global.location && location.port ? location.port : (this.secure ? 443 : 80)); this.query = opts.query || {}; if ('string' == typeof this.query) this.query = util.qsParse(this.query); this.upgrade = false !== opts.upgrade; this.path = (opts.path || '/engine.io').replace(/\/$/, '') + '/'; this.forceJSONP = !!opts.forceJSONP; this.forceBase64 = !!opts.forceBase64; this.timestampParam = opts.timestampParam || 't'; this.timestampRequests = opts.timestampRequests; this.flashPath = opts.flashPath || ''; this.transports = opts.transports || ['polling', 'websocket', 'flashsocket']; this.readyState = ''; this.writeBuffer = []; this.callbackBuffer = []; this.policyPort = opts.policyPort || 843; this.rememberUpgrade = opts.rememberUpgrade || false; this.open(); this.binaryType = null; this.onlyBinaryUpgrades = opts.onlyBinaryUpgrades; } Socket.priorWebsocketSuccess = false; /** * Mix in `Emitter`. */ Emitter(Socket.prototype); /** * Protocol version. * * @api public */ Socket.protocol = parser.protocol; // this is an int /** * Expose deps for legacy compatibility * and standalone browser access. */ Socket.Socket = Socket; Socket.Transport = require('./transport'); Socket.Emitter = require('./emitter'); Socket.transports = require('./transports'); Socket.util = require('./util'); Socket.parser = require('engine.io-parser'); /** * Creates transport of the given type. * * @param {String} transport name * @return {Transport} * @api private */ Socket.prototype.createTransport = function (name) { debug('creating transport "%s"', name); var query = clone(this.query); // append engine.io protocol identifier query.EIO = parser.protocol; // transport name query.transport = name; // session id if we already have one if (this.id) query.sid = this.id; var transport = new transports[name]({ agent: this.agent, hostname: this.hostname, port: this.port, secure: this.secure, path: this.path, query: query, forceJSONP: this.forceJSONP, forceBase64: this.forceBase64, timestampRequests: this.timestampRequests, timestampParam: this.timestampParam, flashPath: this.flashPath, policyPort: this.policyPort, socket: this }); return transport; }; function clone (obj) { var o = {}; for (var i in obj) { if (obj.hasOwnProperty(i)) { o[i] = obj[i]; } } return o; } /** * Initializes transport to use and starts probe. * * @api private */ Socket.prototype.open = function () { var transport; if (this.rememberUpgrade && Socket.priorWebsocketSuccess && this.transports.indexOf('websocket') != -1) { transport = 'websocket'; } else { transport = this.transports[0]; } this.readyState = 'opening'; var transport = this.createTransport(transport); transport.open(); this.setTransport(transport); }; /** * Sets the current transport. Disables the existing one (if any). * * @api private */ Socket.prototype.setTransport = function(transport){ debug('setting transport %s', transport.name); var self = this; if (this.transport) { debug('clearing existing transport %s', this.transport.name); this.transport.removeAllListeners(); } // set up transport this.transport = transport; // set up transport listeners transport .on('drain', function(){ self.onDrain(); }) .on('packet', function(packet){ self.onPacket(packet); }) .on('error', function(e){ self.onError(e); }) .on('close', function(){ self.onClose('transport close'); }); }; /** * Probes a transport. * * @param {String} transport name * @api private */ Socket.prototype.probe = function (name) { debug('probing transport "%s"', name); var transport = this.createTransport(name, { probe: 1 }) , failed = false , self = this; Socket.priorWebsocketSuccess = false; transport.once('open', function () { if (this.onlyBinaryUpgrades) { var upgradeLosesBinary = !this.supportsBinary && self.transport.supportsBinary; failed = failed || upgradeLosesBinary; } if (failed) return; debug('probe transport "%s" opened', name); transport.send([{ type: 'ping', data: 'probe' }]); transport.once('packet', function (msg) { if (failed) return; if ('pong' == msg.type && 'probe' == msg.data) { debug('probe transport "%s" pong', name); self.upgrading = true; self.emit('upgrading', transport); Socket.priorWebsocketSuccess = 'websocket' == transport.name; debug('pausing current transport "%s"', self.transport.name); self.transport.pause(function () { if (failed) return; if ('closed' == self.readyState || 'closing' == self.readyState) { return; } debug('changing transport and sending upgrade packet'); transport.removeListener('error', onerror); self.setTransport(transport); transport.send([{ type: 'upgrade' }]); self.emit('upgrade', transport); transport = null; self.upgrading = false; self.flush(); }); } else { debug('probe transport "%s" failed', name); var err = new Error('probe error'); err.transport = transport.name; self.emit('upgradeError', err); } }); }); transport.once('error', onerror); function onerror(err) { if (failed) return; // Any callback called by transport should be ignored since now failed = true; var error = new Error('probe error: ' + err); error.transport = transport.name; transport.close(); transport = null; debug('probe transport "%s" failed because of error: %s', name, err); self.emit('upgradeError', error); } transport.open(); this.once('close', function () { if (transport) { debug('socket closed prematurely - aborting probe'); failed = true; transport.close(); transport = null; } }); this.once('upgrading', function (to) { if (transport && to.name != transport.name) { debug('"%s" works - aborting "%s"', to.name, transport.name); transport.close(); transport = null; } }); }; /** * Called when connection is deemed open. * * @api public */ Socket.prototype.onOpen = function () { debug('socket open'); this.readyState = 'open'; Socket.priorWebsocketSuccess = 'websocket' == this.transport.name; this.emit('open'); this.onopen && this.onopen.call(this); this.flush(); // we check for `readyState` in case an `open` // listener already closed the socket if ('open' == this.readyState && this.upgrade && this.transport.pause) { debug('starting upgrade probes'); for (var i = 0, l = this.upgrades.length; i < l; i++) { this.probe(this.upgrades[i]); } } }; /** * Handles a packet. * * @api private */ Socket.prototype.onPacket = function (packet) { if ('opening' == this.readyState || 'open' == this.readyState) { debug('socket receive: type "%s", data "%s"', packet.type, packet.data); this.emit('packet', packet); // Socket is live - any packet counts this.emit('heartbeat'); switch (packet.type) { case 'open': this.onHandshake(parsejson(packet.data)); break; case 'pong': this.setPing(); break; case 'error': var err = new Error('server error'); err.code = packet.data; this.emit('error', err); break; case 'message': this.emit('data', packet.data); this.emit('message', packet.data); var event = { data: packet.data }; event.toString = function () { return packet.data; }; this.onmessage && this.onmessage.call(this, event); break; } } else { debug('packet received with socket readyState "%s"', this.readyState); } }; /** * Called upon handshake completion. * * @param {Object} handshake obj * @api private */ Socket.prototype.onHandshake = function (data) { this.emit('handshake', data); this.id = data.sid; this.transport.query.sid = data.sid; this.upgrades = this.filterUpgrades(data.upgrades); this.pingInterval = data.pingInterval; this.pingTimeout = data.pingTimeout; this.onOpen(); this.setPing(); // Prolong liveness of socket on heartbeat this.removeListener('heartbeat', this.onHeartbeat); this.on('heartbeat', this.onHeartbeat); }; /** * Resets ping timeout. * * @api private */ Socket.prototype.onHeartbeat = function (timeout) { clearTimeout(this.pingTimeoutTimer); var self = this; self.pingTimeoutTimer = setTimeout(function () { if ('closed' == self.readyState) return; self.onClose('ping timeout'); }, timeout || (self.pingInterval + self.pingTimeout)); }; /** * Pings server every `this.pingInterval` and expects response * within `this.pingTimeout` or closes connection. * * @api private */ Socket.prototype.setPing = function () { var self = this; clearTimeout(self.pingIntervalTimer); self.pingIntervalTimer = setTimeout(function () { debug('writing ping packet - expecting pong within %sms', self.pingTimeout); self.ping(); self.onHeartbeat(self.pingTimeout); }, self.pingInterval); }; /** * Sends a ping packet. * * @api public */ Socket.prototype.ping = function () { this.sendPacket('ping'); }; /** * Called on `drain` event * * @api private */ Socket.prototype.onDrain = function() { for (var i = 0; i < this.prevBufferLen; i++) { if (this.callbackBuffer[i]) { this.callbackBuffer[i](); } } this.writeBuffer.splice(0, this.prevBufferLen); this.callbackBuffer.splice(0, this.prevBufferLen); // setting prevBufferLen = 0 is very important // for example, when upgrading, upgrade packet is sent over, // and a nonzero prevBufferLen could cause problems on `drain` this.prevBufferLen = 0; if (this.writeBuffer.length == 0) { this.emit('drain'); } else { this.flush(); } }; /** * Flush write buffers. * * @api private */ Socket.prototype.flush = function () { if ('closed' != this.readyState && this.transport.writable && !this.upgrading && this.writeBuffer.length) { debug('flushing %d packets in socket', this.writeBuffer.length); this.transport.send(this.writeBuffer); // keep track of current length of writeBuffer // splice writeBuffer and callbackBuffer on `drain` this.prevBufferLen = this.writeBuffer.length; this.emit('flush'); } }; /** * Sends a message. * * @param {String} message. * @param {Function} callback function. * @return {Socket} for chaining. * @api public */ Socket.prototype.write = Socket.prototype.send = function (msg, fn) { this.sendPacket('message', msg, fn); return this; }; /** * Sends a packet. * * @param {String} packet type. * @param {String} data. * @param {Function} callback function. * @api private */ Socket.prototype.sendPacket = function (type, data, fn) { var packet = { type: type, data: data }; this.emit('packetCreate', packet); this.writeBuffer.push(packet); this.callbackBuffer.push(fn); this.flush(); }; /** * Closes the connection. * * @api private */ Socket.prototype.close = function () { if ('opening' == this.readyState || 'open' == this.readyState) { this.onClose('forced close'); debug('socket closing - telling transport to close'); this.transport.close(); } return this; }; /** * Called upon transport error * * @api private */ Socket.prototype.onError = function (err) { debug('socket error %j', err); Socket.priorWebsocketSuccess = false; this.emit('error', err); this.onerror && this.onerror.call(this, err); this.onClose('transport error', err); }; /** * Called upon transport close. * * @api private */ Socket.prototype.onClose = function (reason, desc) { if ('opening' == this.readyState || 'open' == this.readyState) { debug('socket close with reason: "%s"', reason); var self = this; // clear timers clearTimeout(this.pingIntervalTimer); clearTimeout(this.pingTimeoutTimer); // clean buffers in next tick, so developers can still // grab the buffers on `close` event setTimeout(function() { self.writeBuffer = []; self.callbackBuffer = []; self.prevBufferLen = 0; }, 0); // ignore further transport communication this.transport.removeAllListeners(); // set ready state this.readyState = 'closed'; // clear session id this.id = null; // emit close event this.emit('close', reason, desc); this.onclose && this.onclose.call(this); } }; /** * Filters upgrades, returning only those matching client transports. * * @param {Array} server upgrades * @api private * */ Socket.prototype.filterUpgrades = function (upgrades) { var filteredUpgrades = []; for (var i = 0, j = upgrades.length; i<j; i++) { if (~index(this.transports, upgrades[i])) filteredUpgrades.push(upgrades[i]); } return filteredUpgrades; }; },{"./emitter":12,"./transport":15,"./transports":17,"./util":22,"debug":9,"engine.io-parser":24,"indexof":35,"parsejson":29,"parseuri":37}],15:[function(require,module,exports){ /** * Module dependencies. */ var util = require('./util'); var parser = require('engine.io-parser'); var Emitter = require('./emitter'); /** * Module exports. */ module.exports = Transport; /** * Transport abstract constructor. * * @param {Object} options. * @api private */ function Transport (opts) { this.path = opts.path; this.hostname = opts.hostname; this.port = opts.port; this.secure = opts.secure; this.query = opts.query; this.timestampParam = opts.timestampParam; this.timestampRequests = opts.timestampRequests; this.readyState = ''; this.agent = opts.agent || false; this.socket = opts.socket; } /** * Mix in `Emitter`. */ Emitter(Transport.prototype); /** * Emits an error. * * @param {String} str * @return {Transport} for chaining * @api public */ Transport.prototype.onError = function (msg, desc) { var err = new Error(msg); err.type = 'TransportError'; err.description = desc; this.emit('error', err); return this; }; /** * Opens the transport. * * @api public */ Transport.prototype.open = function () { if ('closed' == this.readyState || '' == this.readyState) { this.readyState = 'opening'; this.doOpen(); } return this; }; /** * Closes the transport. * * @api private */ Transport.prototype.close = function () { if ('opening' == this.readyState || 'open' == this.readyState) { this.doClose(); this.onClose(); } return this; }; /** * Sends multiple packets. * * @param {Array} packets * @api private */ Transport.prototype.send = function(packets){ if ('open' == this.readyState) { this.write(packets); } else { throw new Error('Transport not open'); } }; /** * Called upon open * * @api private */ Transport.prototype.onOpen = function () { this.readyState = 'open'; this.writable = true; this.emit('open'); }; /** * Called with data. * * @param {String} data * @api private */ Transport.prototype.onData = function (data) { this.onPacket(parser.decodePacket(data, this.socket.binaryType)); }; /** * Called with a decoded packet. */ Transport.prototype.onPacket = function (packet) { this.emit('packet', packet); }; /** * Called upon close. * * @api private */ Transport.prototype.onClose = function () { this.readyState = 'closed'; this.emit('close'); }; },{"./emitter":12,"./util":22,"engine.io-parser":24}],16:[function(require,module,exports){ var global=typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}; /** * Module dependencies. */ var WS = require('./websocket'); var util = require('../util'); var debug = require('debug')('engine.io-client:flashsocket'); /** * Module exports. */ module.exports = FlashWS; /** * Obfuscated key for Blue Coat. */ var xobject = global[['Active'].concat('Object').join('X')]; /** * FlashWS constructor. * * @api public */ function FlashWS(options){ WS.call(this, options); this.flashPath = options.flashPath; this.policyPort = options.policyPort; } /** * Inherits from WebSocket. */ util.inherits(FlashWS, WS); /** * Transport name. * * @api public */ FlashWS.prototype.name = 'flashsocket'; /* * FlashSockets only support binary as base64 encoded strings */ FlashWS.prototype.supportsBinary = false; /** * Opens the transport. * * @api public */ FlashWS.prototype.doOpen = function(){ if (!this.check()) { // let the probe timeout return; } // instrument websocketjs logging function log(type){ return function(){ var str = Array.prototype.join.call(arguments, ' '); debug('[websocketjs %s] %s', type, str); }; } global.WEB_SOCKET_LOGGER = { log: log('debug'), error: log('error') }; global.WEB_SOCKET_SUPPRESS_CROSS_DOMAIN_SWF_ERROR = true; global.WEB_SOCKET_DISABLE_AUTO_INITIALIZATION = true; if (!global.WEB_SOCKET_SWF_LOCATION) { global.WEB_SOCKET_SWF_LOCATION = this.flashPath + 'WebSocketMainInsecure.swf'; } // dependencies var deps = [this.flashPath + 'web_socket.js']; if (!global.swfobject) { deps.unshift(this.flashPath + 'swfobject.js'); } var self = this; load(deps, function(){ self.ready(function(){ WebSocket.__addTask(function () { self.ws = new WebSocket(self.uri()); self.addEventListeners(); }); }); }); }; /** * Override to prevent closing uninitialized flashsocket. * * @api private */ FlashWS.prototype.doClose = function(){ if (!this.ws) return; var self = this; WebSocket.__addTask(function(){ WS.prototype.doClose.call(self); }); }; /** * Writes to the Flash socket. * * @api private */ FlashWS.prototype.write = function(){ var self = this, args = arguments; WebSocket.__addTask(function(){ WS.prototype.write.apply(self, args); }); }; /** * Called upon dependencies are loaded. * * @api private */ FlashWS.prototype.ready = function(fn){ if (typeof WebSocket == 'undefined' || !('__initialize' in WebSocket) || !global.swfobject) { return; } if (global.swfobject.getFlashPlayerVersion().major < 10) { return; } function init () { // only start downloading the swf file when // we checked that this browser actually supports it if (!FlashWS.loaded) { if (843 != self.policyPort) { var policy = 'xmlsocket://' + self.hostname + ':' + self.policyPort; WebSocket.loadFlashPolicyFile(policy); } WebSocket.__initialize(); FlashWS.loaded = true; } fn.call(self); } var self = this; if (document.body) { return init(); } util.load(init); }; /** * Feature detection for flashsocket. * * @return {Boolean} whether this transport is available. * @api public */ FlashWS.prototype.check = function(){ if ('undefined' == typeof window) { return false; } if (typeof WebSocket != 'undefined' && !('__initialize' in WebSocket)) { return false; } if (xobject) { var control = null; try { control = new xobject('ShockwaveFlash.ShockwaveFlash'); } catch (e) { } if (control) { return true; } } else { for (var i = 0, l = navigator.plugins.length; i < l; i++) { for (var j = 0, m = navigator.plugins[i].length; j < m; j++) { if (navigator.plugins[i][j].description == 'Shockwave Flash') { return true; } } } } return false; }; /** * Lazy loading of scripts. * Based on $script by Dustin Diaz - MIT */ var scripts = {}; /** * Injects a script. Keeps tracked of injected ones. * * @param {String} path * @param {Function} callback * @api private */ function create(path, fn){ if (scripts[path]) return fn(); var el = document.createElement('script'); var loaded = false; debug('loading "%s"', path); el.onload = el.onreadystatechange = function(){ if (loaded || scripts[path]) return; var rs = el.readyState; if (!rs || 'loaded' == rs || 'complete' == rs) { debug('loaded "%s"', path); el.onload = el.onreadystatechange = null; loaded = true; scripts[path] = true; fn(); } }; el.async = 1; el.src = path; var head = document.getElementsByTagName('head')[0]; head.insertBefore(el, head.firstChild); } /** * Loads scripts and fires a callback. * * @param {Array} paths * @param {Function} callback */ function load(arr, fn){ function process(i){ if (!arr[i]) return fn(); create(arr[i], function () { process(++i); }); } process(0); } },{"../util":22,"./websocket":21,"debug":9}],17:[function(require,module,exports){ var global=typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}; /** * Module dependencies */ var XMLHttpRequest = require('xmlhttprequest') , XHR = require('./polling-xhr') , JSONP = require('./polling-jsonp') , websocket = require('./websocket') , flashsocket = require('./flashsocket') /** * Export transports. */ exports.polling = polling; exports.websocket = websocket; exports.flashsocket = flashsocket; /** * Polling transport polymorphic constructor. * Decides on xhr vs jsonp based on feature detection. * * @api private */ function polling (opts) { var xhr , xd = false; if (global.location) { var isSSL = 'https:' == location.protocol; var port = location.port; // some user agents have empty `location.port` if (!port) { port = isSSL ? 443 : 80; } xd = opts.hostname != location.hostname || port != opts.port; } opts.xdomain = xd; xhr = new XMLHttpRequest(opts); if (xhr && !opts.forceJSONP) { return new XHR(opts); } else { return new JSONP(opts); } }; },{"./flashsocket":16,"./polling-jsonp":18,"./polling-xhr":19,"./websocket":21,"xmlhttprequest":23}],18:[function(require,module,exports){ var global=typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}; /** * Module requirements. */ var Polling = require('./polling'); var util = require('../util'); /** * Module exports. */ module.exports = JSONPPolling; /** * Cached regular expressions. */ var rNewline = /\n/g; /** * Global JSONP callbacks. */ var callbacks; /** * Callbacks count. */ var index = 0; /** * Noop. */ function empty () { } /** * JSONP Polling constructor. * * @param {Object} opts. * @api public */ function JSONPPolling (opts) { Polling.call(this, opts); // define global callbacks array if not present // we do this here (lazily) to avoid unneeded global pollution if (!callbacks) { // we need to consider multiple engines in the same page if (!global.___eio) global.___eio = []; callbacks = global.___eio; } // callback identifier this.index = callbacks.length; // add callback to jsonp global var self = this; callbacks.push(function (msg) { self.onData(msg); }); // append to query string this.query.j = this.index; } /** * Inherits from Polling. */ util.inherits(JSONPPolling, Polling); /* * JSONP only supports binary as base64 encoded strings */ JSONPPolling.prototype.supportsBinary = false; /** * Closes the socket * * @api private */ JSONPPolling.prototype.doClose = function () { if (this.script) { this.script.parentNode.removeChild(this.script); this.script = null; } if (this.form) { this.form.parentNode.removeChild(this.form); this.form = null; } Polling.prototype.doClose.call(this); }; /** * Starts a poll cycle. * * @api private */ JSONPPolling.prototype.doPoll = function () { var self = this; var script = document.createElement('script'); if (this.script) { this.script.parentNode.removeChild(this.script); this.script = null; } script.async = true; script.src = this.uri(); script.onerror = function(e){ self.onError('jsonp poll error',e); }; var insertAt = document.getElementsByTagName('script')[0]; insertAt.parentNode.insertBefore(script, insertAt); this.script = script; if (util.ua.gecko) { setTimeout(function () { var iframe = document.createElement('iframe'); document.body.appendChild(iframe); document.body.removeChild(iframe); }, 100); } }; /** * Writes with a hidden iframe. * * @param {String} data to send * @param {Function} called upon flush. * @api private */ JSONPPolling.prototype.doWrite = function (data, fn) { var self = this; if (!this.form) { var form = document.createElement('form'); var area = document.createElement('textarea'); var id = this.iframeId = 'eio_iframe_' + this.index; var iframe; form.className = 'socketio'; form.style.position = 'absolute'; form.style.top = '-1000px'; form.style.left = '-1000px'; form.target = id; form.method = 'POST'; form.setAttribute('accept-charset', 'utf-8'); area.name = 'd'; form.appendChild(area); document.body.appendChild(form); this.form = form; this.area = area; } this.form.action = this.uri(); function complete () { initIframe(); fn(); } function initIframe () { if (self.iframe) { try { self.form.removeChild(self.iframe); } catch (e) { self.onError('jsonp polling iframe removal error', e); } } try { // ie6 dynamic iframes with target="" support (thanks Chris Lambacher) var html = '<iframe src="javascript:0" name="'+ self.iframeId +'">'; iframe = document.createElement(html); } catch (e) { iframe = document.createElement('iframe'); iframe.name = self.iframeId; iframe.src = 'javascript:0'; } iframe.id = self.iframeId; self.form.appendChild(iframe); self.iframe = iframe; } initIframe(); // escape \n to prevent it from being converted into \r\n by some UAs this.area.value = data.replace(rNewline, '\\n'); try { this.form.submit(); } catch(e) {} if (this.iframe.attachEvent) { this.iframe.onreadystatechange = function(){ if (self.iframe.readyState == 'complete') { complete(); } }; } else { this.iframe.onload = complete; } }; },{"../util":22,"./polling":20}],19:[function(require,module,exports){ var global=typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {};/** * Module requirements. */ var XMLHttpRequest = require('xmlhttprequest'); var Polling = require('./polling'); var util = require('../util'); var Emitter = require('../emitter'); var debug = require('debug')('engine.io-client:polling-xhr'); /** * Module exports. */ module.exports = XHR; module.exports.Request = Request; /** * Obfuscated key for Blue Coat. */ var hasAttachEvent = global.document && global.document.attachEvent; /** * Empty function */ function empty(){} /** * XHR Polling constructor. * * @param {Object} opts * @api public */ function XHR(opts){ Polling.call(this, opts); if (global.location) { var isSSL = 'https:' == location.protocol; var port = location.port; // some user agents have empty `location.port` if (!port) { port = isSSL ? 443 : 80; } this.xd = opts.hostname != global.location.hostname || port != opts.port; } } /** * Inherits from Polling. */ util.inherits(XHR, Polling); /** * XHR supports binary */ XHR.prototype.supportsBinary = true; /** * Creates a request. * * @param {String} method * @api private */ XHR.prototype.request = function(opts){ opts = opts || {}; opts.uri = this.uri(); opts.xd = this.xd; opts.agent = this.agent || false; opts.supportsBinary = this.supportsBinary; return new Request(opts); }; /** * Sends data. * * @param {String} data to send. * @param {Function} called upon flush. * @api private */ XHR.prototype.doWrite = function(data, fn){ var isBinary = typeof data !== 'string' && data !== undefined; var req = this.request({ method: 'POST', data: data, isBinary: isBinary }); var self = this; req.on('success', fn); req.on('error', function(err){ self.onError('xhr post error', err); }); this.sendXhr = req; }; /** * Starts a poll cycle. * * @api private */ XHR.prototype.doPoll = function(){ debug('xhr poll'); var req = this.request(); var self = this; req.on('data', function(data){ self.onData(data); }); req.on('error', function(err){ self.onError('xhr poll error', err); }); this.pollXhr = req; }; /** * Request constructor * * @param {Object} options * @api public */ function Request(opts){ this.method = opts.method || 'GET'; this.uri = opts.uri; this.xd = !!opts.xd; this.async = false !== opts.async; this.data = undefined != opts.data ? opts.data : null; this.agent = opts.agent; this.create(opts.isBinary, opts.supportsBinary); } /** * Mix in `Emitter`. */ Emitter(Request.prototype); /** * Creates the XHR object and sends the request. * * @api private */ Request.prototype.create = function(isBinary, supportsBinary){ var xhr = this.xhr = new XMLHttpRequest({ agent: this.agent, xdomain: this.xd }); var self = this; try { debug('xhr open %s: %s', this.method, this.uri); xhr.open(this.method, this.uri, this.async); if (supportsBinary) { // This has to be done after open because Firefox is stupid // http://stackoverflow.com/questions/13216903/get-binary-data-with-xmlhttprequest-in-a-firefox-extension xhr.responseType = 'arraybuffer'; } if ('POST' == this.method) { try { if (isBinary) { xhr.setRequestHeader('Content-type', 'application/octet-stream'); } else { xhr.setRequestHeader('Content-type', 'text/plain;charset=UTF-8'); } } catch (e) {} } // ie6 check if ('withCredentials' in xhr) { xhr.withCredentials = true; } xhr.onreadystatechange = function(){ var data; try { if (4 != xhr.readyState) return; if (200 == xhr.status || 1223 == xhr.status) { var contentType = xhr.getResponseHeader('Content-Type'); if (contentType === 'application/octet-stream') { data = xhr.response; } else { if (!supportsBinary) { data = xhr.responseText; } else { data = 'ok'; } } } else { // make sure the `error` event handler that's user-set // does not throw in the same tick and gets caught here setTimeout(function(){ self.onError(xhr.status); }, 0); } } catch (e) { self.onError(e); } if (null != data) { self.onData(data); } }; debug('xhr data %s', this.data); xhr.send(this.data); } catch (e) { // Need to defer since .create() is called directly fhrom the constructor // and thus the 'error' event can only be only bound *after* this exception // occurs. Therefore, also, we cannot throw here at all. setTimeout(function() { self.onError(e); }, 0); return; } if (hasAttachEvent) { this.index = Request.requestsCount++; Request.requests[this.index] = this; } }; /** * Called upon successful response. * * @api private */ Request.prototype.onSuccess = function(){ this.emit('success'); this.cleanup(); }; /** * Called if we have data. * * @api private */ Request.prototype.onData = function(data){ this.emit('data', data); this.onSuccess(); }; /** * Called upon error. * * @api private */ Request.prototype.onError = function(err){ this.emit('error', err); this.cleanup(); }; /** * Cleans up house. * * @api private */ Request.prototype.cleanup = function(){ if ('undefined' == typeof this.xhr ) { return; } // xmlhttprequest this.xhr.onreadystatechange = empty; try { this.xhr.abort(); } catch(e) {} if (hasAttachEvent) { delete Request.requests[this.index]; } this.xhr = null; }; /** * Aborts the request. * * @api public */ Request.prototype.abort = function(){ this.cleanup(); }; /** * Cleanup is needed for old versions of IE * that leak memory unless we abort request before unload. */ if (hasAttachEvent) { Request.requestsCount = 0; Request.requests = {}; global.attachEvent('onunload', unloadHandler); } function unloadHandler() { for (var i in Request.requests) { if (Request.requests.hasOwnProperty(i)) { Request.requests[i].abort(); } } } },{"../emitter":12,"../util":22,"./polling":20,"debug":9,"xmlhttprequest":23}],20:[function(require,module,exports){ var global=typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {};/** * Module dependencies. */ var Transport = require('../transport'); var util = require('../util'); var parser = require('engine.io-parser'); var debug = require('debug')('engine.io-client:polling'); /** * Module exports. */ module.exports = Polling; /** * Is XHR2 supported? */ var hasXHR2 = (function() { var XMLHttpRequest = require('xmlhttprequest'); var xhr = new XMLHttpRequest({ agent: this.agent, xdomain: false }); return null != xhr.responseType; })(); /** * Polling interface. * * @param {Object} opts * @api private */ function Polling(opts){ var forceBase64 = (opts && opts.forceBase64); if (!hasXHR2 || forceBase64) { this.supportsBinary = false; } Transport.call(this, opts); } /** * Inherits from Transport. */ util.inherits(Polling, Transport); /** * Transport name. */ Polling.prototype.name = 'polling'; /** * Opens the socket (triggers polling). We write a PING message to determine * when the transport is open. * * @api private */ Polling.prototype.doOpen = function(){ this.poll(); }; /** * Pauses polling. * * @param {Function} callback upon buffers are flushed and transport is paused * @api private */ Polling.prototype.pause = function(onPause){ var pending = 0; var self = this; this.readyState = 'pausing'; function pause(){ debug('paused'); self.readyState = 'paused'; onPause(); } if (this.polling || !this.writable) { var total = 0; if (this.polling) { debug('we are currently polling - waiting to pause'); total++; this.once('pollComplete', function(){ debug('pre-pause polling complete'); --total || pause(); }); } if (!this.writable) { debug('we are currently writing - waiting to pause'); total++; this.once('drain', function(){ debug('pre-pause writing complete'); --total || pause(); }); } } else { pause(); } }; /** * Starts polling cycle. * * @api public */ Polling.prototype.poll = function(){ debug('polling'); this.polling = true; this.doPoll(); this.emit('poll'); }; /** * Overloads onData to detect payloads. * * @api private */ Polling.prototype.onData = function(data){ var self = this; debug('polling got data %s', data); var callback = function(packet, index, total) { // if its the first message we consider the transport open if ('opening' == self.readyState) { self.onOpen(); } // if its a close packet, we close the ongoing requests if ('close' == packet.type) { self.onClose(); return false; } // otherwise bypass onData and handle the message self.onPacket(packet); }; // decode payload parser.decodePayload(data, this.socket.binaryType, callback); // if an event did not trigger closing if ('closed' != this.readyState) { // if we got data we're not polling this.polling = false; this.emit('pollComplete'); if ('open' == this.readyState) { this.poll(); } else { debug('ignoring poll - transport state "%s"', this.readyState); } } }; /** * For polling, send a close packet. * * @api private */ Polling.prototype.doClose = function(){ var self = this; function close(){ debug('writing close packet'); self.write([{ type: 'close' }]); } if ('open' == this.readyState) { debug('transport open - closing'); close(); } else { // in case we're trying to close while // handshaking is in progress (GH-164) debug('transport not open - deferring close'); this.once('open', close); } }; /** * Writes a packets payload. * * @param {Array} data packets * @param {Function} drain callback * @api private */ Polling.prototype.write = function(packets){ var self = this; this.writable = false; var callbackfn = function() { self.writable = true; self.emit('drain'); }; var self = this; parser.encodePayload(packets, this.supportsBinary, function(data) { self.doWrite(data, callbackfn); }); }; /** * Generates uri for connection. * * @api private */ Polling.prototype.uri = function(){ var query = this.query || {}; var schema = this.secure ? 'https' : 'http'; var port = ''; // cache busting is forced for IE / android / iOS6 ಠ_ಠ if ('ActiveXObject' in global || util.ua.chromeframe || util.ua.android || util.ua.ios6 || this.timestampRequests) { if (false !== this.timestampRequests) { query[this.timestampParam] = +new Date; } } if (!this.supportsBinary && !query.sid) { query.b64 = 1; } query = util.qs(query); // avoid port if default for schema if (this.port && (('https' == schema && this.port != 443) || ('http' == schema && this.port != 80))) { port = ':' + this.port; } // prepend ? to query if (query.length) { query = '?' + query; } return schema + '://' + this.hostname + port + this.path + query; }; },{"../transport":15,"../util":22,"debug":9,"engine.io-parser":24,"xmlhttprequest":23}],21:[function(require,module,exports){ /** * Module dependencies. */ var Transport = require('../transport'); var parser = require('engine.io-parser'); var util = require('../util'); var debug = require('debug')('engine.io-client:websocket'); /** * `ws` exposes a WebSocket-compatible interface in * Node, or the `WebSocket` or `MozWebSocket` globals * in the browser. */ var WebSocket = require('ws'); /** * Module exports. */ module.exports = WS; /** * WebSocket transport constructor. * * @api {Object} connection options * @api public */ function WS(opts){ var forceBase64 = (opts && opts.forceBase64); if (forceBase64) { this.supportsBinary = false; } Transport.call(this, opts); } /** * Inherits from Transport. */ util.inherits(WS, Transport); /** * Transport name. * * @api public */ WS.prototype.name = 'websocket'; /* * WebSockets support binary */ WS.prototype.supportsBinary = true; /** * Opens socket. * * @api private */ WS.prototype.doOpen = function(){ if (!this.check()) { // let probe timeout return; } var self = this; var uri = this.uri(); var protocols = void(0); var opts = { agent: this.agent }; this.ws = new WebSocket(uri, protocols, opts); if (this.ws.binaryType === undefined) { this.supportsBinary = false; } this.ws.binaryType = 'arraybuffer'; this.addEventListeners(); }; /** * Adds event listeners to the socket * * @api private */ WS.prototype.addEventListeners = function(){ var self = this; this.ws.onopen = function(){ self.onOpen(); }; this.ws.onclose = function(){ self.onClose(); }; this.ws.onmessage = function(ev){ self.onData(ev.data); }; this.ws.onerror = function(e){ self.onError('websocket error', e); }; }; /** * Override `onData` to use a timer on iOS. * See: https://gist.github.com/mloughran/2052006 * * @api private */ if ('undefined' != typeof navigator && /iPad|iPhone|iPod/i.test(navigator.userAgent)) { WS.prototype.onData = function(data){ var self = this; setTimeout(function(){ Transport.prototype.onData.call(self, data); }, 0); }; } /** * Writes data to socket. * * @param {Array} array of packets. * @api private */ WS.prototype.write = function(packets){ var self = this; this.writable = false; // encodePacket efficient as it uses WS framing // no need for encodePayload for (var i = 0, l = packets.length; i < l; i++) { parser.encodePacket(packets[i], this.supportsBinary, function(data) { self.ws.send(data); }); } function ondrain() { self.writable = true; self.emit('drain'); } // fake drain // defer to next tick to allow Socket to clear writeBuffer setTimeout(ondrain, 0); }; /** * Called upon close * * @api private */ WS.prototype.onClose = function(){ Transport.prototype.onClose.call(this); }; /** * Closes socket. * * @api private */ WS.prototype.doClose = function(){ if (typeof this.ws !== 'undefined') { this.ws.close(); } }; /** * Generates uri for connection. * * @api private */ WS.prototype.uri = function(){ var query = this.query || {}; var schema = this.secure ? 'wss' : 'ws'; var port = ''; // avoid port if default for schema if (this.port && (('wss' == schema && this.port != 443) || ('ws' == schema && this.port != 80))) { port = ':' + this.port; } // append timestamp to URI if (this.timestampRequests) { query[this.timestampParam] = +new Date; } // communicate binary support capabilities if (!this.supportsBinary) { query.b64 = 1; } query = util.qs(query); // prepend ? to query if (query.length) { query = '?' + query; } return schema + '://' + this.hostname + port + this.path + query; }; /** * Feature detection for WebSocket. * * @return {Boolean} whether this transport is available. * @api public */ WS.prototype.check = function(){ return !!WebSocket && !('__initialize' in WebSocket && this.name === WS.prototype.name); }; },{"../transport":15,"../util":22,"debug":9,"engine.io-parser":24,"ws":30}],22:[function(require,module,exports){ var global=typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}; /** * Status of page load. */ var pageLoaded = false; /** * Inheritance. * * @param {Function} ctor a * @param {Function} ctor b * @api private */ exports.inherits = function inherits (a, b) { function c () { } c.prototype = b.prototype; a.prototype = new c; }; /** * Object.keys */ exports.keys = Object.keys || function (obj) { var ret = []; var has = Object.prototype.hasOwnProperty; for (var i in obj) { if (has.call(obj, i)) { ret.push(i); } } return ret; }; /** * Adds an event. * * @api private */ exports.on = function (element, event, fn, capture) { if (element.attachEvent) { element.attachEvent('on' + event, fn); } else if (element.addEventListener) { element.addEventListener(event, fn, capture); } }; /** * Load utility. * * @api private */ exports.load = function (fn) { if (global.document && document.readyState === 'complete' || pageLoaded) { return fn(); } exports.on(global, 'load', fn, false); }; /** * Change the internal pageLoaded value. */ if ('undefined' != typeof window) { exports.load(function () { pageLoaded = true; }); } /** * UA / engines detection namespace. * * @namespace */ exports.ua = {}; /** * Detect webkit. * * @api private */ exports.ua.webkit = 'undefined' != typeof navigator && /webkit/i.test(navigator.userAgent); /** * Detect gecko. * * @api private */ exports.ua.gecko = 'undefined' != typeof navigator && /gecko/i.test(navigator.userAgent); /** * Detect android; */ exports.ua.android = 'undefined' != typeof navigator && /android/i.test(navigator.userAgent); /** * Detect iOS. */ exports.ua.ios = 'undefined' != typeof navigator && /^(iPad|iPhone|iPod)$/.test(navigator.platform); exports.ua.ios6 = exports.ua.ios && /OS 6_/.test(navigator.userAgent); /** * Detect Chrome Frame. */ exports.ua.chromeframe = Boolean(global.externalHost); /** * Compiles a querystring * * @param {Object} * @api private */ exports.qs = function (obj) { var str = ''; for (var i in obj) { if (obj.hasOwnProperty(i)) { if (str.length) str += '&'; str += encodeURIComponent(i) + '=' + encodeURIComponent(obj[i]); } } return str; }; /** * Parses a simple querystring. * * @param {String} qs * @api private */ exports.qsParse = function(qs){ var qry = {}; var pairs = qs.split('&'); for (var i = 0, l = pairs.length; i < l; i++) { var pair = pairs[i].split('='); qry[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]); } return qry; }; },{}],23:[function(require,module,exports){ // browser shim for xmlhttprequest module var hasCORS = require('has-cors'); module.exports = function(opts) { var xdomain = opts.xdomain; // XMLHttpRequest can be disabled on IE try { if ('undefined' != typeof XMLHttpRequest && (!xdomain || hasCORS)) { return new XMLHttpRequest(); } } catch (e) { } if (!xdomain) { try { return new ActiveXObject('Microsoft.XMLHTTP'); } catch(e) { } } } },{"has-cors":33}],24:[function(require,module,exports){ var global=typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {};/** * Module dependencies. */ var keys = require('./keys'); var sliceBuffer = require('arraybuffer.slice'); var base64encoder = require('base64-arraybuffer'); var after = require('after'); /** * Check if we are running an android browser. That requires us to use * ArrayBuffer with polling transports... * * http://ghinda.net/jpeg-blob-ajax-android/ */ var isAndroid = navigator.userAgent.match(/Android/i); /** * Current protocol version. */ exports.protocol = 2; /** * Packet types. */ var packets = exports.packets = { open: 0 // non-ws , close: 1 // non-ws , ping: 2 , pong: 3 , message: 4 , upgrade: 5 , noop: 6 }; var packetslist = keys(packets); /** * Premade error packet. */ var err = { type: 'error', data: 'parser error' }; /** * Create a blob api even for blob builder when vendor prefixes exist */ var Blob = require('blob'); /** * Encodes a packet. * * <packet type id> [ <data> ] * * Example: * * 5hello world * 3 * 4 * * Binary is encoded in an identical principle * * @api private */ exports.encodePacket = function (packet, supportsBinary, callback) { if (typeof supportsBinary == 'function') { callback = supportsBinary; supportsBinary = false; } var data = (packet.data === undefined) ? undefined : packet.data.buffer || packet.data; if (global.ArrayBuffer && data instanceof ArrayBuffer) { return encodeArrayBuffer(packet, supportsBinary, callback); } else if (Blob && data instanceof global.Blob) { return encodeBlob(packet, supportsBinary, callback); } // Sending data as a utf-8 string var encoded = packets[packet.type]; // data fragment is optional if (undefined !== packet.data) { encoded += String(packet.data); } return callback('' + encoded); }; /** * Encode packet helpers for binary types */ function encodeArrayBuffer(packet, supportsBinary, callback) { if (!supportsBinary) { return exports.encodeBase64Packet(packet, callback); } var data = packet.data; var contentArray = new Uint8Array(data); var resultBuffer = new Uint8Array(1 + data.byteLength); resultBuffer[0] = packets[packet.type]; for (var i = 0; i < contentArray.length; i++) { resultBuffer[i+1] = contentArray[i]; } return callback(resultBuffer.buffer); } function encodeBlobAsArrayBuffer(packet, supportsBinary, callback) { if (!supportsBinary) { return exports.encodeBase64Packet(packet, callback); } var fr = new FileReader(); fr.onload = function() { packet.data = fr.result; exports.encodePacket(packet, supportsBinary, callback); }; return fr.readAsArrayBuffer(packet.data); } function encodeBlob(packet, supportsBinary, callback) { if (!supportsBinary) { return exports.encodeBase64Packet(packet, callback); } if (isAndroid) { return encodeBlobAsArrayBuffer(packet, supportsBinary, callback); } var length = new Uint8Array(1); length[0] = packets[packet.type]; var blob = new Blob([length.buffer, packet.data]); return callback(blob); } /** * Encodes a packet with binary data in a base64 string * * @param {Object} packet, has `type` and `data` * @return {String} base64 encoded message */ exports.encodeBase64Packet = function(packet, callback) { var message = 'b' + exports.packets[packet.type]; if (Blob && packet.data instanceof Blob) { var fr = new FileReader(); fr.onload = function() { var b64 = fr.result.split(',')[1]; callback(message + b64); }; return fr.readAsDataURL(packet.data); } var b64data; try { b64data = String.fromCharCode.apply(null, new Uint8Array(packet.data)); } catch (e) { // iPhone Safari doesn't let you apply with typed arrays var typed = new Uint8Array(packet.data); var basic = new Array(typed.length); for (var i = 0; i < typed.length; i++) { basic[i] = typed[i]; } b64data = String.fromCharCode.apply(null, basic); } message += global.btoa(b64data); return callback(message); }; /** * Decodes a packet. Changes format to Blob if requested. * * @return {Object} with `type` and `data` (if any) * @api private */ exports.decodePacket = function (data, binaryType) { // String data if (typeof data == 'string' || data === undefined) { if (data.charAt(0) == 'b') { return exports.decodeBase64Packet(data.substr(1), binaryType); } var type = data.charAt(0); if (Number(type) != type || !packetslist[type]) { return err; } if (data.length > 1) { return { type: packetslist[type], data: data.substring(1) }; } else { return { type: packetslist[type] }; } } var asArray = new Uint8Array(data); var type = asArray[0]; var rest = sliceBuffer(data, 1); if (Blob && binaryType === 'blob') { rest = new Blob([rest]); } return { type: packetslist[type], data: rest }; }; /** * Decodes a packet encoded in a base64 string * * @param {String} base64 encoded message * @return {Object} with `type` and `data` (if any) */ exports.decodeBase64Packet = function(msg, binaryType) { var type = packetslist[msg.charAt(0)]; if (!global.ArrayBuffer) { return { type: type, data: { base64: true, data: msg.substr(1) } }; } var data = base64encoder.decode(msg.substr(1)); if (binaryType === 'blob' && Blob) { data = new Blob([data]); } return { type: type, data: data }; }; /** * Encodes multiple messages (payload). * * <length>:data * * Example: * * 11:hello world2:hi * * If any contents are binary, they will be encoded as base64 strings. Base64 * encoded strings are marked with a b before the length specifier * * @param {Array} packets * @api private */ exports.encodePayload = function (packets, supportsBinary, callback) { if (typeof supportsBinary == 'function') { callback = supportsBinary; supportsBinary = null; } if (supportsBinary) { if (Blob && !isAndroid) { return exports.encodePayloadAsBlob(packets, callback); } return exports.encodePayloadAsArrayBuffer(packets, callback); } if (!packets.length) { return callback('0:'); } function setLengthHeader(message) { return message.length + ':' + message; } function encodeOne(packet, doneCallback) { exports.encodePacket(packet, supportsBinary, function(message) { doneCallback(null, setLengthHeader(message)); }); } map(packets, encodeOne, function(err, results) { return callback(results.join('')); }); }; /** * Async array map using after */ function map(ary, each, done) { var result = new Array(ary.length); var next = after(ary.length, done); var eachWithIndex = function(i, el, cb) { each(el, function(error, msg) { result[i] = msg; cb(error, result); }); }; for (var i = 0; i < ary.length; i++) { eachWithIndex(i, ary[i], next); } } /* * Decodes data when a payload is maybe expected. Possible binary contents are * decoded from their base64 representation * * @param {String} data, callback method * @api public */ exports.decodePayload = function (data, binaryType, callback) { if (typeof data != 'string') { return exports.decodePayloadAsBinary(data, binaryType, callback); } if (typeof binaryType === 'function') { callback = binaryType; binaryType = null; } var packet; if (data == '') { // parser error - ignoring payload return callback(err, 0, 1); } var length = '' , n, msg; for (var i = 0, l = data.length; i < l; i++) { var chr = data.charAt(i); if (':' != chr) { length += chr; } else { if ('' == length || (length != (n = Number(length)))) { // parser error - ignoring payload return callback(err, 0, 1); } msg = data.substr(i + 1, n); if (length != msg.length) { // parser error - ignoring payload return callback(err, 0, 1); } if (msg.length) { packet = exports.decodePacket(msg, binaryType); if (err.type == packet.type && err.data == packet.data) { // parser error in individual packet - ignoring payload return callback(err, 0, 1); } var ret = callback(packet, i + n, l); if (false === ret) return; } // advance cursor i += n; length = ''; } } if (length != '') { // parser error - ignoring payload return callback(err, 0, 1); } }; /** * Encodes multiple messages (payload) as binary. * * <1 = binary, 0 = string><number from 0-9><number from 0-9>[...]<number * 255><data> * * Example: * 1 3 255 1 2 3, if the binary contents are interpreted as 8 bit integers * * @param {Array} packets * @return {ArrayBuffer} encoded payload * @api private */ exports.encodePayloadAsArrayBuffer = function(packets, callback) { if (!packets.length) { return callback(new ArrayBuffer(0)); } function encodeOne(packet, doneCallback) { exports.encodePacket(packet, true, function(data) { return doneCallback(null, data); }); } map(packets, encodeOne, function(err, encodedPackets) { var totalLength = encodedPackets.reduce(function(acc, p) { var len; if (typeof p === 'string'){ len = p.length; } else { len = p.byteLength; } return acc + len.toString().length + len + 2; // string/binary identifier + separator = 2 }, 0); var resultArray = new Uint8Array(totalLength); var bufferIndex = 0; encodedPackets.forEach(function(p) { var isString = typeof p === 'string'; var ab = p; if (isString) { var view = new Uint8Array(p.length); for (var i = 0; i < p.length; i++) { view[i] = p.charCodeAt(i); } ab = view.buffer; } if (isString) { // not true binary resultArray[bufferIndex++] = 0; } else { // true binary resultArray[bufferIndex++] = 1; } var lenStr = ab.byteLength.toString(); for (var i = 0; i < lenStr.length; i++) { resultArray[bufferIndex++] = parseInt(lenStr[i]); } resultArray[bufferIndex++] = 255; var view = new Uint8Array(ab); for (var i = 0; i < view.length; i++) { resultArray[bufferIndex++] = view[i]; } }); return callback(resultArray.buffer); }); }; /** * Encode as Blob */ exports.encodePayloadAsBlob = function(packets, callback) { function encodeOne(packet, doneCallback) { exports.encodePacket(packet, true, function(encoded) { var binaryIdentifier = new Uint8Array(1); binaryIdentifier[0] = 1; if (typeof encoded === 'string') { var view = new Uint8Array(encoded.length); for (var i = 0; i < encoded.length; i++) { view[i] = encoded.charCodeAt(i); } encoded = view.buffer; binaryIdentifier[0] = 0; } var len = (encoded instanceof ArrayBuffer) ? encoded.byteLength : encoded.size; var lenStr = len.toString(); var lengthAry = new Uint8Array(lenStr.length + 1); for (var i = 0; i < lenStr.length; i++) { lengthAry[i] = parseInt(lenStr[i]); } lengthAry[lenStr.length] = 255; if (Blob) { var blob = new Blob([binaryIdentifier.buffer, lengthAry.buffer, encoded]); doneCallback(null, blob); } }); } map(packets, encodeOne, function(err, results) { return callback(new Blob(results)); }); }; /* * Decodes data when a payload is maybe expected. Strings are decoded by * interpreting each byte as a key code for entries marked to start with 0. See * description of encodePayloadAsBinary * * @param {ArrayBuffer} data, callback method * @api public */ exports.decodePayloadAsBinary = function (data, binaryType, callback) { if (typeof binaryType === 'function') { callback = binaryType; binaryType = null; } var bufferTail = data; var buffers = []; while (bufferTail.byteLength > 0) { var tailArray = new Uint8Array(bufferTail); var isString = tailArray[0] === 0; var msgLength = ''; for (var i = 1; ; i++) { if (tailArray[i] == 255) break; msgLength += tailArray[i]; } bufferTail = sliceBuffer(bufferTail, 2 + msgLength.length); msgLength = parseInt(msgLength); var msg = sliceBuffer(bufferTail, 0, msgLength); if (isString) { try { msg = String.fromCharCode.apply(null, new Uint8Array(msg)); } catch (e) { // iPhone Safari doesn't let you apply to typed arrays var typed = new Uint8Array(msg); var basic = new Array(typed.length); for (var i = 0; i < typed.length; i++) { basic[i] = typed[i]; } msg = String.fromCharCode.apply(null, basic); } } buffers.push(msg); bufferTail = sliceBuffer(bufferTail, msgLength); } var total = buffers.length; buffers.forEach(function(buffer, i) { callback(exports.decodePacket(buffer, binaryType), i, total); }); }; },{"./keys":25,"after":26,"arraybuffer.slice":27,"base64-arraybuffer":7,"blob":28}],25:[function(require,module,exports){ /** * Gets the keys for an object. * * @return {Array} keys * @api private */ module.exports = Object.keys || function keys (obj){ var arr = []; var has = Object.prototype.hasOwnProperty; for (var i in obj) { if (has.call(obj, i)) { arr.push(i); } } return arr; }; },{}],26:[function(require,module,exports){ module.exports = after function after(count, callback, err_cb) { var bail = false err_cb = err_cb || noop proxy.count = count return (count === 0) ? callback() : proxy function proxy(err, result) { if (proxy.count <= 0) { throw new Error('after called too many times') } --proxy.count // after first error, rest are passed to err_cb if (err) { bail = true callback(err) // future error callbacks will go to error handler callback = err_cb } else if (proxy.count === 0 && !bail) { callback(null, result) } } } function noop() {} },{}],27:[function(require,module,exports){ /** * An abstraction for slicing an arraybuffer even when * ArrayBuffer.prototype.slice is not supported * * @api public */ module.exports = function(arraybuffer, start, end) { var bytes = arraybuffer.byteLength; start = start || 0; end = end || bytes; if (arraybuffer.slice) { return arraybuffer.slice(start, end); } if (start < 0) { start += bytes; } if (end < 0) { end += bytes; } if (end > bytes) { end = bytes; } if (start >= bytes || start >= end || bytes === 0) { return new ArrayBuffer(0); } var abv = new Uint8Array(arraybuffer); var result = new Uint8Array(end - start); for (var i = start, ii = 0; i < end; i++, ii++) { result[ii] = abv[i]; } return result.buffer; }; },{}],28:[function(require,module,exports){ var global=typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {};/** * Create a blob builder even when vendor prefixes exist */ var BlobBuilder = global.BlobBuilder || global.WebKitBlobBuilder || global.MSBlobBuilder || global.MozBlobBuilder; /** * Check if Blob constructor is supported */ var blobSupported = (function() { try { var b = new Blob(['hi']); return b.size == 2; } catch(e) { return false; } })(); /** * Check if BlobBuilder is supported */ var blobBuilderSupported = BlobBuilder && BlobBuilder.prototype.append && BlobBuilder.prototype.getBlob; function BlobBuilderConstructor(ary, options) { options = options || {}; var bb = new BlobBuilder(); for (var i = 0; i < ary.length; i++) { bb.append(ary[i]); } return (options.type) ? bb.getBlob(options.type) : bb.getBlob(); }; module.exports = (function() { if (blobSupported) { return global.Blob; } else if (blobBuilderSupported) { return BlobBuilderConstructor; } else { return undefined; } })(); },{}],29:[function(require,module,exports){ var global=typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {};/** * JSON parse. * * @see Based on jQuery#parseJSON (MIT) and JSON2 * @api private */ var rvalidchars = /^[\],:{}\s]*$/; var rvalidescape = /\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g; var rvalidtokens = /"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g; var rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g; var rtrimLeft = /^\s+/; var rtrimRight = /\s+$/; module.exports = function parsejson(data) { if ('string' != typeof data || !data) { return null; } data = data.replace(rtrimLeft, '').replace(rtrimRight, ''); // Attempt to parse using the native JSON parser first if (global.JSON && JSON.parse) { return JSON.parse(data); } if (rvalidchars.test(data.replace(rvalidescape, '@') .replace(rvalidtokens, ']') .replace(rvalidbraces, ''))) { return (new Function('return ' + data))(); } }; },{}],30:[function(require,module,exports){ /** * Module dependencies. */ var global = (function() { return this; })(); /** * WebSocket constructor. */ var WebSocket = global.WebSocket || global.MozWebSocket; /** * Module exports. */ module.exports = WebSocket ? ws : null; /** * WebSocket constructor. * * The third `opts` options object gets ignored in web browsers, since it's * non-standard, and throws a TypeError if passed to the constructor. * See: https://github.com/einaros/ws/issues/227 * * @param {String} uri * @param {Array} protocols (optional) * @param {Object) opts (optional) * @api public */ function ws(uri, protocols, opts) { var instance; if (protocols) { instance = new WebSocket(uri, protocols); } else { instance = new WebSocket(uri); } return instance; } if (WebSocket) ws.prototype = WebSocket.prototype; },{}],31:[function(require,module,exports){ var global=typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {};/* * Module requirements. */ var isArray = require('isarray'); /** * Module exports. */ module.exports = hasBinary; /** * Checks for binary data. * * Right now only Buffer and ArrayBuffer are supported.. * * @param {Object} anything * @api public */ function hasBinary(data) { function recursiveCheckForBinary(obj) { if (!obj) return false; if ( (global.Buffer && Buffer.isBuffer(obj)) || (global.ArrayBuffer && obj instanceof ArrayBuffer) || (global.Blob && obj instanceof Blob) || (global.File && obj instanceof File) ) { return true; } if (isArray(obj)) { for (var i = 0; i < obj.length; i++) { if (recursiveCheckForBinary(obj[i])) { return true; } } } else if (obj && 'object' == typeof obj) { for (var key in obj) { if (recursiveCheckForBinary(obj[key])) { return true; } } } return false; } return recursiveCheckForBinary(data); } },{"isarray":32}],32:[function(require,module,exports){ module.exports = Array.isArray || function (arr) { return Object.prototype.toString.call(arr) == '[object Array]'; }; },{}],33:[function(require,module,exports){ /** * Module dependencies. */ var global = require('global'); /** * Module exports. * * Logic borrowed from Modernizr: * * - https://github.com/Modernizr/Modernizr/blob/master/feature-detects/cors.js */ try { module.exports = 'XMLHttpRequest' in global && 'withCredentials' in new global.XMLHttpRequest(); } catch (err) { // if XMLHttp support is disabled in IE then it will throw // when trying to create module.exports = false; } },{"global":34}],34:[function(require,module,exports){ /** * Returns `this`. Execute this without a "context" (i.e. without it being * attached to an object of the left-hand side), and `this` points to the * "global" scope of the current JS execution. */ module.exports = (function () { return this; })(); },{}],35:[function(require,module,exports){ var indexOf = [].indexOf; module.exports = function(arr, obj){ if (indexOf) return arr.indexOf(obj); for (var i = 0; i < arr.length; ++i) { if (arr[i] === obj) return i; } return -1; }; },{}],36:[function(require,module,exports){ /** * HOP ref. */ var has = Object.prototype.hasOwnProperty; /** * Return own keys in `obj`. * * @param {Object} obj * @return {Array} * @api public */ exports.keys = Object.keys || function(obj){ var keys = []; for (var key in obj) { if (has.call(obj, key)) { keys.push(key); } } return keys; }; /** * Return own values in `obj`. * * @param {Object} obj * @return {Array} * @api public */ exports.values = function(obj){ var vals = []; for (var key in obj) { if (has.call(obj, key)) { vals.push(obj[key]); } } return vals; }; /** * Merge `b` into `a`. * * @param {Object} a * @param {Object} b * @return {Object} a * @api public */ exports.merge = function(a, b){ for (var key in b) { if (has.call(b, key)) { a[key] = b[key]; } } return a; }; /** * Return length of `obj`. * * @param {Object} obj * @return {Number} * @api public */ exports.length = function(obj){ return exports.keys(obj).length; }; /** * Check if `obj` is empty. * * @param {Object} obj * @return {Boolean} * @api public */ exports.isEmpty = function(obj){ return 0 == exports.length(obj); }; },{}],37:[function(require,module,exports){ /** * Parses an URI * * @author Steven Levithan <stevenlevithan.com> (MIT license) * @api private */ var re = /^(?:(?![^:@]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/; var parts = [ 'source', 'protocol', 'authority', 'userInfo', 'user', 'password', 'host' , 'port', 'relative', 'path', 'directory', 'file', 'query', 'anchor' ]; module.exports = function parseuri(str) { var m = re.exec(str || '') , uri = {} , i = 14; while (i--) { uri[parts[i]] = m[i] || ''; } return uri; }; },{}],38:[function(require,module,exports){ var global=typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {};/** * Modle requirements */ var isArray = require('isarray'); /** * Replaces every Buffer | ArrayBuffer in packet with a numbered placeholder. * Anything with blobs or files should be fed through removeBlobs before coming * here. * * @param {Object} packet - socket.io event packet * @return {Object} with deconstructed packet and list of buffers * @api public */ exports.deconstructPacket = function(packet) { var buffers = []; var packetData = packet.data; function deconstructBinPackRecursive(data) { if (!data) return data; if ((global.Buffer && Buffer.isBuffer(data)) || (global.ArrayBuffer && data instanceof ArrayBuffer)) { // replace binary var placeholder = {_placeholder: true, num: buffers.length}; buffers.push(data); return placeholder; } else if (isArray(data)) { var newData = new Array(data.length); for (var i = 0; i < data.length; i++) { newData[i] = deconstructBinPackRecursive(data[i]); } return newData; } else if ('object' == typeof data) { var newData = {}; for (var key in data) { newData[key] = deconstructBinPackRecursive(data[key]); } return newData; } return data; } var pack = packet; pack.data = deconstructBinPackRecursive(packetData); pack.attachments = buffers.length; // number of binary 'attachments' return {packet: pack, buffers: buffers}; } /** * Reconstructs a binary packet from its placeholder packet and buffers * * @param {Object} packet - event packet with placeholders * @param {Array} buffers - binary buffers to put in placeholder positions * @return {Object} reconstructed packet * @api public */ exports.reconstructPacket = function(packet, buffers) { var curPlaceHolder = 0; function reconstructBinPackRecursive(data) { if (data._placeholder) { var buf = buffers[data.num]; // appropriate buffer (should be natural order anyway) return buf; } else if (isArray(data)) { for (var i = 0; i < data.length; i++) { data[i] = reconstructBinPackRecursive(data[i]); } return data; } else if ('object' == typeof data) { for (var key in data) { data[key] = reconstructBinPackRecursive(data[key]); } return data; } return data; } packet.data = reconstructBinPackRecursive(packet.data); packet.attachments = undefined; // no longer useful return packet; } /** * Asynchronously removes Blobs or Files from data via * FileReader's readAsArrayBuffer method. Used before encoding * data as msgpack. Calls callback with the blobless data. * * @param {Object} data * @param {Function} callback * @api private */ exports.removeBlobs = function(data, callback) { function removeBlobsRecursive(obj, curKey, containingObject) { if (!obj) return obj; // convert any blob if ((global.Blob && obj instanceof Blob) || (global.File && obj instanceof File)) { pendingBlobs++; // async filereader var fileReader = new FileReader(); fileReader.onload = function() { // this.result == arraybuffer if (containingObject) { containingObject[curKey] = this.result; } else { bloblessData = this.result; } // if nothing pending its callback time if(! --pendingBlobs) { callback(bloblessData); } }; fileReader.readAsArrayBuffer(obj); // blob -> arraybuffer } if (isArray(obj)) { // handle array for (var i = 0; i < obj.length; i++) { removeBlobsRecursive(obj[i], i, obj); } } else if (obj && 'object' == typeof obj && !isBuf(obj)) { // and object for (var key in obj) { removeBlobsRecursive(obj[key], key, obj); } } } var pendingBlobs = 0; var bloblessData = data; removeBlobsRecursive(bloblessData); if (!pendingBlobs) { callback(bloblessData); } } /** * Returns true if obj is a buffer or an arraybuffer. * * @api private */ function isBuf(obj) { return (global.Buffer && Buffer.isBuffer(obj)) || (global.ArrayBuffer && obj instanceof ArrayBuffer); } },{"isarray":40}],39:[function(require,module,exports){ var global=typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}; /** * Module dependencies. */ var debug = require('debug')('socket.io-parser'); var json = require('json3'); var isArray = require('isarray'); var Emitter = require('emitter'); var binary = require('./binary'); /** * Protocol version. * * @api public */ exports.protocol = 3; /** * Packet types. * * @api public */ exports.types = [ 'CONNECT', 'DISCONNECT', 'EVENT', 'BINARY_EVENT', 'ACK', 'ERROR' ]; /** * Packet type `connect`. * * @api public */ exports.CONNECT = 0; /** * Packet type `disconnect`. * * @api public */ exports.DISCONNECT = 1; /** * Packet type `event`. * * @api public */ exports.EVENT = 2; /** * Packet type `ack`. * * @api public */ exports.ACK = 3; /** * Packet type `error`. * * @api public */ exports.ERROR = 4; /** * Packet type 'binary event' * * @api public */ exports.BINARY_EVENT = 5; exports.Encoder = Encoder /** * A socket.io Encoder instance * * @api public */ function Encoder() {}; /** * Encode a packet as a single string if non-binary, or as a * buffer sequence, depending on packet type. * * @param {Object} obj - packet object * @param {Function} callback - function to handle encodings (likely engine.write) * @return Calls callback with Array of encodings * @api public */ Encoder.prototype.encode = function(obj, callback){ debug('encoding packet %j', obj); if (exports.BINARY_EVENT == obj.type || exports.ACK == obj.type) { encodeAsBinary(obj, callback); } else { var encoding = encodeAsString(obj); callback([encoding]); } }; /** * Encode packet as string. * * @param {Object} packet * @return {String} encoded * @api private */ function encodeAsString(obj) { var str = ''; var nsp = false; // first is type str += obj.type; // attachments if we have them if (exports.BINARY_EVENT == obj.type || exports.ACK == obj.type) { str += obj.attachments; str += '-'; } // if we have a namespace other than `/` // we append it followed by a comma `,` if (obj.nsp && '/' != obj.nsp) { nsp = true; str += obj.nsp; } // immediately followed by the id if (null != obj.id) { if (nsp) { str += ','; nsp = false; } str += obj.id; } // json data if (null != obj.data) { if (nsp) str += ','; str += json.stringify(obj.data); } debug('encoded %j as %s', obj, str); return str; } /** * Encode packet as 'buffer sequence' by removing blobs, and * deconstructing packet into object with placeholders and * a list of buffers. * * @param {Object} packet * @return {Buffer} encoded * @api private */ function encodeAsBinary(obj, callback) { function writeEncoding(bloblessData) { var deconstruction = binary.deconstructPacket(bloblessData); var pack = encodeAsString(deconstruction.packet); var buffers = deconstruction.buffers; buffers.unshift(pack); // add packet info to beginning of data list callback(buffers); // write all the buffers } binary.removeBlobs(obj, writeEncoding); } exports.Decoder = Decoder /** * A socket.io Decoder instance * * @return {Object} decoder * @api public */ function Decoder() { this.reconstructor = null; } /** * Mix in `Emitter` with Decoder. */ Emitter(Decoder.prototype); /** * Decodes an ecoded packet string into packet JSON. * * @param {String} obj - encoded packet * @return {Object} packet * @api public */ Decoder.prototype.add = function(obj) { var packet; if ('string' == typeof obj) { packet = decodeString(obj); if (exports.BINARY_EVENT == packet.type || exports.ACK == packet.type) { // binary packet's json this.reconstructor = new BinaryReconstructor(packet); // no attachments, labeled binary but no binary data to follow if (this.reconstructor.reconPack.attachments == 0) { this.emit('decoded', packet); } } else { // non-binary full packet this.emit('decoded', packet); } } else if ((global.Buffer && Buffer.isBuffer(obj)) || (global.ArrayBuffer && obj instanceof ArrayBuffer) || obj.base64) { // raw binary data if (!this.reconstructor) { throw new Error('got binary data when not reconstructing a packet'); } else { packet = this.reconstructor.takeBinaryData(obj); if (packet) { // received final buffer this.reconstructor = null; this.emit('decoded', packet); } } } else { throw new Error('Unknown type: ' + obj); } } /** * Decode a packet String (JSON data) * * @param {String} str * @return {Object} packet * @api private */ function decodeString(str) { var p = {}; var i = 0; // look up type p.type = Number(str.charAt(0)); if (null == exports.types[p.type]) return error(); // look up attachments if type binary if (exports.BINARY_EVENT == p.type || exports.ACK == p.type) { p.attachments = ''; while (str.charAt(++i) != '-') { p.attachments += str.charAt(i); } p.attachments = Number(p.attachments); } // look up namespace (if any) if ('/' == str.charAt(i + 1)) { p.nsp = ''; while (++i) { var c = str.charAt(i); if (',' == c) break; p.nsp += c; if (i + 1 == str.length) break; } } else { p.nsp = '/'; } // look up id var next = str.charAt(i + 1); if ('' != next && Number(next) == next) { p.id = ''; while (++i) { var c = str.charAt(i); if (null == c || Number(c) != c) { --i; break; } p.id += str.charAt(i); if (i + 1 == str.length) break; } p.id = Number(p.id); } // look up json data if (str.charAt(++i)) { try { p.data = json.parse(str.substr(i)); } catch(e){ return error(); } } debug('decoded %s as %j', str, p); return p; }; /** * Deallocates a parser's resources * * @api public */ Decoder.prototype.destroy = function() { if (this.reconstructor) { this.reconstructor.finishedReconstruction(); } } /** * A manager of a binary event's 'buffer sequence'. Should * be constructed whenever a packet of type BINARY_EVENT is * decoded. * * @param {Object} packet * @return {BinaryReconstructor} initialized reconstructor * @api private */ function BinaryReconstructor(packet) { this.reconPack = packet; this.buffers = []; } /** * Method to be called when binary data received from connection * after a BINARY_EVENT packet. * * @param {Buffer | ArrayBuffer} binData - the raw binary data received * @return {null | Object} returns null if more binary data is expected or * a reconstructed packet object if all buffers have been received. * @api private */ BinaryReconstructor.prototype.takeBinaryData = function(binData) { this.buffers.push(binData); if (this.buffers.length == this.reconPack.attachments) { // done with buffer list var packet = binary.reconstructPacket(this.reconPack, this.buffers); this.finishedReconstruction(); return packet; } return null; } /** * Cleans up binary packet reconstruction variables. * * @api private */ BinaryReconstructor.prototype.finishedReconstruction = function() { this.reconPack = null; this.buffers = []; } function error(data){ return { type: exports.ERROR, data: 'parser error' }; } },{"./binary":38,"debug":9,"emitter":10,"isarray":40,"json3":41}],40:[function(require,module,exports){ module.exports=require(32) },{}],41:[function(require,module,exports){ /*! JSON v3.2.6 | http://bestiejs.github.io/json3 | Copyright 2012-2013, Kit Cambridge | http://kit.mit-license.org */ ;(function (window) { // Convenience aliases. var getClass = {}.toString, isProperty, forEach, undef; // Detect the `define` function exposed by asynchronous module loaders. The // strict `define` check is necessary for compatibility with `r.js`. var isLoader = typeof define === "function" && define.amd; // Detect native implementations. var nativeJSON = typeof JSON == "object" && JSON; // Set up the JSON 3 namespace, preferring the CommonJS `exports` object if // available. var JSON3 = typeof exports == "object" && exports && !exports.nodeType && exports; if (JSON3 && nativeJSON) { // Explicitly delegate to the native `stringify` and `parse` // implementations in CommonJS environments. JSON3.stringify = nativeJSON.stringify; JSON3.parse = nativeJSON.parse; } else { // Export for web browsers, JavaScript engines, and asynchronous module // loaders, using the global `JSON` object if available. JSON3 = window.JSON = nativeJSON || {}; } // Test the `Date#getUTC*` methods. Based on work by @Yaffle. var isExtended = new Date(-3509827334573292); try { // The `getUTCFullYear`, `Month`, and `Date` methods return nonsensical // results for certain dates in Opera >= 10.53. isExtended = isExtended.getUTCFullYear() == -109252 && isExtended.getUTCMonth() === 0 && isExtended.getUTCDate() === 1 && // Safari < 2.0.2 stores the internal millisecond time value correctly, // but clips the values returned by the date methods to the range of // signed 32-bit integers ([-2 ** 31, 2 ** 31 - 1]). isExtended.getUTCHours() == 10 && isExtended.getUTCMinutes() == 37 && isExtended.getUTCSeconds() == 6 && isExtended.getUTCMilliseconds() == 708; } catch (exception) {} // Internal: Determines whether the native `JSON.stringify` and `parse` // implementations are spec-compliant. Based on work by Ken Snyder. function has(name) { if (has[name] !== undef) { // Return cached feature test result. return has[name]; } var isSupported; if (name == "bug-string-char-index") { // IE <= 7 doesn't support accessing string characters using square // bracket notation. IE 8 only supports this for primitives. isSupported = "a"[0] != "a"; } else if (name == "json") { // Indicates whether both `JSON.stringify` and `JSON.parse` are // supported. isSupported = has("json-stringify") && has("json-parse"); } else { var value, serialized = '{"a":[1,true,false,null,"\\u0000\\b\\n\\f\\r\\t"]}'; // Test `JSON.stringify`. if (name == "json-stringify") { var stringify = JSON3.stringify, stringifySupported = typeof stringify == "function" && isExtended; if (stringifySupported) { // A test function object with a custom `toJSON` method. (value = function () { return 1; }).toJSON = value; try { stringifySupported = // Firefox 3.1b1 and b2 serialize string, number, and boolean // primitives as object literals. stringify(0) === "0" && // FF 3.1b1, b2, and JSON 2 serialize wrapped primitives as object // literals. stringify(new Number()) === "0" && stringify(new String()) == '""' && // FF 3.1b1, 2 throw an error if the value is `null`, `undefined`, or // does not define a canonical JSON representation (this applies to // objects with `toJSON` properties as well, *unless* they are nested // within an object or array). stringify(getClass) === undef && // IE 8 serializes `undefined` as `"undefined"`. Safari <= 5.1.7 and // FF 3.1b3 pass this test. stringify(undef) === undef && // Safari <= 5.1.7 and FF 3.1b3 throw `Error`s and `TypeError`s, // respectively, if the value is omitted entirely. stringify() === undef && // FF 3.1b1, 2 throw an error if the given value is not a number, // string, array, object, Boolean, or `null` literal. This applies to // objects with custom `toJSON` methods as well, unless they are nested // inside object or array literals. YUI 3.0.0b1 ignores custom `toJSON` // methods entirely. stringify(value) === "1" && stringify([value]) == "[1]" && // Prototype <= 1.6.1 serializes `[undefined]` as `"[]"` instead of // `"[null]"`. stringify([undef]) == "[null]" && // YUI 3.0.0b1 fails to serialize `null` literals. stringify(null) == "null" && // FF 3.1b1, 2 halts serialization if an array contains a function: // `[1, true, getClass, 1]` serializes as "[1,true,],". FF 3.1b3 // elides non-JSON values from objects and arrays, unless they // define custom `toJSON` methods. stringify([undef, getClass, null]) == "[null,null,null]" && // Simple serialization test. FF 3.1b1 uses Unicode escape sequences // where character escape codes are expected (e.g., `\b` => `\u0008`). stringify({ "a": [value, true, false, null, "\x00\b\n\f\r\t"] }) == serialized && // FF 3.1b1 and b2 ignore the `filter` and `width` arguments. stringify(null, value) === "1" && stringify([1, 2], null, 1) == "[\n 1,\n 2\n]" && // JSON 2, Prototype <= 1.7, and older WebKit builds incorrectly // serialize extended years. stringify(new Date(-8.64e15)) == '"-271821-04-20T00:00:00.000Z"' && // The milliseconds are optional in ES 5, but required in 5.1. stringify(new Date(8.64e15)) == '"+275760-09-13T00:00:00.000Z"' && // Firefox <= 11.0 incorrectly serializes years prior to 0 as negative // four-digit years instead of six-digit years. Credits: @Yaffle. stringify(new Date(-621987552e5)) == '"-000001-01-01T00:00:00.000Z"' && // Safari <= 5.1.5 and Opera >= 10.53 incorrectly serialize millisecond // values less than 1000. Credits: @Yaffle. stringify(new Date(-1)) == '"1969-12-31T23:59:59.999Z"'; } catch (exception) { stringifySupported = false; } } isSupported = stringifySupported; } // Test `JSON.parse`. if (name == "json-parse") { var parse = JSON3.parse; if (typeof parse == "function") { try { // FF 3.1b1, b2 will throw an exception if a bare literal is provided. // Conforming implementations should also coerce the initial argument to // a string prior to parsing. if (parse("0") === 0 && !parse(false)) { // Simple parsing test. value = parse(serialized); var parseSupported = value["a"].length == 5 && value["a"][0] === 1; if (parseSupported) { try { // Safari <= 5.1.2 and FF 3.1b1 allow unescaped tabs in strings. parseSupported = !parse('"\t"'); } catch (exception) {} if (parseSupported) { try { // FF 4.0 and 4.0.1 allow leading `+` signs and leading // decimal points. FF 4.0, 4.0.1, and IE 9-10 also allow // certain octal literals. parseSupported = parse("01") !== 1; } catch (exception) {} } if (parseSupported) { try { // FF 4.0, 4.0.1, and Rhino 1.7R3-R4 allow trailing decimal // points. These environments, along with FF 3.1b1 and 2, // also allow trailing commas in JSON objects and arrays. parseSupported = parse("1.") !== 1; } catch (exception) {} } } } } catch (exception) { parseSupported = false; } } isSupported = parseSupported; } } return has[name] = !!isSupported; } if (!has("json")) { // Common `[[Class]]` name aliases. var functionClass = "[object Function]"; var dateClass = "[object Date]"; var numberClass = "[object Number]"; var stringClass = "[object String]"; var arrayClass = "[object Array]"; var booleanClass = "[object Boolean]"; // Detect incomplete support for accessing string characters by index. var charIndexBuggy = has("bug-string-char-index"); // Define additional utility methods if the `Date` methods are buggy. if (!isExtended) { var floor = Math.floor; // A mapping between the months of the year and the number of days between // January 1st and the first of the respective month. var Months = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334]; // Internal: Calculates the number of days between the Unix epoch and the // first day of the given month. var getDay = function (year, month) { return Months[month] + 365 * (year - 1970) + floor((year - 1969 + (month = +(month > 1))) / 4) - floor((year - 1901 + month) / 100) + floor((year - 1601 + month) / 400); }; } // Internal: Determines if a property is a direct property of the given // object. Delegates to the native `Object#hasOwnProperty` method. if (!(isProperty = {}.hasOwnProperty)) { isProperty = function (property) { var members = {}, constructor; if ((members.__proto__ = null, members.__proto__ = { // The *proto* property cannot be set multiple times in recent // versions of Firefox and SeaMonkey. "toString": 1 }, members).toString != getClass) { // Safari <= 2.0.3 doesn't implement `Object#hasOwnProperty`, but // supports the mutable *proto* property. isProperty = function (property) { // Capture and break the object's prototype chain (see section 8.6.2 // of the ES 5.1 spec). The parenthesized expression prevents an // unsafe transformation by the Closure Compiler. var original = this.__proto__, result = property in (this.__proto__ = null, this); // Restore the original prototype chain. this.__proto__ = original; return result; }; } else { // Capture a reference to the top-level `Object` constructor. constructor = members.constructor; // Use the `constructor` property to simulate `Object#hasOwnProperty` in // other environments. isProperty = function (property) { var parent = (this.constructor || constructor).prototype; return property in this && !(property in parent && this[property] === parent[property]); }; } members = null; return isProperty.call(this, property); }; } // Internal: A set of primitive types used by `isHostType`. var PrimitiveTypes = { 'boolean': 1, 'number': 1, 'string': 1, 'undefined': 1 }; // Internal: Determines if the given object `property` value is a // non-primitive. var isHostType = function (object, property) { var type = typeof object[property]; return type == 'object' ? !!object[property] : !PrimitiveTypes[type]; }; // Internal: Normalizes the `for...in` iteration algorithm across // environments. Each enumerated key is yielded to a `callback` function. forEach = function (object, callback) { var size = 0, Properties, members, property; // Tests for bugs in the current environment's `for...in` algorithm. The // `valueOf` property inherits the non-enumerable flag from // `Object.prototype` in older versions of IE, Netscape, and Mozilla. (Properties = function () { this.valueOf = 0; }).prototype.valueOf = 0; // Iterate over a new instance of the `Properties` class. members = new Properties(); for (property in members) { // Ignore all properties inherited from `Object.prototype`. if (isProperty.call(members, property)) { size++; } } Properties = members = null; // Normalize the iteration algorithm. if (!size) { // A list of non-enumerable properties inherited from `Object.prototype`. members = ["valueOf", "toString", "toLocaleString", "propertyIsEnumerable", "isPrototypeOf", "hasOwnProperty", "constructor"]; // IE <= 8, Mozilla 1.0, and Netscape 6.2 ignore shadowed non-enumerable // properties. forEach = function (object, callback) { var isFunction = getClass.call(object) == functionClass, property, length; var hasProperty = !isFunction && typeof object.constructor != 'function' && isHostType(object, 'hasOwnProperty') ? object.hasOwnProperty : isProperty; for (property in object) { // Gecko <= 1.0 enumerates the `prototype` property of functions under // certain conditions; IE does not. if (!(isFunction && property == "prototype") && hasProperty.call(object, property)) { callback(property); } } // Manually invoke the callback for each non-enumerable property. for (length = members.length; property = members[--length]; hasProperty.call(object, property) && callback(property)); }; } else if (size == 2) { // Safari <= 2.0.4 enumerates shadowed properties twice. forEach = function (object, callback) { // Create a set of iterated properties. var members = {}, isFunction = getClass.call(object) == functionClass, property; for (property in object) { // Store each property name to prevent double enumeration. The // `prototype` property of functions is not enumerated due to cross- // environment inconsistencies. if (!(isFunction && property == "prototype") && !isProperty.call(members, property) && (members[property] = 1) && isProperty.call(object, property)) { callback(property); } } }; } else { // No bugs detected; use the standard `for...in` algorithm. forEach = function (object, callback) { var isFunction = getClass.call(object) == functionClass, property, isConstructor; for (property in object) { if (!(isFunction && property == "prototype") && isProperty.call(object, property) && !(isConstructor = property === "constructor")) { callback(property); } } // Manually invoke the callback for the `constructor` property due to // cross-environment inconsistencies. if (isConstructor || isProperty.call(object, (property = "constructor"))) { callback(property); } }; } return forEach(object, callback); }; // Public: Serializes a JavaScript `value` as a JSON string. The optional // `filter` argument may specify either a function that alters how object and // array members are serialized, or an array of strings and numbers that // indicates which properties should be serialized. The optional `width` // argument may be either a string or number that specifies the indentation // level of the output. if (!has("json-stringify")) { // Internal: A map of control characters and their escaped equivalents. var Escapes = { 92: "\\\\", 34: '\\"', 8: "\\b", 12: "\\f", 10: "\\n", 13: "\\r", 9: "\\t" }; // Internal: Converts `value` into a zero-padded string such that its // length is at least equal to `width`. The `width` must be <= 6. var leadingZeroes = "000000"; var toPaddedString = function (width, value) { // The `|| 0` expression is necessary to work around a bug in // Opera <= 7.54u2 where `0 == -0`, but `String(-0) !== "0"`. return (leadingZeroes + (value || 0)).slice(-width); }; // Internal: Double-quotes a string `value`, replacing all ASCII control // characters (characters with code unit values between 0 and 31) with // their escaped equivalents. This is an implementation of the // `Quote(value)` operation defined in ES 5.1 section 15.12.3. var unicodePrefix = "\\u00"; var quote = function (value) { var result = '"', index = 0, length = value.length, isLarge = length > 10 && charIndexBuggy, symbols; if (isLarge) { symbols = value.split(""); } for (; index < length; index++) { var charCode = value.charCodeAt(index); // If the character is a control character, append its Unicode or // shorthand escape sequence; otherwise, append the character as-is. switch (charCode) { case 8: case 9: case 10: case 12: case 13: case 34: case 92: result += Escapes[charCode]; break; default: if (charCode < 32) { result += unicodePrefix + toPaddedString(2, charCode.toString(16)); break; } result += isLarge ? symbols[index] : charIndexBuggy ? value.charAt(index) : value[index]; } } return result + '"'; }; // Internal: Recursively serializes an object. Implements the // `Str(key, holder)`, `JO(value)`, and `JA(value)` operations. var serialize = function (property, object, callback, properties, whitespace, indentation, stack) { var value, className, year, month, date, time, hours, minutes, seconds, milliseconds, results, element, index, length, prefix, result; try { // Necessary for host object support. value = object[property]; } catch (exception) {} if (typeof value == "object" && value) { className = getClass.call(value); if (className == dateClass && !isProperty.call(value, "toJSON")) { if (value > -1 / 0 && value < 1 / 0) { // Dates are serialized according to the `Date#toJSON` method // specified in ES 5.1 section 15.9.5.44. See section 15.9.1.15 // for the ISO 8601 date time string format. if (getDay) { // Manually compute the year, month, date, hours, minutes, // seconds, and milliseconds if the `getUTC*` methods are // buggy. Adapted from @Yaffle's `date-shim` project. date = floor(value / 864e5); for (year = floor(date / 365.2425) + 1970 - 1; getDay(year + 1, 0) <= date; year++); for (month = floor((date - getDay(year, 0)) / 30.42); getDay(year, month + 1) <= date; month++); date = 1 + date - getDay(year, month); // The `time` value specifies the time within the day (see ES // 5.1 section 15.9.1.2). The formula `(A % B + B) % B` is used // to compute `A modulo B`, as the `%` operator does not // correspond to the `modulo` operation for negative numbers. time = (value % 864e5 + 864e5) % 864e5; // The hours, minutes, seconds, and milliseconds are obtained by // decomposing the time within the day. See section 15.9.1.10. hours = floor(time / 36e5) % 24; minutes = floor(time / 6e4) % 60; seconds = floor(time / 1e3) % 60; milliseconds = time % 1e3; } else { year = value.getUTCFullYear(); month = value.getUTCMonth(); date = value.getUTCDate(); hours = value.getUTCHours(); minutes = value.getUTCMinutes(); seconds = value.getUTCSeconds(); milliseconds = value.getUTCMilliseconds(); } // Serialize extended years correctly. value = (year <= 0 || year >= 1e4 ? (year < 0 ? "-" : "+") + toPaddedString(6, year < 0 ? -year : year) : toPaddedString(4, year)) + "-" + toPaddedString(2, month + 1) + "-" + toPaddedString(2, date) + // Months, dates, hours, minutes, and seconds should have two // digits; milliseconds should have three. "T" + toPaddedString(2, hours) + ":" + toPaddedString(2, minutes) + ":" + toPaddedString(2, seconds) + // Milliseconds are optional in ES 5.0, but required in 5.1. "." + toPaddedString(3, milliseconds) + "Z"; } else { value = null; } } else if (typeof value.toJSON == "function" && ((className != numberClass && className != stringClass && className != arrayClass) || isProperty.call(value, "toJSON"))) { // Prototype <= 1.6.1 adds non-standard `toJSON` methods to the // `Number`, `String`, `Date`, and `Array` prototypes. JSON 3 // ignores all `toJSON` methods on these objects unless they are // defined directly on an instance. value = value.toJSON(property); } } if (callback) { // If a replacement function was provided, call it to obtain the value // for serialization. value = callback.call(object, property, value); } if (value === null) { return "null"; } className = getClass.call(value); if (className == booleanClass) { // Booleans are represented literally. return "" + value; } else if (className == numberClass) { // JSON numbers must be finite. `Infinity` and `NaN` are serialized as // `"null"`. return value > -1 / 0 && value < 1 / 0 ? "" + value : "null"; } else if (className == stringClass) { // Strings are double-quoted and escaped. return quote("" + value); } // Recursively serialize objects and arrays. if (typeof value == "object") { // Check for cyclic structures. This is a linear search; performance // is inversely proportional to the number of unique nested objects. for (length = stack.length; length--;) { if (stack[length] === value) { // Cyclic structures cannot be serialized by `JSON.stringify`. throw TypeError(); } } // Add the object to the stack of traversed objects. stack.push(value); results = []; // Save the current indentation level and indent one additional level. prefix = indentation; indentation += whitespace; if (className == arrayClass) { // Recursively serialize array elements. for (index = 0, length = value.length; index < length; index++) { element = serialize(index, value, callback, properties, whitespace, indentation, stack); results.push(element === undef ? "null" : element); } result = results.length ? (whitespace ? "[\n" + indentation + results.join(",\n" + indentation) + "\n" + prefix + "]" : ("[" + results.join(",") + "]")) : "[]"; } else { // Recursively serialize object members. Members are selected from // either a user-specified list of property names, or the object // itself. forEach(properties || value, function (property) { var element = serialize(property, value, callback, properties, whitespace, indentation, stack); if (element !== undef) { // According to ES 5.1 section 15.12.3: "If `gap` {whitespace} // is not the empty string, let `member` {quote(property) + ":"} // be the concatenation of `member` and the `space` character." // The "`space` character" refers to the literal space // character, not the `space` {width} argument provided to // `JSON.stringify`. results.push(quote(property) + ":" + (whitespace ? " " : "") + element); } }); result = results.length ? (whitespace ? "{\n" + indentation + results.join(",\n" + indentation) + "\n" + prefix + "}" : ("{" + results.join(",") + "}")) : "{}"; } // Remove the object from the traversed object stack. stack.pop(); return result; } }; // Public: `JSON.stringify`. See ES 5.1 section 15.12.3. JSON3.stringify = function (source, filter, width) { var whitespace, callback, properties, className; if (typeof filter == "function" || typeof filter == "object" && filter) { if ((className = getClass.call(filter)) == functionClass) { callback = filter; } else if (className == arrayClass) { // Convert the property names array into a makeshift set. properties = {}; for (var index = 0, length = filter.length, value; index < length; value = filter[index++], ((className = getClass.call(value)), className == stringClass || className == numberClass) && (properties[value] = 1)); } } if (width) { if ((className = getClass.call(width)) == numberClass) { // Convert the `width` to an integer and create a string containing // `width` number of space characters. if ((width -= width % 1) > 0) { for (whitespace = "", width > 10 && (width = 10); whitespace.length < width; whitespace += " "); } } else if (className == stringClass) { whitespace = width.length <= 10 ? width : width.slice(0, 10); } } // Opera <= 7.54u2 discards the values associated with empty string keys // (`""`) only if they are used directly within an object member list // (e.g., `!("" in { "": 1})`). return serialize("", (value = {}, value[""] = source, value), callback, properties, whitespace, "", []); }; } // Public: Parses a JSON source string. if (!has("json-parse")) { var fromCharCode = String.fromCharCode; // Internal: A map of escaped control characters and their unescaped // equivalents. var Unescapes = { 92: "\\", 34: '"', 47: "/", 98: "\b", 116: "\t", 110: "\n", 102: "\f", 114: "\r" }; // Internal: Stores the parser state. var Index, Source; // Internal: Resets the parser state and throws a `SyntaxError`. var abort = function() { Index = Source = null; throw SyntaxError(); }; // Internal: Returns the next token, or `"$"` if the parser has reached // the end of the source string. A token may be a string, number, `null` // literal, or Boolean literal. var lex = function () { var source = Source, length = source.length, value, begin, position, isSigned, charCode; while (Index < length) { charCode = source.charCodeAt(Index); switch (charCode) { case 9: case 10: case 13: case 32: // Skip whitespace tokens, including tabs, carriage returns, line // feeds, and space characters. Index++; break; case 123: case 125: case 91: case 93: case 58: case 44: // Parse a punctuator token (`{`, `}`, `[`, `]`, `:`, or `,`) at // the current position. value = charIndexBuggy ? source.charAt(Index) : source[Index]; Index++; return value; case 34: // `"` delimits a JSON string; advance to the next character and // begin parsing the string. String tokens are prefixed with the // sentinel `@` character to distinguish them from punctuators and // end-of-string tokens. for (value = "@", Index++; Index < length;) { charCode = source.charCodeAt(Index); if (charCode < 32) { // Unescaped ASCII control characters (those with a code unit // less than the space character) are not permitted. abort(); } else if (charCode == 92) { // A reverse solidus (`\`) marks the beginning of an escaped // control character (including `"`, `\`, and `/`) or Unicode // escape sequence. charCode = source.charCodeAt(++Index); switch (charCode) { case 92: case 34: case 47: case 98: case 116: case 110: case 102: case 114: // Revive escaped control characters. value += Unescapes[charCode]; Index++; break; case 117: // `\u` marks the beginning of a Unicode escape sequence. // Advance to the first character and validate the // four-digit code point. begin = ++Index; for (position = Index + 4; Index < position; Index++) { charCode = source.charCodeAt(Index); // A valid sequence comprises four hexdigits (case- // insensitive) that form a single hexadecimal value. if (!(charCode >= 48 && charCode <= 57 || charCode >= 97 && charCode <= 102 || charCode >= 65 && charCode <= 70)) { // Invalid Unicode escape sequence. abort(); } } // Revive the escaped character. value += fromCharCode("0x" + source.slice(begin, Index)); break; default: // Invalid escape sequence. abort(); } } else { if (charCode == 34) { // An unescaped double-quote character marks the end of the // string. break; } charCode = source.charCodeAt(Index); begin = Index; // Optimize for the common case where a string is valid. while (charCode >= 32 && charCode != 92 && charCode != 34) { charCode = source.charCodeAt(++Index); } // Append the string as-is. value += source.slice(begin, Index); } } if (source.charCodeAt(Index) == 34) { // Advance to the next character and return the revived string. Index++; return value; } // Unterminated string. abort(); default: // Parse numbers and literals. begin = Index; // Advance past the negative sign, if one is specified. if (charCode == 45) { isSigned = true; charCode = source.charCodeAt(++Index); } // Parse an integer or floating-point value. if (charCode >= 48 && charCode <= 57) { // Leading zeroes are interpreted as octal literals. if (charCode == 48 && ((charCode = source.charCodeAt(Index + 1)), charCode >= 48 && charCode <= 57)) { // Illegal octal literal. abort(); } isSigned = false; // Parse the integer component. for (; Index < length && ((charCode = source.charCodeAt(Index)), charCode >= 48 && charCode <= 57); Index++); // Floats cannot contain a leading decimal point; however, this // case is already accounted for by the parser. if (source.charCodeAt(Index) == 46) { position = ++Index; // Parse the decimal component. for (; position < length && ((charCode = source.charCodeAt(position)), charCode >= 48 && charCode <= 57); position++); if (position == Index) { // Illegal trailing decimal. abort(); } Index = position; } // Parse exponents. The `e` denoting the exponent is // case-insensitive. charCode = source.charCodeAt(Index); if (charCode == 101 || charCode == 69) { charCode = source.charCodeAt(++Index); // Skip past the sign following the exponent, if one is // specified. if (charCode == 43 || charCode == 45) { Index++; } // Parse the exponential component. for (position = Index; position < length && ((charCode = source.charCodeAt(position)), charCode >= 48 && charCode <= 57); position++); if (position == Index) { // Illegal empty exponent. abort(); } Index = position; } // Coerce the parsed value to a JavaScript number. return +source.slice(begin, Index); } // A negative sign may only precede numbers. if (isSigned) { abort(); } // `true`, `false`, and `null` literals. if (source.slice(Index, Index + 4) == "true") { Index += 4; return true; } else if (source.slice(Index, Index + 5) == "false") { Index += 5; return false; } else if (source.slice(Index, Index + 4) == "null") { Index += 4; return null; } // Unrecognized token. abort(); } } // Return the sentinel `$` character if the parser has reached the end // of the source string. return "$"; }; // Internal: Parses a JSON `value` token. var get = function (value) { var results, hasMembers; if (value == "$") { // Unexpected end of input. abort(); } if (typeof value == "string") { if ((charIndexBuggy ? value.charAt(0) : value[0]) == "@") { // Remove the sentinel `@` character. return value.slice(1); } // Parse object and array literals. if (value == "[") { // Parses a JSON array, returning a new JavaScript array. results = []; for (;; hasMembers || (hasMembers = true)) { value = lex(); // A closing square bracket marks the end of the array literal. if (value == "]") { break; } // If the array literal contains elements, the current token // should be a comma separating the previous element from the // next. if (hasMembers) { if (value == ",") { value = lex(); if (value == "]") { // Unexpected trailing `,` in array literal. abort(); } } else { // A `,` must separate each array element. abort(); } } // Elisions and leading commas are not permitted. if (value == ",") { abort(); } results.push(get(value)); } return results; } else if (value == "{") { // Parses a JSON object, returning a new JavaScript object. results = {}; for (;; hasMembers || (hasMembers = true)) { value = lex(); // A closing curly brace marks the end of the object literal. if (value == "}") { break; } // If the object literal contains members, the current token // should be a comma separator. if (hasMembers) { if (value == ",") { value = lex(); if (value == "}") { // Unexpected trailing `,` in object literal. abort(); } } else { // A `,` must separate each object member. abort(); } } // Leading commas are not permitted, object property names must be // double-quoted strings, and a `:` must separate each property // name and value. if (value == "," || typeof value != "string" || (charIndexBuggy ? value.charAt(0) : value[0]) != "@" || lex() != ":") { abort(); } results[value.slice(1)] = get(lex()); } return results; } // Unexpected token encountered. abort(); } return value; }; // Internal: Updates a traversed object member. var update = function(source, property, callback) { var element = walk(source, property, callback); if (element === undef) { delete source[property]; } else { source[property] = element; } }; // Internal: Recursively traverses a parsed JSON object, invoking the // `callback` function for each value. This is an implementation of the // `Walk(holder, name)` operation defined in ES 5.1 section 15.12.2. var walk = function (source, property, callback) { var value = source[property], length; if (typeof value == "object" && value) { // `forEach` can't be used to traverse an array in Opera <= 8.54 // because its `Object#hasOwnProperty` implementation returns `false` // for array indices (e.g., `![1, 2, 3].hasOwnProperty("0")`). if (getClass.call(value) == arrayClass) { for (length = value.length; length--;) { update(value, length, callback); } } else { forEach(value, function (property) { update(value, property, callback); }); } } return callback.call(source, property, value); }; // Public: `JSON.parse`. See ES 5.1 section 15.12.2. JSON3.parse = function (source, callback) { var result, value; Index = 0; Source = "" + source; result = get(lex()); // If a JSON string contains multiple tokens, it is invalid. if (lex() != "$") { abort(); } // Reset the parser state. Index = Source = null; return callback && getClass.call(callback) == functionClass ? walk((value = {}, value[""] = result, value), "", callback) : result; }; } } // Export for asynchronous module loaders. if (isLoader) { define(function () { return JSON3; }); } }(this)); },{}],42:[function(require,module,exports){ module.exports = toArray function toArray(list, index) { var array = [] index = index || 0 for (var i = index || 0; i < list.length; i++) { array[i - index] = list[i] } return array } },{}]},{},[1]) (1) }); ;
/* * /MathJax/jax/output/HTML-CSS/fonts/STIX/General/Regular/ij.js * * Copyright (c) 2009-2014 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.Hub.Insert(MathJax.OutputJax["HTML-CSS"].FONTDATA.FONTS.STIXGeneral,{120484:[441,11,278,47,235],120485:[441,207,278,-124,246]});MathJax.Ajax.loadComplete(MathJax.OutputJax["HTML-CSS"].fontDir+"/General/Regular/ij.js");
/* * Translated default messages for the jQuery validation plugin in lithuanian. * Locale: LT */ jQuery.extend(jQuery.validator.messages, { required: "Šis laukas yra privalomas.", remote: "Prašau pataisyti šį lauką.", email: "Prašau įvesti teisingą elektroninio pašto adresą.", url: "Prašau įvesti teisingą URL.", date: "Prašau įvesti teisingą datą.", dateISO: "Prašau įvesti teisingą datą (ISO).", number: "Prašau įvesti teisingą skaičių.", digits: "Prašau naudoti tik skaitmenis.", creditcard: "Prašau įvesti teisingą kreditinės kortelės numerį.", equalTo: "Prašau įvestį tą pačią reikšmę dar kartą.", accept: "Prašau įvesti reikšmę su teisingu plėtiniu.", maxlength: $.format("Prašau įvesti ne daugiau kaip {0} simbolių."), minlength: $.format("Prašau įvesti bent {0} simbolius."), rangelength: $.format("Prašau įvesti reikšmes, kurių ilgis nuo {0} iki {1} simbolių."), range: $.format("Prašau įvesti reikšmę intervale nuo {0} iki {1}."), max: $.format("Prašau įvesti reikšmę mažesnę arba lygią {0}."), min: $.format("Prašau įvesti reikšmę didesnę arba lygią {0}.") });
/* line-chart - v1.0.9 - 26 June 2014 https://github.com/n3-charts/line-chart Copyright (c) 2014 n3-charts */ var directive, m, mod, old_m; old_m = angular.module('n3-charts.linechart', ['n3charts.utils']); m = angular.module('n3-line-chart', ['n3charts.utils']); directive = function(name, conf) { old_m.directive(name, conf); return m.directive(name, conf); }; directive('linechart', [ 'n3utils', '$window', '$timeout', function(n3utils, $window, $timeout) { var link; link = function(scope, element, attrs, ctrl) { var dim, initialHandlers, isUpdatingOptions, promise, window_resize, _u; _u = n3utils; dim = _u.getDefaultMargins(); scope.updateDimensions = function(dimensions) { var bottom, left, right, top; top = _u.getPixelCssProp(element[0].parentElement, 'padding-top'); bottom = _u.getPixelCssProp(element[0].parentElement, 'padding-bottom'); left = _u.getPixelCssProp(element[0].parentElement, 'padding-left'); right = _u.getPixelCssProp(element[0].parentElement, 'padding-right'); dimensions.width = (element[0].parentElement.offsetWidth || 900) - left - right; return dimensions.height = (element[0].parentElement.offsetHeight || 500) - top - bottom; }; scope.update = function() { scope.updateDimensions(dim); return scope.redraw(dim); }; isUpdatingOptions = false; initialHandlers = { onSeriesVisibilityChange: function(_arg) { var index, newVisibility, series; series = _arg.series, index = _arg.index, newVisibility = _arg.newVisibility; isUpdatingOptions = true; scope.options.series[index].visible = newVisibility; scope.$apply(); return isUpdatingOptions = false; } }; scope.redraw = function(dimensions) { var axes, columnWidth, dataPerSeries, handlers, isThumbnail, options, svg; options = _u.sanitizeOptions(scope.options, attrs.mode); handlers = angular.extend(initialHandlers, _u.getTooltipHandlers(options)); dataPerSeries = _u.getDataPerSeries(scope.data, options); isThumbnail = attrs.mode === 'thumbnail'; _u.clean(element[0]); svg = _u.bootstrap(element[0], dimensions); axes = _u.createAxes(svg, dimensions, options.axes).andAddThemIf(isThumbnail); if (dataPerSeries.length) { _u.setScalesDomain(axes, scope.data, options.series, svg, options.axes); } if (isThumbnail) { _u.adjustMarginsForThumbnail(dimensions, axes); } else { _u.adjustMargins(dimensions, options, scope.data); } _u.createContent(svg, handlers); if (dataPerSeries.length) { columnWidth = _u.getBestColumnWidth(dimensions, dataPerSeries); _u.drawArea(svg, axes, dataPerSeries, options, handlers).drawColumns(svg, axes, dataPerSeries, columnWidth, handlers).drawLines(svg, axes, dataPerSeries, options, handlers); if (options.drawDots) { _u.drawDots(svg, axes, dataPerSeries, options, handlers); } } if (options.drawLegend) { _u.drawLegend(svg, options.series, dimensions, handlers); } if (options.tooltipMode === 'scrubber') { return _u.createGlass(svg, dimensions, handlers, axes, dataPerSeries); } else if (options.tooltipMode !== 'none') { return _u.addTooltips(svg, dimensions, options.axes); } }; promise = void 0; window_resize = function() { if (promise != null) { $timeout.cancel(promise); } return promise = $timeout(scope.update, 1); }; $window.addEventListener('resize', window_resize); scope.$watch('data', scope.update, true); return scope.$watch('options', function(v) { if (isUpdatingOptions) { return; } return scope.update(); }, true); }; return { replace: true, restrict: 'E', scope: { data: '=', options: '=' }, template: '<div></div>', link: link }; } ]); mod = angular.module('n3charts.utils', []); mod.factory('n3utils', [ '$window', '$log', '$rootScope', function($window, $log, $rootScope) { return { addPattern: function(svg, series) { var group; group = svg.select('defs').append('pattern').attr({ id: series.type + 'Pattern_' + series.index, patternUnits: "userSpaceOnUse", x: 0, y: 0, width: 60, height: 60 }).append('g').style({ 'fill': series.color, 'fill-opacity': 0.3 }); group.append('rect').style('fill-opacity', 0.3).attr('width', 60).attr('height', 60); group.append('path').attr('d', "M 10 0 l10 0 l -20 20 l 0 -10 z"); group.append('path').attr('d', "M40 0 l10 0 l-50 50 l0 -10 z"); group.append('path').attr('d', "M60 10 l0 10 l-40 40 l-10 0 z"); return group.append('path').attr('d', "M60 40 l0 10 l-10 10 l -10 0 z"); }, drawArea: function(svg, scales, data, options) { var areaSeries, drawers; areaSeries = data.filter(function(series) { return series.type === 'area'; }); areaSeries.forEach((function(series) { return this.addPattern(svg, series); }), this); drawers = { y: this.createLeftAreaDrawer(scales, options.lineMode, options.tension), y2: this.createRightAreaDrawer(scales, options.lineMode, options.tension) }; svg.select('.content').selectAll('.areaGroup').data(areaSeries).enter().append('g').attr('class', function(s) { return 'areaGroup ' + 'series_' + s.index; }).append('path').attr('class', 'area').style('fill', function(s) { if (s.striped !== true) { return s.color; } return "url(#areaPattern_" + s.index + ")"; }).style('opacity', function(s) { if (s.striped) { return '1'; } else { return '0.3'; } }).attr('d', function(d) { return drawers[d.axis](d.values); }); return this; }, createLeftAreaDrawer: function(scales, mode, tension) { return d3.svg.area().x(function(d) { return scales.xScale(d.x); }).y0(function(d) { return scales.yScale(0); }).y1(function(d) { return scales.yScale(d.value); }).interpolate(mode).tension(tension); }, createRightAreaDrawer: function(scales, mode, tension) { return d3.svg.area().x(function(d) { return scales.xScale(d.x); }).y0(function(d) { return scales.y2Scale(0); }).y1(function(d) { return scales.y2Scale(d.value); }).interpolate(mode).tension(tension); }, getBestColumnWidth: function(dimensions, seriesData) { var avWidth, gap, n, seriesCount; if (!(seriesData && seriesData.length !== 0)) { return 10; } n = seriesData[0].values.length + 2; seriesCount = seriesData.length; gap = 0; avWidth = dimensions.width - dimensions.left - dimensions.right; return parseInt(Math.max((avWidth - (n - 1) * gap) / (n * seriesCount), 5)); }, drawColumns: function(svg, axes, data, columnWidth, handlers) { var colGroup, x1; data = data.filter(function(s) { return s.type === 'column'; }); x1 = d3.scale.ordinal().domain(data.map(function(s) { return s.name + s.index; })).rangeBands([0, data.length * columnWidth], 0); colGroup = svg.select('.content').selectAll('.columnGroup').data(data).enter().append("g").attr('class', function(s) { return 'columnGroup ' + 'series_' + s.index; }).style('fill', function(s) { return s.color; }).style('fill-opacity', 0.8).attr('transform', function(s) { return "translate(" + (x1(s.name + s.index) - data.length * columnWidth / 2) + ",0)"; }).on('mouseover', function(series) { var target; target = d3.select(d3.event.target); return typeof handlers.onMouseOver === "function" ? handlers.onMouseOver(svg, { series: series, x: target.attr('x'), y: axes[series.axis + 'Scale'](target.datum().value), datum: target.datum() }) : void 0; }).on('mouseout', function(d) { d3.select(d3.event.target).attr('r', 2); return typeof handlers.onMouseOut === "function" ? handlers.onMouseOut(svg) : void 0; }); colGroup.selectAll("rect").data(function(d) { return d.values; }).enter().append("rect").style("fill-opacity", function(d) { if (d.value === 0) { return 0; } else { return 1; } }).attr({ width: columnWidth, x: function(d) { return axes.xScale(d.x); }, height: function(d) { if (d.value === 0) { return axes[d.axis + 'Scale'].range()[0]; } return Math.abs(axes[d.axis + 'Scale'](d.value) - axes[d.axis + 'Scale'](0)); }, y: function(d) { if (d.value === 0) { return 0; } else { return axes[d.axis + 'Scale'](Math.max(0, d.value)); } } }); return this; }, drawDots: function(svg, axes, data, options, handlers) { var dotGroup, _ref; dotGroup = svg.select('.content').selectAll('.dotGroup').data(data.filter(function(s) { var _ref; return (_ref = s.type) === 'line' || _ref === 'area'; })).enter().append('g'); dotGroup.attr({ "class": function(s) { return "dotGroup series_" + s.index; }, fill: function(s) { return s.color; } }).selectAll('.dot').data(function(d) { return d.values; }).enter().append('circle').attr({ 'class': 'dot', 'r': 2, 'cx': function(d) { return axes.xScale(d.x); }, 'cy': function(d) { return axes[d.axis + 'Scale'](d.value); } }).style({ 'stroke': 'white', 'stroke-width': '2px' }); if ((_ref = options.tooltipMode) === 'dots' || _ref === 'both' || _ref === 'scrubber') { dotGroup.on('mouseover', function(series) { var target; target = d3.select(d3.event.target); target.attr('r', 4); return typeof handlers.onMouseOver === "function" ? handlers.onMouseOver(svg, { series: series, x: target.attr('cx'), y: target.attr('cy'), datum: target.datum() }) : void 0; }).on('mouseout', function(d) { d3.select(d3.event.target).attr('r', 2); return typeof handlers.onMouseOut === "function" ? handlers.onMouseOut(svg) : void 0; }); } return this; }, computeLegendLayout: function(series, dimensions) { var fn, i, j, label, layout, leftSeries, rightLayout, rightSeries, w; fn = function(s) { return s.label || s.y; }; layout = [0]; leftSeries = series.filter(function(s) { return s.axis === 'y'; }); i = 1; while (i < leftSeries.length) { layout.push(this.getTextWidth(fn(leftSeries[i - 1])) + layout[i - 1] + 40); i++; } rightSeries = series.filter(function(s) { return s.axis === 'y2'; }); if (rightSeries.length === 0) { return layout; } w = dimensions.width - dimensions.right - dimensions.left; rightLayout = [w - this.getTextWidth(fn(rightSeries[rightSeries.length - 1]))]; j = rightSeries.length - 2; while (j >= 0) { label = fn(rightSeries[j]); rightLayout.push(w - this.getTextWidth(label) - (w - rightLayout[rightLayout.length - 1]) - 40); j--; } rightLayout.reverse(); return layout.concat(rightLayout); }, drawLegend: function(svg, series, dimensions, handlers) { var d, item, layout, legend, that; layout = this.computeLegendLayout(series, dimensions); that = this; legend = svg.append('g').attr('class', 'legend'); d = 16; svg.select('defs').append('svg:clipPath').attr('id', 'legend-clip').append('circle').attr('r', d / 2); item = legend.selectAll('.legendItem').data(series); item.enter().append('g').attr({ 'class': function(s, i) { return "legendItem series_" + i; }, 'transform': function(s, i) { return "translate(" + layout[i] + "," + (dimensions.height - 40) + ")"; }, 'opacity': function(s, i) { if (s.visible === false) { that.toggleSeries(svg, i); return '0.2'; } return '1'; } }); item.on('click', function(s, i) { var isNowVisible; isNowVisible = that.toggleSeries(svg, i); d3.select(this).attr('opacity', isNowVisible ? '1' : '0.2'); return typeof handlers.onSeriesVisibilityChange === "function" ? handlers.onSeriesVisibilityChange({ series: s, index: i, newVisibility: isNowVisible }) : void 0; }); item.append('circle').attr({ 'fill': function(s) { return s.color; }, 'stroke': function(s) { return s.color; }, 'stroke-width': '2px', 'r': d / 2 }); item.append('path').attr({ 'clip-path': 'url(#legend-clip)', 'fill-opacity': function(s) { var _ref; if ((_ref = s.type) === 'area' || _ref === 'column') { return '1'; } else { return '0'; } }, 'fill': 'white', 'stroke': 'white', 'stroke-width': '2px', 'd': function(s) { return that.getLegendItemPath(s, d, d); } }); item.append('circle').attr({ 'fill-opacity': 0, 'stroke': function(s) { return s.color; }, 'stroke-width': '2px', 'r': d / 2 }); item.append('text').attr({ 'class': function(d, i) { return "legendItem series_" + i; }, 'font-family': 'Courier', 'font-size': 10, 'transform': 'translate(13, 4)', 'text-rendering': 'geometric-precision' }).text(function(s) { return s.label || s.y; }); return this; }, getLegendItemPath: function(series, w, h) { var base_path, path; if (series.type === 'column') { path = 'M-' + w / 3 + ' -' + h / 8 + ' l0 ' + h + ' '; path += 'M0' + ' -' + h / 3 + ' l0 ' + h + ' '; path += 'M' + w / 3 + ' -' + h / 10 + ' l0 ' + h + ' '; return path; } base_path = 'M-' + w / 2 + ' 0' + h / 3 + ' l' + w / 3 + ' -' + h / 3 + ' l' + w / 3 + ' ' + h / 3 + ' l' + w / 3 + ' -' + 2 * h / 3; if (series.type === 'area') { base_path + ' l0 ' + h + ' l-' + w + ' 0z'; } return base_path; }, toggleSeries: function(svg, index) { var isVisible; isVisible = false; svg.select('.content').selectAll('.series_' + index).style('display', function(s) { if (d3.select(this).style('display') === 'none') { isVisible = true; return 'initial'; } else { isVisible = false; return 'none'; } }); return isVisible; }, drawLines: function(svg, scales, data, options, handlers) { var drawers, interpolateData, lineGroup, _ref; drawers = { y: this.createLeftLineDrawer(scales, options.lineMode, options.tension), y2: this.createRightLineDrawer(scales, options.lineMode, options.tension) }; lineGroup = svg.select('.content').selectAll('.lineGroup').data(data.filter(function(s) { var _ref; return (_ref = s.type) === 'line' || _ref === 'area'; })).enter().append('g'); lineGroup.style('stroke', function(s) { return s.color; }).attr('class', function(s) { return "lineGroup series_" + s.index; }).append('path').attr({ "class": 'line', d: function(d) { return drawers[d.axis](d.values); } }).style({ 'fill': 'none', 'stroke-width': function(s) { return s.thickness; }, 'stroke-dasharray': function(s) { if (s.lineMode === 'dashed') { return '10,3'; } return void 0; } }); if ((_ref = options.tooltipMode) === 'both' || _ref === 'lines') { interpolateData = function(series) { var datum, error, i, interpDatum, maxXPos, maxXValue, maxYPos, maxYValue, minXPos, minXValue, minYPos, minYValue, mousePos, target, valuesData, x, xPercentage, xVal, y, yPercentage, yVal, _i, _len; target = d3.select(d3.event.target); try { mousePos = d3.mouse(this); } catch (_error) { error = _error; mousePos = [0, 0]; } valuesData = target.datum().values; for (i = _i = 0, _len = valuesData.length; _i < _len; i = ++_i) { datum = valuesData[i]; x = scales.xScale(datum.x); y = scales.yScale(datum.value); if ((typeof minXPos === "undefined" || minXPos === null) || x < minXPos) { minXPos = x; minXValue = datum.x; } if ((typeof maxXPos === "undefined" || maxXPos === null) || x > maxXPos) { maxXPos = x; maxXValue = datum.x; } if ((typeof minYPos === "undefined" || minYPos === null) || y < minYPos) { minYPos = y; } if ((typeof maxYPos === "undefined" || maxYPos === null) || y > maxYPos) { maxYPos = y; } if ((typeof minYValue === "undefined" || minYValue === null) || datum.value < minYValue) { minYValue = datum.value; } if ((typeof maxYValue === "undefined" || maxYValue === null) || datum.value > maxYValue) { maxYValue = datum.value; } } xPercentage = (mousePos[0] - minXPos) / (maxXPos - minXPos); yPercentage = (mousePos[1] - minYPos) / (maxYPos - minYPos); xVal = Math.round(xPercentage * (maxXValue - minXValue) + minXValue); yVal = Math.round((1 - yPercentage) * (maxYValue - minYValue) + minYValue); interpDatum = { x: xVal, value: yVal }; return typeof handlers.onMouseOver === "function" ? handlers.onMouseOver(svg, { series: series, x: mousePos[0], y: mousePos[1], datum: interpDatum }) : void 0; }; lineGroup.on('mousemove', interpolateData).on('mouseout', function(d) { return typeof handlers.onMouseOut === "function" ? handlers.onMouseOut(svg) : void 0; }); } return this; }, createLeftLineDrawer: function(scales, mode, tension) { return d3.svg.line().x(function(d) { return scales.xScale(d.x); }).y(function(d) { return scales.yScale(d.value); }).interpolate(mode).tension(tension); }, createRightLineDrawer: function(scales, mode, tension) { return d3.svg.line().x(function(d) { return scales.xScale(d.x); }).y(function(d) { return scales.y2Scale(d.value); }).interpolate(mode).tension(tension); }, getPixelCssProp: function(element, propertyName) { var string; string = $window.getComputedStyle(element, null).getPropertyValue(propertyName); return +string.replace(/px$/, ''); }, getDefaultMargins: function() { return { top: 20, right: 50, bottom: 60, left: 50 }; }, clean: function(element) { return d3.select(element).on('keydown', null).on('keyup', null).select('svg').remove(); }, bootstrap: function(element, dimensions) { var height, svg, width; d3.select(element).classed('chart', true); width = dimensions.width; height = dimensions.height; svg = d3.select(element).append('svg').attr({ width: width, height: height }).append('g').attr('transform', 'translate(' + dimensions.left + ',' + dimensions.top + ')'); svg.append('defs').attr('class', 'patterns'); return svg; }, createContent: function(svg) { return svg.append('g').attr('class', 'content'); }, createGlass: function(svg, dimensions, handlers, axes, data) { var glass, items; glass = svg.append('g').attr({ 'class': 'glass-container', 'opacity': 0 }); items = glass.selectAll('.scrubberItem').data(data).enter().append('g').attr('class', function(s, i) { return "scrubberItem series_" + i; }); items.append('circle').attr({ 'class': function(s, i) { return "scrubberDot series_" + i; }, 'fill': 'white', 'stroke': function(s) { return s.color; }, 'stroke-width': '2px', 'r': 4 }); items.append('path').attr({ 'class': function(s, i) { return "scrubberPath series_" + i; }, 'y': '-7px', 'fill': function(s) { return s.color; } }); items.append('text').style('text-anchor', function(s) { if (s.axis === 'y') { return 'end'; } else { return 'start'; } }).attr({ 'class': function(d, i) { return "scrubberText series_" + i; }, 'height': '14px', 'font-family': 'Courier', 'font-size': 10, 'fill': 'white', 'transform': function(s) { if (s.axis === 'y') { return 'translate(-7, 3)'; } else { return 'translate(7, 3)'; } }, 'text-rendering': 'geometric-precision' }).text(function(s) { return s.label || s.y; }); return glass.append('rect').attr({ "class": 'glass', width: dimensions.width - dimensions.left - dimensions.right, height: dimensions.height - dimensions.top - dimensions.bottom }).style('fill', 'white').style('fill-opacity', 0.000001).on('mouseover', function() { return handlers.onChartHover(svg, d3.select(d3.event.target), axes, data); }); }, getDataPerSeries: function(data, options) { var axes, series, straightenedData; series = options.series; axes = options.axes; if (!(series && series.length && data && data.length)) { return []; } straightenedData = []; series.forEach(function(s) { var seriesData; seriesData = { xFormatter: axes.x.tooltipFormatter, index: straightenedData.length, name: s.y, values: [], striped: s.striped === true ? true : void 0, color: s.color, axis: s.axis || 'y', type: s.type, thickness: s.thickness, lineMode: s.lineMode }; data.filter(function(row) { return row[s.y] != null; }).forEach(function(row) { return seriesData.values.push({ x: row[options.axes.x.key], value: row[s.y], axis: s.axis || 'y' }); }); return straightenedData.push(seriesData); }); return straightenedData; }, resetMargins: function(dimensions) { var defaults; defaults = this.getDefaultMargins(); dimensions.left = defaults.left; dimensions.right = defaults.right; dimensions.top = defaults.top; return dimensions.bottom = defaults.bottom; }, adjustMargins: function(dimensions, options, data) { var leftSeries, leftWidest, rightSeries, rightWidest, series; this.resetMargins(dimensions); if (!(data && data.length)) { return; } series = options.series; leftSeries = series.filter(function(s) { return s.axis !== 'y2'; }); leftWidest = this.getWidestOrdinate(data, leftSeries); dimensions.left = this.getTextWidth('' + leftWidest) + 20; rightSeries = series.filter(function(s) { return s.axis === 'y2'; }); if (!rightSeries.length) { return; } rightWidest = this.getWidestOrdinate(data, rightSeries); return dimensions.right = this.getTextWidth('' + rightWidest) + 20; }, adjustMarginsForThumbnail: function(dimensions, axes) { dimensions.top = 1; dimensions.bottom = 2; dimensions.left = 0; return dimensions.right = 1; }, getTextWidth: function(text) { return parseInt(text.length * 5) + 10; }, getWidestOrdinate: function(data, series) { var widest; widest = ''; data.forEach(function(row) { return series.forEach(function(series) { if (row[series.y] == null) { return; } if (('' + row[series.y]).length > ('' + widest).length) { return widest = row[series.y]; } }); }); return widest; }, getDefaultOptions: function() { return { tooltipMode: 'dots', lineMode: 'linear', tension: 0.7, axes: { x: { type: 'linear', key: 'x' }, y: { type: 'linear' } }, series: [], drawLegend: true, drawDots: true }; }, sanitizeOptions: function(options, mode) { var _ref; if (options == null) { return this.getDefaultOptions(); } if (mode === 'thumbnail') { options.drawLegend = false; options.drawDots = false; options.tooltipMode = 'none'; } options.series = this.sanitizeSeriesOptions(options.series); options.axes = this.sanitizeAxes(options.axes, this.haveSecondYAxis(options.series)); options.lineMode || (options.lineMode = 'linear'); options.tension = /^\d+(\.\d+)?$/.test(options.tension) ? options.tension : 0.7; if ((_ref = options.tooltipMode) !== 'none' && _ref !== 'dots' && _ref !== 'lines' && _ref !== 'both' && _ref !== 'scrubber') { options.tooltipMode = 'dots'; } if (options.tooltipMode === 'scrubber') { options.drawLegend = true; } if (options.drawLegend !== false) { options.drawLegend = true; } if (options.drawDots !== false) { options.drawDots = true; } return options; }, sanitizeSeriesOptions: function(options) { var colors; if (options == null) { return []; } colors = d3.scale.category10(); options.forEach(function(s, i) { var _ref, _ref1, _ref2, _ref3; s.axis = ((_ref = s.axis) != null ? _ref.toLowerCase() : void 0) !== 'y2' ? 'y' : 'y2'; s.color || (s.color = colors(i)); s.type = (_ref1 = s.type) === 'line' || _ref1 === 'area' || _ref1 === 'column' ? s.type : "line"; if (s.type === 'column') { delete s.thickness; delete s.lineMode; } else if (!/^\d+px$/.test(s.thickness)) { s.thickness = '1px'; } if (((_ref2 = s.type) === 'line' || _ref2 === 'area') && ((_ref3 = s.lineMode) !== 'dashed')) { return delete s.lineMode; } }); return options; }, sanitizeAxes: function(axesOptions, secondAxis) { var _base; if (axesOptions == null) { axesOptions = {}; } axesOptions.x = this.sanitizeAxisOptions(axesOptions.x); (_base = axesOptions.x).key || (_base.key = "x"); axesOptions.y = this.sanitizeAxisOptions(axesOptions.y); if (secondAxis) { axesOptions.y2 = this.sanitizeAxisOptions(axesOptions.y2); } this.sanitizeExtrema(axesOptions.y); if (secondAxis) { this.sanitizeExtrema(axesOptions.y2); } return axesOptions; }, sanitizeExtrema: function(options) { var max, min; min = this.getSanitizedExtremum(options.min); if (min != null) { options.min = min; } else { delete options.min; } max = this.getSanitizedExtremum(options.max); if (max != null) { return options.max = max; } else { return delete options.max; } }, getSanitizedExtremum: function(value) { var number; if (value == null) { return void 0; } number = parseInt(value, 10); if (isNaN(number)) { $log.warn("Invalid extremum value : " + value + ", deleting it."); return void 0; } return number; }, sanitizeAxisOptions: function(options) { if (options == null) { return { type: 'linear' }; } options.type || (options.type = 'linear'); return options; }, createAxes: function(svg, dimensions, axesOptions) { var drawY2Axis, height, style, that, width, x, xAxis, y, y2, y2Axis, yAxis, _ref; drawY2Axis = axesOptions.y2 != null; width = dimensions.width; height = dimensions.height; width = width - dimensions.left - dimensions.right; height = height - dimensions.top - dimensions.bottom; x = void 0; if (axesOptions.x.type === 'date') { x = d3.time.scale().rangeRound([0, width]); } else { x = d3.scale.linear().rangeRound([0, width]); } y = void 0; if (axesOptions.y.type === 'log') { y = d3.scale.log().clamp(true).rangeRound([height, 0]); } else { y = d3.scale.linear().rangeRound([height, 0]); } y2 = void 0; if (drawY2Axis && axesOptions.y2.type === 'log') { y2 = d3.scale.log().clamp(true).rangeRound([height, 0]); } else { y2 = d3.scale.linear().rangeRound([height, 0]); } y.clamp(true); y2.clamp(true); xAxis = d3.svg.axis().scale(x).orient('bottom').tickFormat(axesOptions.x.labelFunction); yAxis = d3.svg.axis().scale(y).orient('left').tickFormat(axesOptions.y.labelFunction); y2Axis = d3.svg.axis().scale(y2).orient('right').tickFormat((_ref = axesOptions.y2) != null ? _ref.labelFunction : void 0); style = function(group) { group.style({ 'font': '10px Courier', 'shape-rendering': 'crispEdges' }); return group.selectAll('path').style({ 'fill': 'none', 'stroke': '#000' }); }; that = this; return { xScale: x, yScale: y, y2Scale: y2, xAxis: xAxis, yAxis: yAxis, y2Axis: y2Axis, andAddThemIf: function(condition) { if (!condition) { style(svg.append('g').attr('class', 'x axis').attr('transform', 'translate(0,' + height + ')').call(xAxis)); style(svg.append('g').attr('class', 'y axis').call(yAxis)); if (drawY2Axis) { style(svg.append('g').attr('class', 'y2 axis').attr('transform', 'translate(' + width + ', 0)').call(y2Axis)); } } return { xScale: x, yScale: y, y2Scale: y2, xAxis: xAxis, yAxis: yAxis, y2Axis: y2Axis }; } }; }, setScalesDomain: function(scales, data, series, svg, axesOptions) { var y2Domain, yDomain; this.setXScale(scales.xScale, data, series, axesOptions); yDomain = this.getVerticalDomain(axesOptions, data, series, 'y'); y2Domain = this.getVerticalDomain(axesOptions, data, series, 'y2'); scales.yScale.domain(yDomain).nice(); scales.y2Scale.domain(y2Domain).nice(); svg.selectAll('.x.axis').call(scales.xAxis); svg.selectAll('.y.axis').call(scales.yAxis); return svg.selectAll('.y2.axis').call(scales.y2Axis); }, getVerticalDomain: function(axesOptions, data, series, key) { var domain, o; if (!(o = axesOptions[key])) { return []; } domain = this.yExtent(series.filter(function(s) { return s.axis === key; }), data); if (o.type === 'log') { domain[0] = domain[0] === 0 ? 0.001 : domain[0]; } if (o.min != null) { domain[0] = o.min; } if (o.max != null) { domain[1] = o.max; } return domain; }, yExtent: function(series, data) { var maxY, minY; minY = Number.POSITIVE_INFINITY; maxY = Number.NEGATIVE_INFINITY; series.forEach(function(s) { minY = Math.min(minY, d3.min(data, function(d) { return d[s.y]; })); return maxY = Math.max(maxY, d3.max(data, function(d) { return d[s.y]; })); }); if (minY === maxY) { if (minY > 0) { return [0, minY * 2]; } else { return [minY * 2, 0]; } } return [minY, maxY]; }, setXScale: function(xScale, data, series, axesOptions) { xScale.domain(this.xExtent(data, axesOptions.x.key)); if (series.filter(function(s) { return s.type === 'column'; }).length) { return this.adjustXScaleForColumns(xScale, data, axesOptions.x.key); } }, xExtent: function(data, key) { var from, to, _ref; _ref = d3.extent(data, function(d) { return d[key]; }), from = _ref[0], to = _ref[1]; if (from === to) { if (from > 0) { return [0, from * 2]; } else { return [from * 2, 0]; } } return [from, to]; }, adjustXScaleForColumns: function(xScale, data, field) { var d, step; step = this.getAverageStep(data, field); d = xScale.domain(); if (angular.isDate(d[0])) { return xScale.domain([new Date(d[0].getTime() - step), new Date(d[1].getTime() + step)]); } else { return xScale.domain([d[0] - step, d[1] + step]); } }, getAverageStep: function(data, field) { var i, n, sum; if (!(data.length > 1)) { return 0; } sum = 0; n = data.length - 1; i = 0; while (i < n) { sum += data[i + 1][field] - data[i][field]; i++; } return sum / n; }, haveSecondYAxis: function(series) { return !series.every(function(s) { return s.axis !== 'y2'; }); }, getTooltipHandlers: function(options) { if (options.tooltipMode === 'scrubber') { return { onChartHover: angular.bind(this, this.showScrubber) }; } else { return { onMouseOver: angular.bind(this, this.onMouseOver), onMouseOut: angular.bind(this, this.onMouseOut) }; } }, showScrubber: function(svg, glass, axes, data) { var that; that = this; glass.on('mousemove', function() { svg.selectAll('.glass-container').attr('opacity', 1); return that.updateScrubber(svg, d3.mouse(this), axes, data); }); return glass.on('mouseout', function() { glass.on('mousemove', null); return svg.selectAll('.glass-container').attr('opacity', 0); }); }, updateScrubber: function(svg, _arg, axes, data) { var getClosest, that, x, y; x = _arg[0], y = _arg[1]; getClosest = function(values, value) { var i, left, right; left = 0; right = values.length - 1; i = Math.round((right - left) / 2); while (true) { if (value < values[i].x) { right = i; i = i - Math.ceil((right - left) / 2); } else { left = i; i = i + Math.floor((right - left) / 2); } if (i === left || i === right) { if (Math.abs(value - values[left].x) < Math.abs(value - values[right].x)) { i = left; } else { i = right; } break; } } return values[i]; }; that = this; return data.forEach(function(series, index) { var item, v; v = getClosest(series.values, axes.xScale.invert(x)); item = svg.select(".scrubberItem.series_" + index); item.transition().duration(50).attr({ 'transform': "translate(" + (axes.xScale(v.x)) + ", " + (axes[v.axis + 'Scale'](v.value)) + ")" }); item.select('text').text(v.value); return item.select('path').attr('d', function(s) { if (s.axis === 'y2') { return that.getY2TooltipPath(that.getTextWidth('' + v.value)); } else { return that.getYTooltipPath(that.getTextWidth('' + v.value)); } }); }); }, addTooltips: function(svg, dimensions, axesOptions) { var h, height, p, w, width, xTooltip, y2Tooltip, yTooltip; width = dimensions.width; height = dimensions.height; width = width - dimensions.left - dimensions.right; height = height - dimensions.top - dimensions.bottom; w = 24; h = 18; p = 5; xTooltip = svg.append('g').attr({ 'id': 'xTooltip', 'class': 'xTooltip', 'opacity': 0 }); xTooltip.append('path').attr('transform', "translate(0," + (height + 1) + ")"); xTooltip.append('text').style('text-anchor', 'middle').attr({ 'width': w, 'height': h, 'font-family': 'monospace', 'font-size': 10, 'transform': 'translate(0,' + (height + 19) + ')', 'fill': 'white', 'text-rendering': 'geometric-precision' }); yTooltip = svg.append('g').attr({ id: 'yTooltip', "class": 'yTooltip', opacity: 0 }); yTooltip.append('path'); yTooltip.append('text').attr({ 'width': h, 'height': w, 'font-family': 'monospace', 'font-size': 10, 'fill': 'white', 'text-rendering': 'geometric-precision' }); if (axesOptions.y2 != null) { y2Tooltip = svg.append('g').attr({ 'id': 'y2Tooltip', 'class': 'y2Tooltip', 'opacity': 0, 'transform': 'translate(' + width + ',0)' }); y2Tooltip.append('path'); return y2Tooltip.append('text').attr({ 'width': h, 'height': w, 'font-family': 'monospace', 'font-size': 10, 'fill': 'white', 'text-rendering': 'geometric-precision' }); } }, onMouseOver: function(svg, event) { this.updateXTooltip(svg, event); if (event.series.axis === 'y2') { return this.updateY2Tooltip(svg, event); } else { return this.updateYTooltip(svg, event); } }, onMouseOut: function(svg) { return this.hideTooltips(svg); }, updateXTooltip: function(svg, event) { var textX, xTooltip; xTooltip = svg.select("#xTooltip").transition().attr({ 'opacity': 1.0, 'transform': 'translate(' + event.x + ',0)' }); textX = void 0; if (event.series.xFormatter != null) { textX = '' + event.series.xFormatter(event.datum.x); } else { textX = '' + event.datum.x; } xTooltip.select('text').text(textX); return xTooltip.select('path').attr('fill', event.series.color).attr('d', this.getXTooltipPath(textX)); }, getXTooltipPath: function(text) { var h, p, w; w = this.getTextWidth(text); h = 18; p = 5; return 'm-' + w / 2 + ' ' + p + ' ' + 'l0 ' + h + ' ' + 'l' + w + ' 0 ' + 'l0 ' + '-' + h + 'l-' + (w / 2 - p) + ' 0 ' + 'l-' + p + ' -' + h / 4 + ' ' + 'l-' + p + ' ' + h / 4 + ' ' + 'l-' + (w / 2 - p) + ' 0z'; }, updateYTooltip: function(svg, event) { var textY, w, yTooltip, yTooltipText; yTooltip = svg.select("#yTooltip").transition().attr({ 'opacity': 1.0, 'transform': 'translate(0, ' + event.y + ')' }); textY = '' + event.datum.value; w = this.getTextWidth(textY); yTooltipText = yTooltip.select('text').text(textY); yTooltipText.attr({ 'transform': 'translate(' + (-w - 2) + ',3)', 'width': w }); return yTooltip.select('path').attr('fill', event.series.color).attr('d', this.getYTooltipPath(w)); }, getYTooltipPath: function(w) { var h, p; h = 18; p = 5; return 'm0 0' + 'l-' + p + ' -' + p + ' ' + 'l0 -' + (h / 2 - p) + ' ' + 'l-' + w + ' 0 ' + 'l0 ' + h + ' ' + 'l' + w + ' 0 ' + 'l0 -' + (h / 2 - p) + 'l-' + p + ' ' + p + 'z'; }, updateY2Tooltip: function(svg, event) { var textY, w, y2Tooltip, y2TooltipText; y2Tooltip = svg.select("#y2Tooltip").transition().attr('opacity', 1.0); textY = '' + event.datum.value; w = this.getTextWidth(textY); y2TooltipText = y2Tooltip.select('text').text(textY); y2TooltipText.attr({ 'transform': 'translate(7, ' + (parseFloat(event.y) + 3) + ')', 'w': w }); return y2Tooltip.select('path').attr({ 'fill': event.series.color, 'd': this.getY2TooltipPath(w), 'transform': 'translate(0, ' + event.y + ')' }); }, getY2TooltipPath: function(w) { var h, p; h = 18; p = 5; return 'm0 0' + 'l' + p + ' ' + p + ' ' + 'l0 ' + (h / 2 - p) + ' ' + 'l' + w + ' 0 ' + 'l0 -' + h + ' ' + 'l-' + w + ' 0 ' + 'l0 ' + (h / 2 - p) + ' ' + 'l-' + p + ' ' + p + 'z'; }, hideTooltips: function(svg) { svg.select("#xTooltip").transition().attr('opacity', 0); svg.select("#yTooltip").transition().attr('opacity', 0); return svg.select("#y2Tooltip").transition().attr('opacity', 0); } }; } ]);
// Backbone React Component // ======================== // // Backbone.React.Component v0.8.0-alpha.1 // // (c) 2014 "Magalhas" José Magalhães <magalhas@gmail.com> // Backbone.React.Component can be freely distributed under the MIT license. // // // `Backbone.React.Component` is a mixin that glues [Backbone](http://backbonejs.org/) // models and collections into [React](http://facebook.github.io/react/) components. // // When the component is mounted, a wrapper starts listening to models and // collections changes to automatically set your component props and achieve UI // binding through reactive updates. // // // // Basic Usage // // var MyComponent = React.createClass({ // mixins: [Backbone.React.Component.mixin], // render: function () { // return <div>{this.props.foo}</div>; // } // }); // var model = new Backbone.Model({foo: 'bar'}); // React.render(<MyComponent model={model} />, document.body); (function (root, factory) { // Universal module definition if (typeof define === 'function' && define.amd) { define(['react', 'backbone', 'underscore'], factory); } else if (typeof module !== 'undefined' && module.exports) { module.exports = factory(require('react'), require('backbone'), require('underscore')); } else { factory(root.React, root.Backbone, root._); } }(this, function (React, Backbone, _) { 'use strict'; if (!Backbone.React) { Backbone.React = {}; } if (!Backbone.React.Component) { Backbone.React.Component = {}; } // Mixin used in all component instances. Exported through `Backbone.React.Component.mixin`. Backbone.React.Component.mixin = { // Types of the context passed to child components. Only // `hasParentBackboneMixin` is required all of the others are optional. childContextTypes: { hasParentBackboneMixin: React.PropTypes.bool.isRequired, parentModel: React.PropTypes.any, parentCollection: React.PropTypes.any }, // Types of the context received from the parent component. All of them are // optional. contextTypes: { hasParentBackboneMixin: React.PropTypes.bool, parentModel: React.PropTypes.any, parentCollection: React.PropTypes.any }, // Passes data to our child components. getChildContext: function () { return { hasParentBackboneMixin: true, parentModel: this.getModel(), parentCollection: this.getCollection() }; }, // Sets `this.el` and `this.$el` when the component mounts. componentDidMount: function () { this.setElement(this.getDOMNode()); }, // Sets `this.el` and `this.$el` when the component updates. componentDidUpdate: function () { this.setElement(this.getDOMNode()); }, // When the component mounts, instance a `Wrapper` to take care // of models and collections binding with `this.props`. componentWillMount: function () { if (!this.wrapper) { this.wrapper = new Wrapper(this, this.props); } }, // When the component unmounts, dispose listeners and delete // `this.wrapper` reference. componentWillUnmount: function () { if (this.wrapper) { this.wrapper.stopListening(); delete this.wrapper; } }, // In order to allow passing nested models and collections as reference we // filter `nextProps.model` and `nextProps.collection`. componentWillReceiveProps: function (nextProps) { var model = nextProps.model; var collection = nextProps.collection; var key; if (this.wrapper.model && model) { delete nextProps.model; if (this.wrapper.model.attributes) { this.wrapper.setProps(model, void 0, nextProps); } else { for (key in model) { this.wrapper.setProps(model[key], key, nextProps); } } } if (this.wrapper.collection && collection && !(collection instanceof Array)) { delete nextProps.collection; if (this.wrapper.collection.models) { this.wrapper.setProps(collection, void 0, nextProps); } else { for (key in collection) { this.wrapper.setProps(collection[key], key, nextProps); } } } }, // Shortcut to `@$el.find`. Inspired by `Backbone.View`. $: function () { return this.$el && this.$el.find.apply(this.$el, arguments); }, // Grabs the collection from `@wrapper.collection` or `@context.parentCollection` getCollection: function () { return this.wrapper.collection || this.context.parentCollection; }, // Grabs the model from `@wrapper.model` or `@context.parentModel` getModel: function () { return this.wrapper.model || this.context.parentModel; }, // Sets a DOM element to render/mount this component on this.el and this.$el. setElement: function (el) { if (el && Backbone.$ && el instanceof Backbone.$) { if (el.length > 1) { throw new Error('You can only assign one element to a component'); } this.el = el[0]; this.$el = el; } else if (el) { this.el = el; if (Backbone.$) { this.$el = Backbone.$(el); } } return this; } }; // Binds models and collections to a `React.Component`. It mixes `Backbone.Events`. function Wrapper (component, props) { props = props || {}; var model = props.model, collection = props.collection; // Check if `props.model` is a `Backbone.Model` or an hashmap of them if (typeof model !== 'undefined' && (model.attributes || typeof model === 'object' && _.values(model)[0].attributes)) { delete props.model; // The model(s) bound to this component this.model = model; // Set model(s) attributes on `props` for the first render this.setPropsBackbone(model, void 0, props); } // Check if `props.collection` is a `Backbone.Collection` or an hashmap of them if (typeof collection !== 'undefined' && (collection.models || typeof collection === 'object' && _.values(collection)[0].models)) { delete props.collection; // The collection(s) bound to this component this.collection = collection; // Set collection(s) models on props for the first render this.setPropsBackbone(collection, void 0, props); } // 1:1 relation with the `component` this.component = component; // Start listeners if this is a root node and if there's DOM if (!component.context.hasParentBackboneMixin && typeof document !== 'undefined') { this.startModelListeners(); this.startCollectionListeners(); } } // Mixing `Backbone.Events` into `Wrapper.prototype` _.extend(Wrapper.prototype, Backbone.Events, { // Sets `this.props` when a model/collection request results in error. It delegates // to `this.setProps`. It listens to `Backbone.Model#error` and `Backbone.Collection#error`. onError: function (modelOrCollection, res, options) { // Set state only if there's no silent option if (!options.silent) this.component.setState({ isRequesting: false, hasError: true, error: res }); }, // Sets `this.props` when a model/collection request starts. It delegates to // `this.setProps`. It listens to `Backbone.Model#request` and `Backbone.Collection#request`. onRequest: function (modelOrCollection, xhr, options) { // Set props only if there's no silent option if (!options.silent) this.component.setState({ isRequesting: true, hasError: false }); }, // Sets `this.props` when a model/collection syncs. It delegates to `this.setProps`. // It listens to `Backbone.Model#sync` and `Backbone.Collection#sync` onSync: function (modelOrCollection, res, options) { // Set props only if there's no silent option if (!options.silent) this.component.setState({isRequesting: false}); }, // Used internally to set `this.collection` or `this.model` on `this.props`. Delegates to // `this.setProps`. It listens to `Backbone.Collection` events such as `add`, `remove`, // `change`, `sort`, `reset` and to `Backbone.Model` `change`. setPropsBackbone: function (modelOrCollection, key, target) { if (!(modelOrCollection.models || modelOrCollection.attributes)) { for (key in modelOrCollection) this.setPropsBackbone(modelOrCollection[key], key, target); return; } this.setProps.apply(this, arguments); }, // Sets a model, collection or object into props by delegating to `this.component.setProps`. setProps: function (modelOrCollection, key, target) { var props = {}; var newProps = modelOrCollection.toJSON ? modelOrCollection.toJSON() : modelOrCollection; if (key) { props[key] = newProps; } else if (modelOrCollection instanceof Backbone.Collection) { props.collection = newProps; } else { props = newProps; } if (target) { _.extend(target, props); } else { this.nextProps = _.extend(this.nextProps || {}, props); _.defer(_.bind(function () { if (this.nextProps) { if (this.component) { this.component.setProps(this.nextProps); } delete this.nextProps; } }, this)); } }, // Binds the component to any collection changes. startCollectionListeners: function (collection, key) { if (!collection) collection = this.collection; if (collection) { if (collection.models) this .listenTo(collection, 'add remove change sort reset', _.partial(this.setPropsBackbone, collection, key, void 0)) .listenTo(collection, 'error', this.onError) .listenTo(collection, 'request', this.onRequest) .listenTo(collection, 'sync', this.onSync); else if (typeof collection === 'object') for (key in collection) if (collection.hasOwnProperty(key)) this.startCollectionListeners(collection[key], key); } }, // Binds the component to any model changes. startModelListeners: function (model, key) { if (!model) model = this.model; if (model) { if (model.attributes) this .listenTo(model, 'change', _.partial(this.setPropsBackbone, model, key, void 0)) .listenTo(model, 'error', this.onError) .listenTo(model, 'request', this.onRequest) .listenTo(model, 'sync', this.onSync); else if (typeof model === 'object') for (key in model) this.startModelListeners(model[key], key); } } }); // Expose `Backbone.React.Component.mixin`. return Backbone.React.Component.mixin; })); // <a href="https://github.com/magalhas/backbone-react-component"><img style="position: absolute; top: 0; right: 0; border: 0;" src="https://github-camo.global.ssl.fastly.net/38ef81f8aca64bb9a64448d0d70f1308ef5341ab/68747470733a2f2f73332e616d617a6f6e6177732e636f6d2f6769746875622f726962626f6e732f666f726b6d655f72696768745f6461726b626c75655f3132313632312e706e67" alt="Fork me on GitHub" data-canonical-src="https://s3.amazonaws.com/github/ribbons/forkme_right_darkblue_121621.png"></a>
(function () { var defs = {}; // id -> {dependencies, definition, instance (possibly undefined)} // Used when there is no 'main' module. // The name is probably (hopefully) unique so minification removes for releases. var register_3795 = function (id) { var module = dem(id); var fragments = id.split('.'); var target = Function('return this;')(); for (var i = 0; i < fragments.length - 1; ++i) { if (target[fragments[i]] === undefined) target[fragments[i]] = {}; target = target[fragments[i]]; } target[fragments[fragments.length - 1]] = module; }; var instantiate = function (id) { var actual = defs[id]; var dependencies = actual.deps; var definition = actual.defn; var len = dependencies.length; var instances = new Array(len); for (var i = 0; i < len; ++i) instances[i] = dem(dependencies[i]); var defResult = definition.apply(null, instances); if (defResult === undefined) throw 'module [' + id + '] returned undefined'; actual.instance = defResult; }; var def = function (id, dependencies, definition) { if (typeof id !== 'string') throw 'module id must be a string'; else if (dependencies === undefined) throw 'no dependencies for ' + id; else if (definition === undefined) throw 'no definition function for ' + id; defs[id] = { deps: dependencies, defn: definition, instance: undefined }; }; var dem = function (id) { var actual = defs[id]; if (actual === undefined) throw 'module [' + id + '] was undefined'; else if (actual.instance === undefined) instantiate(id); return actual.instance; }; var req = function (ids, callback) { var len = ids.length; var instances = new Array(len); for (var i = 0; i < len; ++i) instances.push(dem(ids[i])); callback.apply(null, callback); }; var ephox = {}; ephox.bolt = { module: { api: { define: def, require: req, demand: dem } } }; var define = def; var require = req; var demand = dem; // this helps with minificiation when using a lot of global references var defineGlobal = function (id, ref) { define(id, [], function () { return ref; }); }; /*jsc ["tinymce.plugins.charmap.Plugin","tinymce.core.PluginManager","tinymce.core.util.Tools","global!tinymce.util.Tools.resolve"] jsc*/ defineGlobal("global!tinymce.util.Tools.resolve", tinymce.util.Tools.resolve); /** * ResolveGlobal.js * * Released under LGPL License. * Copyright (c) 1999-2017 Ephox Corp. All rights reserved * * License: http://www.tinymce.com/license * Contributing: http://www.tinymce.com/contributing */ define( 'tinymce.core.PluginManager', [ 'global!tinymce.util.Tools.resolve' ], function (resolve) { return resolve('tinymce.PluginManager'); } ); /** * ResolveGlobal.js * * Released under LGPL License. * Copyright (c) 1999-2017 Ephox Corp. All rights reserved * * License: http://www.tinymce.com/license * Contributing: http://www.tinymce.com/contributing */ define( 'tinymce.core.util.Tools', [ 'global!tinymce.util.Tools.resolve' ], function (resolve) { return resolve('tinymce.util.Tools'); } ); /** * Plugin.js * * Released under LGPL License. * Copyright (c) 1999-2017 Ephox Corp. All rights reserved * * License: http://www.tinymce.com/license * Contributing: http://www.tinymce.com/contributing */ /** * This class contains all core logic for the charmap plugin. * * @class tinymce.charmap.Plugin * @private */ define( 'tinymce.plugins.charmap.Plugin', [ 'tinymce.core.PluginManager', 'tinymce.core.util.Tools' ], function (PluginManager, Tools) { PluginManager.add('charmap', function (editor) { var isArray = Tools.isArray; function getDefaultCharMap() { return [ ['160', 'no-break space'], ['173', 'soft hyphen'], ['34', 'quotation mark'], // finance ['162', 'cent sign'], ['8364', 'euro sign'], ['163', 'pound sign'], ['165', 'yen sign'], // signs ['169', 'copyright sign'], ['174', 'registered sign'], ['8482', 'trade mark sign'], ['8240', 'per mille sign'], ['181', 'micro sign'], ['183', 'middle dot'], ['8226', 'bullet'], ['8230', 'three dot leader'], ['8242', 'minutes / feet'], ['8243', 'seconds / inches'], ['167', 'section sign'], ['182', 'paragraph sign'], ['223', 'sharp s / ess-zed'], // quotations ['8249', 'single left-pointing angle quotation mark'], ['8250', 'single right-pointing angle quotation mark'], ['171', 'left pointing guillemet'], ['187', 'right pointing guillemet'], ['8216', 'left single quotation mark'], ['8217', 'right single quotation mark'], ['8220', 'left double quotation mark'], ['8221', 'right double quotation mark'], ['8218', 'single low-9 quotation mark'], ['8222', 'double low-9 quotation mark'], ['60', 'less-than sign'], ['62', 'greater-than sign'], ['8804', 'less-than or equal to'], ['8805', 'greater-than or equal to'], ['8211', 'en dash'], ['8212', 'em dash'], ['175', 'macron'], ['8254', 'overline'], ['164', 'currency sign'], ['166', 'broken bar'], ['168', 'diaeresis'], ['161', 'inverted exclamation mark'], ['191', 'turned question mark'], ['710', 'circumflex accent'], ['732', 'small tilde'], ['176', 'degree sign'], ['8722', 'minus sign'], ['177', 'plus-minus sign'], ['247', 'division sign'], ['8260', 'fraction slash'], ['215', 'multiplication sign'], ['185', 'superscript one'], ['178', 'superscript two'], ['179', 'superscript three'], ['188', 'fraction one quarter'], ['189', 'fraction one half'], ['190', 'fraction three quarters'], // math / logical ['402', 'function / florin'], ['8747', 'integral'], ['8721', 'n-ary sumation'], ['8734', 'infinity'], ['8730', 'square root'], ['8764', 'similar to'], ['8773', 'approximately equal to'], ['8776', 'almost equal to'], ['8800', 'not equal to'], ['8801', 'identical to'], ['8712', 'element of'], ['8713', 'not an element of'], ['8715', 'contains as member'], ['8719', 'n-ary product'], ['8743', 'logical and'], ['8744', 'logical or'], ['172', 'not sign'], ['8745', 'intersection'], ['8746', 'union'], ['8706', 'partial differential'], ['8704', 'for all'], ['8707', 'there exists'], ['8709', 'diameter'], ['8711', 'backward difference'], ['8727', 'asterisk operator'], ['8733', 'proportional to'], ['8736', 'angle'], // undefined ['180', 'acute accent'], ['184', 'cedilla'], ['170', 'feminine ordinal indicator'], ['186', 'masculine ordinal indicator'], ['8224', 'dagger'], ['8225', 'double dagger'], // alphabetical special chars ['192', 'A - grave'], ['193', 'A - acute'], ['194', 'A - circumflex'], ['195', 'A - tilde'], ['196', 'A - diaeresis'], ['197', 'A - ring above'], ['256', 'A - macron'], ['198', 'ligature AE'], ['199', 'C - cedilla'], ['200', 'E - grave'], ['201', 'E - acute'], ['202', 'E - circumflex'], ['203', 'E - diaeresis'], ['274', 'E - macron'], ['204', 'I - grave'], ['205', 'I - acute'], ['206', 'I - circumflex'], ['207', 'I - diaeresis'], ['298', 'I - macron'], ['208', 'ETH'], ['209', 'N - tilde'], ['210', 'O - grave'], ['211', 'O - acute'], ['212', 'O - circumflex'], ['213', 'O - tilde'], ['214', 'O - diaeresis'], ['216', 'O - slash'], ['332', 'O - macron'], ['338', 'ligature OE'], ['352', 'S - caron'], ['217', 'U - grave'], ['218', 'U - acute'], ['219', 'U - circumflex'], ['220', 'U - diaeresis'], ['362', 'U - macron'], ['221', 'Y - acute'], ['376', 'Y - diaeresis'], ['562', 'Y - macron'], ['222', 'THORN'], ['224', 'a - grave'], ['225', 'a - acute'], ['226', 'a - circumflex'], ['227', 'a - tilde'], ['228', 'a - diaeresis'], ['229', 'a - ring above'], ['257', 'a - macron'], ['230', 'ligature ae'], ['231', 'c - cedilla'], ['232', 'e - grave'], ['233', 'e - acute'], ['234', 'e - circumflex'], ['235', 'e - diaeresis'], ['275', 'e - macron'], ['236', 'i - grave'], ['237', 'i - acute'], ['238', 'i - circumflex'], ['239', 'i - diaeresis'], ['299', 'i - macron'], ['240', 'eth'], ['241', 'n - tilde'], ['242', 'o - grave'], ['243', 'o - acute'], ['244', 'o - circumflex'], ['245', 'o - tilde'], ['246', 'o - diaeresis'], ['248', 'o slash'], ['333', 'o macron'], ['339', 'ligature oe'], ['353', 's - caron'], ['249', 'u - grave'], ['250', 'u - acute'], ['251', 'u - circumflex'], ['252', 'u - diaeresis'], ['363', 'u - macron'], ['253', 'y - acute'], ['254', 'thorn'], ['255', 'y - diaeresis'], ['563', 'y - macron'], ['913', 'Alpha'], ['914', 'Beta'], ['915', 'Gamma'], ['916', 'Delta'], ['917', 'Epsilon'], ['918', 'Zeta'], ['919', 'Eta'], ['920', 'Theta'], ['921', 'Iota'], ['922', 'Kappa'], ['923', 'Lambda'], ['924', 'Mu'], ['925', 'Nu'], ['926', 'Xi'], ['927', 'Omicron'], ['928', 'Pi'], ['929', 'Rho'], ['931', 'Sigma'], ['932', 'Tau'], ['933', 'Upsilon'], ['934', 'Phi'], ['935', 'Chi'], ['936', 'Psi'], ['937', 'Omega'], ['945', 'alpha'], ['946', 'beta'], ['947', 'gamma'], ['948', 'delta'], ['949', 'epsilon'], ['950', 'zeta'], ['951', 'eta'], ['952', 'theta'], ['953', 'iota'], ['954', 'kappa'], ['955', 'lambda'], ['956', 'mu'], ['957', 'nu'], ['958', 'xi'], ['959', 'omicron'], ['960', 'pi'], ['961', 'rho'], ['962', 'final sigma'], ['963', 'sigma'], ['964', 'tau'], ['965', 'upsilon'], ['966', 'phi'], ['967', 'chi'], ['968', 'psi'], ['969', 'omega'], // symbols ['8501', 'alef symbol'], ['982', 'pi symbol'], ['8476', 'real part symbol'], ['978', 'upsilon - hook symbol'], ['8472', 'Weierstrass p'], ['8465', 'imaginary part'], // arrows ['8592', 'leftwards arrow'], ['8593', 'upwards arrow'], ['8594', 'rightwards arrow'], ['8595', 'downwards arrow'], ['8596', 'left right arrow'], ['8629', 'carriage return'], ['8656', 'leftwards double arrow'], ['8657', 'upwards double arrow'], ['8658', 'rightwards double arrow'], ['8659', 'downwards double arrow'], ['8660', 'left right double arrow'], ['8756', 'therefore'], ['8834', 'subset of'], ['8835', 'superset of'], ['8836', 'not a subset of'], ['8838', 'subset of or equal to'], ['8839', 'superset of or equal to'], ['8853', 'circled plus'], ['8855', 'circled times'], ['8869', 'perpendicular'], ['8901', 'dot operator'], ['8968', 'left ceiling'], ['8969', 'right ceiling'], ['8970', 'left floor'], ['8971', 'right floor'], ['9001', 'left-pointing angle bracket'], ['9002', 'right-pointing angle bracket'], ['9674', 'lozenge'], ['9824', 'black spade suit'], ['9827', 'black club suit'], ['9829', 'black heart suit'], ['9830', 'black diamond suit'], ['8194', 'en space'], ['8195', 'em space'], ['8201', 'thin space'], ['8204', 'zero width non-joiner'], ['8205', 'zero width joiner'], ['8206', 'left-to-right mark'], ['8207', 'right-to-left mark'] ]; } function charmapFilter(charmap) { return Tools.grep(charmap, function (item) { return isArray(item) && item.length == 2; }); } function getCharsFromSetting(settingValue) { if (isArray(settingValue)) { return [].concat(charmapFilter(settingValue)); } if (typeof settingValue == "function") { return settingValue(); } return []; } function extendCharMap(charmap) { var settings = editor.settings; if (settings.charmap) { charmap = getCharsFromSetting(settings.charmap); } if (settings.charmap_append) { return [].concat(charmap).concat(getCharsFromSetting(settings.charmap_append)); } return charmap; } function getCharMap() { return extendCharMap(getDefaultCharMap()); } function insertChar(chr) { editor.fire('insertCustomChar', { chr: chr }).chr; editor.execCommand('mceInsertContent', false, chr); } function showDialog() { var gridHtml, x, y, win; function getParentTd(elm) { while (elm) { if (elm.nodeName == 'TD') { return elm; } elm = elm.parentNode; } } gridHtml = '<table role="presentation" cellspacing="0" class="mce-charmap"><tbody>'; var charmap = getCharMap(); var width = Math.min(charmap.length, 25); var height = Math.ceil(charmap.length / width); for (y = 0; y < height; y++) { gridHtml += '<tr>'; for (x = 0; x < width; x++) { var index = y * width + x; if (index < charmap.length) { var chr = charmap[index]; var chrText = chr ? String.fromCharCode(parseInt(chr[0], 10)) : '&nbsp;'; gridHtml += ( '<td title="' + chr[1] + '">' + '<div tabindex="-1" title="' + chr[1] + '" role="button" data-chr="' + chrText + '">' + chrText + '</div>' + '</td>' ); } else { gridHtml += '<td />'; } } gridHtml += '</tr>'; } gridHtml += '</tbody></table>'; var charMapPanel = { type: 'container', html: gridHtml, onclick: function (e) { var target = e.target; if (/^(TD|DIV)$/.test(target.nodeName)) { var charDiv = getParentTd(target).firstChild; if (charDiv && charDiv.hasAttribute('data-chr')) { insertChar(charDiv.getAttribute('data-chr')); if (!e.ctrlKey) { win.close(); } } } }, onmouseover: function (e) { var td = getParentTd(e.target); if (td && td.firstChild) { win.find('#preview').text(td.firstChild.firstChild.data); win.find('#previewTitle').text(td.title); } else { win.find('#preview').text(' '); win.find('#previewTitle').text(' '); } } }; win = editor.windowManager.open({ title: "Special character", spacing: 10, padding: 10, items: [ charMapPanel, { type: 'container', layout: 'flex', direction: 'column', align: 'center', spacing: 5, minWidth: 160, minHeight: 160, items: [ { type: 'label', name: 'preview', text: ' ', style: 'font-size: 40px; text-align: center', border: 1, minWidth: 140, minHeight: 80 }, { type: 'label', name: 'previewTitle', text: ' ', style: 'text-align: center', border: 1, minWidth: 140, minHeight: 80 } ] } ], buttons: [ { text: "Close", onclick: function () { win.close(); } } ] }); } editor.addCommand('mceShowCharmap', showDialog); editor.addButton('charmap', { icon: 'charmap', tooltip: 'Special character', cmd: 'mceShowCharmap' }); editor.addMenuItem('charmap', { icon: 'charmap', text: 'Special character', cmd: 'mceShowCharmap', context: 'insert' }); return { getCharMap: getCharMap, insertChar: insertChar }; }); return function () { }; } ); dem('tinymce.plugins.charmap.Plugin')(); })();
var spawnCommand = require('../'), command = (process.platform === 'win32') ? 'echo "Hello spawn"' : 'echo "Hello spawn" | base64', child = spawnCommand(command); child.stdout.on('data', function (data) { console.log('data', data.toString()); }); child.on('exit', function (exitCode) { console.log('exit', exitCode); });
exports.index = 1; exports.show = 'nothing'
/** * 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. * * @providesModule DOMLazyTree */ 'use strict'; var DOMNamespaces = require('./DOMNamespaces'); var setInnerHTML = require('./setInnerHTML'); var createMicrosoftUnsafeLocalFunction = require('./createMicrosoftUnsafeLocalFunction'); var setTextContent = require('./setTextContent'); 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;
var Stream = require('stream'); var json = typeof JSON === 'object' ? JSON : require('jsonify'); var through = require('through'); var nextTick = typeof setImmediate !== 'undefined' ? setImmediate : process.nextTick ; module.exports = function () { var output = through(); output.pause(); output.queue('TAP version 13\n'); var results = new Results(output); output.push = function (t) { results.push(t) }; output.only = function (name) { results.only = name; }; nextTick(function next () { var t = results.tests.shift(); if (!t && results.running) return; if (!t) return results.close(); t.run(); }); return output; }; function Results (stream) { this.count = 0; this.fail = 0; this.pass = 0; this.stream = stream; this.tests = []; this.running = 0; } Results.prototype.push = function (t, parentT) { var self = this; var write = function (s) { self.stream.queue(s) }; t.once('prerun', function () { if (self.only && self.only !== t.name && !parentT) { var nt = self.tests.shift(); if (nt) nt.run() else self.close(); return; } self.running ++; write('# ' + t.name + '\n'); }); if (parentT) { var ix = self.tests.indexOf(parentT); if (ix >= 0) self.tests.splice(ix, 0, t); } else self.tests.push(t); var plan; t.on('plan', function (n) { plan = n }); var subtests = 0; t.on('test', function (st) { subtests ++; st.on('end', function () { subtests --; if (subtests === 1) nextTick(function () { st.run() }); else if (subtests === 0 && !t.ended) { t.end(); } }); self.push(st, t); if (subtests === 1) { if (plan === undefined) st.run(); else nextTick(function () { st.run(); }); } }); t.on('result', function (res) { if (typeof res === 'string') { write('# ' + res + '\n'); return; } write(encodeResult(res, self.count + 1)); self.count ++; if (res.ok) self.pass ++ else self.fail ++ }); t.once('end', function () { if (t._skip) { var nt = self.tests.shift(); if (nt) nt.run(); else self.close(); return; } self.running --; if (subtests !== 0) return; if (self.running === 0 && self.tests.length) { var nt = self.tests.shift(); nt.run(); } else if (self.running === 0) { self.close(); } }); }; Results.prototype.close = function () { var self = this; if (self.closed) self.stream.emit('error', new Error('ALREADY CLOSED')); self.closed = true; var write = function (s) { self.stream.queue(s) }; write('\n1..' + self.count + '\n'); write('# tests ' + self.count + '\n'); write('# pass ' + self.pass + '\n'); if (self.fail) write('# fail ' + self.fail + '\n') else write('\n# ok\n') self.stream.queue(null); }; function encodeResult (res, count) { var output = ''; output += (res.ok ? 'ok ' : 'not ok ') + count; output += res.name ? ' ' + res.name.replace(/\s+/g, ' ') : ''; if (res.skip) output += ' # SKIP'; else if (res.todo) output += ' # TODO'; output += '\n'; if (res.ok) return output; var outer = ' '; var inner = outer + ' '; output += outer + '---\n'; output += inner + 'operator: ' + res.operator + '\n'; var ex = json.stringify(res.expected, getSerialize()) || ''; var ac = json.stringify(res.actual, getSerialize()) || ''; if (Math.max(ex.length, ac.length) > 65) { output += inner + 'expected:\n' + inner + ' ' + ex + '\n'; output += inner + 'actual:\n' + inner + ' ' + ac + '\n'; } else { output += inner + 'expected: ' + ex + '\n'; output += inner + 'actual: ' + ac + '\n'; } if (res.at) { output += inner + 'at: ' + res.at + '\n'; } if (res.operator === 'error' && res.actual && res.actual.stack) { var lines = String(res.actual.stack).split('\n'); output += inner + 'stack:\n'; output += inner + ' ' + lines[0] + '\n'; for (var i = 1; i < lines.length; i++) { output += inner + lines[i] + '\n'; } } output += outer + '...\n'; return output; } function getSerialize () { var seen = []; return function (key, value) { var ret = value; if (typeof value === 'object' && value) { var found = false; for (var i = 0; i < seen.length; i++) { if (seen[i] === value) { found = true break; } } if (found) ret = '[Circular]' else seen.push(value) } return ret; }; }
/* Copyright (c) 2004-2013, The Dojo Foundation All Rights Reserved. Available via Academic Free License >= 2.1 OR the modified BSD license. see: http://dojotoolkit.org/license for details */ if(!dojo._hasResource["dojo.dnd.Avatar"]){ dojo._hasResource["dojo.dnd.Avatar"]=true; dojo.provide("dojo.dnd.Avatar"); dojo.require("dojo.dnd.common"); dojo.declare("dojo.dnd.Avatar",null,{constructor:function(_1){ this.manager=_1; this.construct(); },construct:function(){ this.isA11y=dojo.hasClass(dojo.body(),"dijit_a11y"); var a=dojo.create("table",{"class":"dojoDndAvatar",style:{position:"absolute",zIndex:"1999",margin:"0px"}}),_2=this.manager.source,_3,b=dojo.create("tbody",null,a),tr=dojo.create("tr",null,b),td=dojo.create("td",null,tr),_4=this.isA11y?dojo.create("span",{id:"a11yIcon",innerHTML:this.manager.copy?"+":"<"},td):null,_5=dojo.create("span",{innerHTML:_2.generateText?this._generateText():""},td),k=Math.min(5,this.manager.nodes.length),i=0; dojo.attr(tr,{"class":"dojoDndAvatarHeader",style:{opacity:0.9}}); for(;i<k;++i){ if(_2.creator){ _3=_2._normalizedCreator(_2.getItem(this.manager.nodes[i].id).data,"avatar").node; }else{ _3=this.manager.nodes[i].cloneNode(true); if(_3.tagName.toLowerCase()=="tr"){ var _6=dojo.create("table"),_7=dojo.create("tbody",null,_6); _7.appendChild(_3); _3=_6; } } _3.id=""; tr=dojo.create("tr",null,b); td=dojo.create("td",null,tr); td.appendChild(_3); dojo.attr(tr,{"class":"dojoDndAvatarItem",style:{opacity:(9-i)/10}}); } this.node=a; },destroy:function(){ dojo.destroy(this.node); this.node=false; },update:function(){ dojo[(this.manager.canDropFlag?"add":"remove")+"Class"](this.node,"dojoDndAvatarCanDrop"); if(this.isA11y){ var _8=dojo.byId("a11yIcon"); var _9="+"; if(this.manager.canDropFlag&&!this.manager.copy){ _9="< "; }else{ if(!this.manager.canDropFlag&&!this.manager.copy){ _9="o"; }else{ if(!this.manager.canDropFlag){ _9="x"; } } } _8.innerHTML=_9; } dojo.query(("tr.dojoDndAvatarHeader td span"+(this.isA11y?" span":"")),this.node).forEach(function(_a){ _a.innerHTML=this._generateText(); },this); },_generateText:function(){ return this.manager.nodes.length.toString(); }}); }
/* Copyright (c) 2006-2013 by OpenLayers Contributors (see authors.txt for * full list of contributors). Published under the 2-clause BSD license. * See license.txt in the OpenLayers distribution or repository for the * full text of the license. */ /** * @requires OpenLayers/Format.js */ /** * Class: OpenLayers.Format.CSWGetRecords * Default version is 2.0.2. * * Returns: * {<OpenLayers.Format>} A CSWGetRecords format of the given version. */ OpenLayers.Format.CSWGetRecords = function(options) { options = OpenLayers.Util.applyDefaults( options, OpenLayers.Format.CSWGetRecords.DEFAULTS ); var cls = OpenLayers.Format.CSWGetRecords["v"+options.version.replace(/\./g, "_")]; if(!cls) { throw "Unsupported CSWGetRecords version: " + options.version; } return new cls(options); }; /** * Constant: DEFAULTS * {Object} Default properties for the CSWGetRecords format. */ OpenLayers.Format.CSWGetRecords.DEFAULTS = { "version": "2.0.2" };
/*! * Parsleyjs * Guillaume Potier - <guillaume@wisembly.com> * Version 2.0.3 - built Mon Jul 21 2014 11:58:33 * MIT Licensed * */ !(function (factory) { if (typeof define === 'function' && define.amd) { // AMD. Register as an anonymous module depending on jQuery. define(['jquery'], factory); } else { // No AMD. Register plugin with global jQuery object. factory(jQuery); } }(function ($) { // small hack for requirejs if jquery is loaded through map and not path // see http://requirejs.org/docs/jquery.html if ('undefined' === typeof $ && 'undefined' !== typeof window.jQuery) $ = window.jQuery; var ParsleyUtils = { // Parsley DOM-API // returns object from dom attributes and values // if attr is given, returns bool if attr present in DOM or not attr: function ($element, namespace, checkAttr) { var attribute, obj = {}, msie = this.msieversion(), regex = new RegExp('^' + namespace, 'i'); if ('undefined' === typeof $element || 'undefined' === typeof $element[0]) return {}; for (var i in $element[0].attributes) { attribute = $element[0].attributes[i]; if ('undefined' !== typeof attribute && null !== attribute && (!msie || msie >= 8 || attribute.specified) && regex.test(attribute.name)) { if ('undefined' !== typeof checkAttr && new RegExp(checkAttr + '$', 'i').test(attribute.name)) return true; obj[this.camelize(attribute.name.replace(namespace, ''))] = this.deserializeValue(attribute.value); } } return 'undefined' === typeof checkAttr ? obj : false; }, setAttr: function ($element, namespace, attr, value) { $element[0].setAttribute(this.dasherize(namespace + attr), String(value)); }, // Recursive object / array getter get: function (obj, path) { var i = 0, paths = (path || '').split('.'); while (this.isObject(obj) || this.isArray(obj)) { obj = obj[paths[i++]]; if (i === paths.length) return obj; } return undefined; }, hash: function (length) { return String(Math.random()).substring(2, length ? length + 2 : 9); }, /** Third party functions **/ // Underscore isArray isArray: function (mixed) { return Object.prototype.toString.call(mixed) === '[object Array]'; }, // Underscore isObject isObject: function (mixed) { return mixed === Object(mixed); }, // Zepto deserialize function deserializeValue: function (value) { var num; try { return value ? value == "true" || (value == "false" ? false : value == "null" ? null : !isNaN(num = Number(value)) ? num : /^[\[\{]/.test(value) ? $.parseJSON(value) : value) : value; } catch (e) { return value; } }, // Zepto camelize function camelize: function (str) { return str.replace(/-+(.)?/g, function(match, chr) { return chr ? chr.toUpperCase() : ''; }); }, // Zepto dasherize function dasherize: function (str) { return str.replace(/::/g, '/') .replace(/([A-Z]+)([A-Z][a-z])/g, '$1_$2') .replace(/([a-z\d])([A-Z])/g, '$1_$2') .replace(/_/g, '-') .toLowerCase(); }, // http://support.microsoft.com/kb/167820 // http://stackoverflow.com/questions/19999388/jquery-check-if-user-is-using-ie msieversion: function () { var ua = window.navigator.userAgent, msie = ua.indexOf('MSIE '); if (msie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./)) return parseInt(ua.substring(msie + 5, ua.indexOf('.', msie)), 10); return 0; } }; // All these options could be overriden and specified directly in DOM using // `data-parsley-` default DOM-API // eg: `inputs` can be set in DOM using `data-parsley-inputs="input, textarea"` // eg: `data-parsley-stop-on-first-failing-constraint="false"` var ParsleyDefaults = { // ### General // Default data-namespace for DOM API namespace: 'data-parsley-', // Supported inputs by default inputs: 'input, textarea, select', // Excluded inputs by default excluded: 'input[type=button], input[type=submit], input[type=reset], input[type=hidden]', // Stop validating field on highest priority failing constraint priorityEnabled: true, // ### UI // Enable\Disable error messages uiEnabled: true, // Key events threshold before validation validationThreshold: 3, // Focused field on form validation error. 'fist'|'last'|'none' focus: 'first', // `$.Event()` that will trigger validation. eg: `keyup`, `change`.. trigger: false, // Class that would be added on every failing validation Parsley field errorClass: 'parsley-error', // Same for success validation successClass: 'parsley-success', // Return the `$element` that will receive these above success or error classes // Could also be (and given directly from DOM) a valid selector like `'#div'` classHandler: function (ParsleyField) {}, // Return the `$element` where errors will be appended // Could also be (and given directly from DOM) a valid selector like `'#div'` errorsContainer: function (ParsleyField) {}, // ul elem that would receive errors' list errorsWrapper: '<ul class="parsley-errors-list"></ul>', // li elem that would receive error message errorTemplate: '<li></li>' }; var ParsleyAbstract = function() {}; ParsleyAbstract.prototype = { asyncSupport: false, actualizeOptions: function () { this.options = this.OptionsFactory.get(this); return this; }, // ParsleyValidator validate proxy function . Could be replaced by third party scripts validateThroughValidator: function (value, constraints, priority) { return window.ParsleyValidator.validate.apply(window.ParsleyValidator, [value, constraints, priority]); }, // Subscribe an event and a handler for a specific field or a specific form // If on a ParsleyForm instance, it will be attached to form instance and also // To every field instance for this form subscribe: function (name, fn) { $.listenTo(this, name.toLowerCase(), fn); return this; }, // Same as subscribe above. Unsubscribe an event for field, or form + its fields unsubscribe: function (name) { $.unsubscribeTo(this, name.toLowerCase()); return this; }, // Reset UI reset: function () { // Field case: just emit a reset event for UI if ('ParsleyForm' !== this.__class__) return $.emit('parsley:field:reset', this); // Form case: emit a reset event for each field for (var i = 0; i < this.fields.length; i++) $.emit('parsley:field:reset', this.fields[i]); $.emit('parsley:form:reset', this); }, // Destroy Parsley instance (+ UI) destroy: function () { // Field case: emit destroy event to clean UI and then destroy stored instance if ('ParsleyForm' !== this.__class__) { this.$element.removeData('Parsley'); this.$element.removeData('ParsleyFieldMultiple'); $.emit('parsley:field:destroy', this); return; } // Form case: destroy all its fields and then destroy stored instance for (var i = 0; i < this.fields.length; i++) this.fields[i].destroy(); this.$element.removeData('Parsley'); $.emit('parsley:form:destroy', this); } }; /*! * validator.js * Guillaume Potier - <guillaume@wisembly.com> * Version 0.5.8 - built Sun Mar 16 2014 17:18:21 * MIT Licensed * */ ( function ( exports ) { /** * Validator */ var Validator = function ( options ) { this.__class__ = 'Validator'; this.__version__ = '0.5.8'; this.options = options || {}; this.bindingKey = this.options.bindingKey || '_validatorjsConstraint'; return this; }; Validator.prototype = { constructor: Validator, /* * Validate string: validate( string, Assert, string ) || validate( string, [ Assert, Assert ], [ string, string ] ) * Validate object: validate( object, Constraint, string ) || validate( object, Constraint, [ string, string ] ) * Validate binded object: validate( object, string ) || validate( object, [ string, string ] ) */ validate: function ( objectOrString, AssertsOrConstraintOrGroup, group ) { if ( 'string' !== typeof objectOrString && 'object' !== typeof objectOrString ) throw new Error( 'You must validate an object or a string' ); // string / array validation if ( 'string' === typeof objectOrString || _isArray(objectOrString) ) return this._validateString( objectOrString, AssertsOrConstraintOrGroup, group ); // binded object validation if ( this.isBinded( objectOrString ) ) return this._validateBindedObject( objectOrString, AssertsOrConstraintOrGroup ); // regular object validation return this._validateObject( objectOrString, AssertsOrConstraintOrGroup, group ); }, bind: function ( object, constraint ) { if ( 'object' !== typeof object ) throw new Error( 'Must bind a Constraint to an object' ); object[ this.bindingKey ] = new Constraint( constraint ); return this; }, unbind: function ( object ) { if ( 'undefined' === typeof object._validatorjsConstraint ) return this; delete object[ this.bindingKey ]; return this; }, isBinded: function ( object ) { return 'undefined' !== typeof object[ this.bindingKey ]; }, getBinded: function ( object ) { return this.isBinded( object ) ? object[ this.bindingKey ] : null; }, _validateString: function ( string, assert, group ) { var result, failures = []; if ( !_isArray( assert ) ) assert = [ assert ]; for ( var i = 0; i < assert.length; i++ ) { if ( ! ( assert[ i ] instanceof Assert) ) throw new Error( 'You must give an Assert or an Asserts array to validate a string' ); result = assert[ i ].check( string, group ); if ( result instanceof Violation ) failures.push( result ); } return failures.length ? failures : true; }, _validateObject: function ( object, constraint, group ) { if ( 'object' !== typeof constraint ) throw new Error( 'You must give a constraint to validate an object' ); if ( constraint instanceof Constraint ) return constraint.check( object, group ); return new Constraint( constraint ).check( object, group ); }, _validateBindedObject: function ( object, group ) { return object[ this.bindingKey ].check( object, group ); } }; Validator.errorCode = { must_be_a_string: 'must_be_a_string', must_be_an_array: 'must_be_an_array', must_be_a_number: 'must_be_a_number', must_be_a_string_or_array: 'must_be_a_string_or_array' }; /** * Constraint */ var Constraint = function ( data, options ) { this.__class__ = 'Constraint'; this.options = options || {}; this.nodes = {}; if ( data ) { try { this._bootstrap( data ); } catch ( err ) { throw new Error( 'Should give a valid mapping object to Constraint', err, data ); } } return this; }; Constraint.prototype = { constructor: Constraint, check: function ( object, group ) { var result, failures = {}; // check all constraint nodes if strict validation enabled. Else, only object nodes that have a constraint for ( var property in this.options.strict ? this.nodes : object ) { if ( this.options.strict ? this.has( property, object ) : this.has( property ) ) { result = this._check( property, object[ property ], group ); // check returned an array of Violations or an object mapping Violations if ( ( _isArray( result ) && result.length > 0 ) || ( !_isArray( result ) && !_isEmptyObject( result ) ) ) failures[ property ] = result; // in strict mode, get a violation for each constraint node not in object } else if ( this.options.strict ) { try { // we trigger here a HaveProperty Assert violation to have uniform Violation object in the end new Assert().HaveProperty( property ).validate( object ); } catch ( violation ) { failures[ property ] = violation; } } } return _isEmptyObject(failures) ? true : failures; }, add: function ( node, object ) { if ( object instanceof Assert || ( _isArray( object ) && object[ 0 ] instanceof Assert ) ) { this.nodes[ node ] = object; return this; } if ( 'object' === typeof object && !_isArray( object ) ) { this.nodes[ node ] = object instanceof Constraint ? object : new Constraint( object ); return this; } throw new Error( 'Should give an Assert, an Asserts array, a Constraint', object ); }, has: function ( node, nodes ) { nodes = 'undefined' !== typeof nodes ? nodes : this.nodes; return 'undefined' !== typeof nodes[ node ]; }, get: function ( node, placeholder ) { return this.has( node ) ? this.nodes[ node ] : placeholder || null; }, remove: function ( node ) { var _nodes = []; for ( var i in this.nodes ) if ( i !== node ) _nodes[ i ] = this.nodes[ i ]; this.nodes = _nodes; return this; }, _bootstrap: function ( data ) { if ( data instanceof Constraint ) return this.nodes = data.nodes; for ( var node in data ) this.add( node, data[ node ] ); }, _check: function ( node, value, group ) { // Assert if ( this.nodes[ node ] instanceof Assert ) return this._checkAsserts( value, [ this.nodes[ node ] ], group ); // Asserts if ( _isArray( this.nodes[ node ] ) ) return this._checkAsserts( value, this.nodes[ node ], group ); // Constraint -> check api if ( this.nodes[ node ] instanceof Constraint ) return this.nodes[ node ].check( value, group ); throw new Error( 'Invalid node', this.nodes[ node ] ); }, _checkAsserts: function ( value, asserts, group ) { var result, failures = []; for ( var i = 0; i < asserts.length; i++ ) { result = asserts[ i ].check( value, group ); if ( 'undefined' !== typeof result && true !== result ) failures.push( result ); // Some asserts (Collection for example) could return an object // if ( result && ! ( result instanceof Violation ) ) // return result; // // // Vast assert majority return Violation // if ( result instanceof Violation ) // failures.push( result ); } return failures; } }; /** * Violation */ var Violation = function ( assert, value, violation ) { this.__class__ = 'Violation'; if ( ! ( assert instanceof Assert ) ) throw new Error( 'Should give an assertion implementing the Assert interface' ); this.assert = assert; this.value = value; if ( 'undefined' !== typeof violation ) this.violation = violation; }; Violation.prototype = { show: function () { var show = { assert: this.assert.__class__, value: this.value }; if ( this.violation ) show.violation = this.violation; return show; }, __toString: function () { if ( 'undefined' !== typeof this.violation ) this.violation = '", ' + this.getViolation().constraint + ' expected was ' + this.getViolation().expected; return this.assert.__class__ + ' assert failed for "' + this.value + this.violation || ''; }, getViolation: function () { var constraint, expected; for ( constraint in this.violation ) expected = this.violation[ constraint ]; return { constraint: constraint, expected: expected }; } }; /** * Assert */ var Assert = function ( group ) { this.__class__ = 'Assert'; this.__parentClass__ = this.__class__; this.groups = []; if ( 'undefined' !== typeof group ) this.addGroup( group ); return this; }; Assert.prototype = { construct: Assert, check: function ( value, group ) { if ( group && !this.hasGroup( group ) ) return; if ( !group && this.hasGroups() ) return; try { return this.validate( value, group ); } catch ( violation ) { return violation; } }, hasGroup: function ( group ) { if ( _isArray( group ) ) return this.hasOneOf( group ); // All Asserts respond to "Any" group if ( 'Any' === group ) return true; // Asserts with no group also respond to "Default" group. Else return false if ( !this.hasGroups() ) return 'Default' === group; return -1 !== this.groups.indexOf( group ); }, hasOneOf: function ( groups ) { for ( var i = 0; i < groups.length; i++ ) if ( this.hasGroup( groups[ i ] ) ) return true; return false; }, hasGroups: function () { return this.groups.length > 0; }, addGroup: function ( group ) { if ( _isArray( group ) ) return this.addGroups( group ); if ( !this.hasGroup( group ) ) this.groups.push( group ); return this; }, removeGroup: function ( group ) { var _groups = []; for ( var i = 0; i < this.groups.length; i++ ) if ( group !== this.groups[ i ] ) _groups.push( this.groups[ i ] ); this.groups = _groups; return this; }, addGroups: function ( groups ) { for ( var i = 0; i < groups.length; i++ ) this.addGroup( groups[ i ] ); return this; }, /** * Asserts definitions */ HaveProperty: function ( node ) { this.__class__ = 'HaveProperty'; this.node = node; this.validate = function ( object ) { if ( 'undefined' === typeof object[ this.node ] ) throw new Violation( this, object, { value: this.node } ); return true; }; return this; }, Blank: function () { this.__class__ = 'Blank'; this.validate = function ( value ) { if ( 'string' !== typeof value ) throw new Violation( this, value, { value: Validator.errorCode.must_be_a_string } ); if ( '' !== value.replace( /^\s+/g, '' ).replace( /\s+$/g, '' ) ) throw new Violation( this, value ); return true; }; return this; }, Callback: function ( fn ) { this.__class__ = 'Callback'; this.arguments = Array.prototype.slice.call( arguments ); if ( 1 === this.arguments.length ) this.arguments = []; else this.arguments.splice( 0, 1 ); if ( 'function' !== typeof fn ) throw new Error( 'Callback must be instanciated with a function' ); this.fn = fn; this.validate = function ( value ) { var result = this.fn.apply( this, [ value ].concat( this.arguments ) ); if ( true !== result ) throw new Violation( this, value, { result: result } ); return true; }; return this; }, Choice: function ( list ) { this.__class__ = 'Choice'; if ( !_isArray( list ) && 'function' !== typeof list ) throw new Error( 'Choice must be instanciated with an array or a function' ); this.list = list; this.validate = function ( value ) { var list = 'function' === typeof this.list ? this.list() : this.list; for ( var i = 0; i < list.length; i++ ) if ( value === list[ i ] ) return true; throw new Violation( this, value, { choices: list } ); }; return this; }, Collection: function ( constraint ) { this.__class__ = 'Collection'; this.constraint = 'undefined' !== typeof constraint ? new Constraint( constraint ) : false; this.validate = function ( collection, group ) { var result, validator = new Validator(), count = 0, failures = {}, groups = this.groups.length ? this.groups : group; if ( !_isArray( collection ) ) throw new Violation( this, array, { value: Validator.errorCode.must_be_an_array } ); for ( var i = 0; i < collection.length; i++ ) { result = this.constraint ? validator.validate( collection[ i ], this.constraint, groups ) : validator.validate( collection[ i ], groups ); if ( !_isEmptyObject( result ) ) failures[ count ] = result; count++; } return !_isEmptyObject( failures ) ? failures : true; }; return this; }, Count: function ( count ) { this.__class__ = 'Count'; this.count = count; this.validate = function ( array ) { if ( !_isArray( array ) ) throw new Violation( this, array, { value: Validator.errorCode.must_be_an_array } ); var count = 'function' === typeof this.count ? this.count( array ) : this.count; if ( isNaN( Number( count ) ) ) throw new Error( 'Count must be a valid interger', count ); if ( count !== array.length ) throw new Violation( this, array, { count: count } ); return true; }; return this; }, Email: function () { this.__class__ = 'Email'; this.validate = function ( value ) { var regExp = /^((([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; if ( 'string' !== typeof value ) throw new Violation( this, value, { value: Validator.errorCode.must_be_a_string } ); if ( !regExp.test( value ) ) throw new Violation( this, value ); return true; }; return this; }, Eql: function ( eql ) { this.__class__ = 'Eql'; if ( 'undefined' === typeof eql ) throw new Error( 'Equal must be instanciated with an Array or an Object' ); this.eql = eql; this.validate = function ( value ) { var eql = 'function' === typeof this.eql ? this.eql( value ) : this.eql; if ( !expect.eql( eql, value ) ) throw new Violation( this, value, { eql: eql } ); return true; }; return this; }, EqualTo: function ( reference ) { this.__class__ = 'EqualTo'; if ( 'undefined' === typeof reference ) throw new Error( 'EqualTo must be instanciated with a value or a function' ); this.reference = reference; this.validate = function ( value ) { var reference = 'function' === typeof this.reference ? this.reference( value ) : this.reference; if ( reference !== value ) throw new Violation( this, value, { value: reference } ); return true; }; return this; }, GreaterThan: function ( threshold ) { this.__class__ = 'GreaterThan'; if ( 'undefined' === typeof threshold ) throw new Error( 'Should give a threshold value' ); this.threshold = threshold; this.validate = function ( value ) { if ( '' === value || isNaN( Number( value ) ) ) throw new Violation( this, value, { value: Validator.errorCode.must_be_a_number } ); if ( this.threshold >= value ) throw new Violation( this, value, { threshold: this.threshold } ); return true; }; return this; }, GreaterThanOrEqual: function ( threshold ) { this.__class__ = 'GreaterThanOrEqual'; if ( 'undefined' === typeof threshold ) throw new Error( 'Should give a threshold value' ); this.threshold = threshold; this.validate = function ( value ) { if ( '' === value || isNaN( Number( value ) ) ) throw new Violation( this, value, { value: Validator.errorCode.must_be_a_number } ); if ( this.threshold > value ) throw new Violation( this, value, { threshold: this.threshold } ); return true; }; return this; }, InstanceOf: function ( classRef ) { this.__class__ = 'InstanceOf'; if ( 'undefined' === typeof classRef ) throw new Error( 'InstanceOf must be instanciated with a value' ); this.classRef = classRef; this.validate = function ( value ) { if ( true !== (value instanceof this.classRef) ) throw new Violation( this, value, { classRef: this.classRef } ); return true; }; return this; }, IPv4: function () { this.__class__ = 'IPv4'; this.validate = function ( value ) { var regExp = /^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/; if ( 'string' !== typeof value ) throw new Violation( this, value, { value: Validator.errorCode.must_be_a_string } ); if ( !regExp.test( value ) ) throw new Violation( this, value ); return true; }; return this; }, Length: function ( boundaries ) { this.__class__ = 'Length'; if ( !boundaries.min && !boundaries.max ) throw new Error( 'Lenth assert must be instanciated with a { min: x, max: y } object' ); this.min = boundaries.min; this.max = boundaries.max; this.validate = function ( value ) { if ( 'string' !== typeof value && !_isArray( value ) ) throw new Violation( this, value, { value: Validator.errorCode.must_be_a_string_or_array } ); if ( 'undefined' !== typeof this.min && this.min === this.max && value.length !== this.min ) throw new Violation( this, value, { min: this.min, max: this.max } ); if ( 'undefined' !== typeof this.max && value.length > this.max ) throw new Violation( this, value, { max: this.max } ); if ( 'undefined' !== typeof this.min && value.length < this.min ) throw new Violation( this, value, { min: this.min } ); return true; }; return this; }, LessThan: function ( threshold ) { this.__class__ = 'LessThan'; if ( 'undefined' === typeof threshold ) throw new Error( 'Should give a threshold value' ); this.threshold = threshold; this.validate = function ( value ) { if ( '' === value || isNaN( Number( value ) ) ) throw new Violation( this, value, { value: Validator.errorCode.must_be_a_number } ); if ( this.threshold <= value ) throw new Violation( this, value, { threshold: this.threshold } ); return true; }; return this; }, LessThanOrEqual: function ( threshold ) { this.__class__ = 'LessThanOrEqual'; if ( 'undefined' === typeof threshold ) throw new Error( 'Should give a threshold value' ); this.threshold = threshold; this.validate = function ( value ) { if ( '' === value || isNaN( Number( value ) ) ) throw new Violation( this, value, { value: Validator.errorCode.must_be_a_number } ); if ( this.threshold < value ) throw new Violation( this, value, { threshold: this.threshold } ); return true; }; return this; }, Mac: function () { this.__class__ = 'Mac'; this.validate = function ( value ) { var regExp = /^(?:[0-9A-F]{2}:){5}[0-9A-F]{2}$/i; if ( 'string' !== typeof value ) throw new Violation( this, value, { value: Validator.errorCode.must_be_a_string } ); if ( !regExp.test( value ) ) throw new Violation( this, value ); return true; }; return this; }, NotNull: function () { this.__class__ = 'NotNull'; this.validate = function ( value ) { if ( null === value || 'undefined' === typeof value ) throw new Violation( this, value ); return true; }; return this; }, NotBlank: function () { this.__class__ = 'NotBlank'; this.validate = function ( value ) { if ( 'string' !== typeof value ) throw new Violation( this, value, { value: Validator.errorCode.must_be_a_string } ); if ( '' === value.replace( /^\s+/g, '' ).replace( /\s+$/g, '' ) ) throw new Violation( this, value ); return true; }; return this; }, Null: function () { this.__class__ = 'Null'; this.validate = function ( value ) { if ( null !== value ) throw new Violation( this, value ); return true; }; return this; }, Range: function ( min, max ) { this.__class__ = 'Range'; if ( 'undefined' === typeof min || 'undefined' === typeof max ) throw new Error( 'Range assert expects min and max values' ); this.min = min; this.max = max; this.validate = function ( value ) { try { // validate strings and objects with their Length if ( ( 'string' === typeof value && isNaN( Number( value ) ) ) || _isArray( value ) ) new Assert().Length( { min: this.min, max: this.max } ).validate( value ); // validate numbers with their value else new Assert().GreaterThanOrEqual( this.min ).validate( value ) && new Assert().LessThanOrEqual( this.max ).validate( value ); return true; } catch ( violation ) { throw new Violation( this, value, violation.violation ); } return true; }; return this; }, Regexp: function ( regexp, flag ) { this.__class__ = 'Regexp'; if ( 'undefined' === typeof regexp ) throw new Error( 'You must give a regexp' ); this.regexp = regexp; this.flag = flag || ''; this.validate = function ( value ) { if ( 'string' !== typeof value ) throw new Violation( this, value, { value: Validator.errorCode.must_be_a_string } ); if ( !new RegExp( this.regexp, this.flag ).test( value ) ) throw new Violation( this, value, { regexp: this.regexp, flag: this.flag } ); return true; }; return this; }, Required: function () { this.__class__ = 'Required'; this.validate = function ( value ) { if ( 'undefined' === typeof value ) throw new Violation( this, value ); try { if ( 'string' === typeof value ) new Assert().NotNull().validate( value ) && new Assert().NotBlank().validate( value ); else if ( true === _isArray( value ) ) new Assert().Length( { min: 1 } ).validate( value ); } catch ( violation ) { throw new Violation( this, value ); } return true; }; return this; }, // Unique() or Unique ( { key: foo } ) Unique: function ( object ) { this.__class__ = 'Unique'; if ( 'object' === typeof object ) this.key = object.key; this.validate = function ( array ) { var value, store = []; if ( !_isArray( array ) ) throw new Violation( this, array, { value: Validator.errorCode.must_be_an_array } ); for ( var i = 0; i < array.length; i++ ) { value = 'object' === typeof array[ i ] ? array[ i ][ this.key ] : array[ i ]; if ( 'undefined' === typeof value ) continue; if ( -1 !== store.indexOf( value ) ) throw new Violation( this, array, { value: value } ); store.push( value ); } return true; }; return this; } }; // expose to the world these awesome classes exports.Assert = Assert; exports.Validator = Validator; exports.Violation = Violation; exports.Constraint = Constraint; /** * Some useful object prototypes / functions here */ // IE8<= compatibility // https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/indexOf if (!Array.prototype.indexOf) Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) { if (this === null) { throw new TypeError(); } var t = Object(this); var len = t.length >>> 0; if (len === 0) { return -1; } var n = 0; if (arguments.length > 1) { n = Number(arguments[1]); if (n != n) { // shortcut for verifying if it's NaN n = 0; } else if (n !== 0 && n != Infinity && n != -Infinity) { n = (n > 0 || -1) * Math.floor(Math.abs(n)); } } if (n >= len) { return -1; } var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0); for (; k < len; k++) { if (k in t && t[k] === searchElement) { return k; } } return -1; }; // Test if object is empty, useful for Constraint violations check var _isEmptyObject = function ( obj ) { for ( var property in obj ) return false; return true; }; var _isArray = function ( obj ) { return Object.prototype.toString.call( obj ) === '[object Array]'; }; // https://github.com/LearnBoost/expect.js/blob/master/expect.js var expect = { eql: function ( actual, expected ) { if ( actual === expected ) { return true; } else if ( 'undefined' !== typeof Buffer && Buffer.isBuffer( actual ) && Buffer.isBuffer( expected ) ) { if ( actual.length !== expected.length ) return false; for ( var i = 0; i < actual.length; i++ ) if ( actual[i] !== expected[i] ) return false; return true; } else if ( actual instanceof Date && expected instanceof Date ) { return actual.getTime() === expected.getTime(); } else if ( typeof actual !== 'object' && typeof expected !== 'object' ) { // loosy == return actual == expected; } else { return this.objEquiv(actual, expected); } }, isUndefinedOrNull: function ( value ) { return value === null || typeof value === 'undefined'; }, isArguments: function ( object ) { return Object.prototype.toString.call(object) == '[object Arguments]'; }, keys: function ( obj ) { if ( Object.keys ) return Object.keys( obj ); var keys = []; for ( var i in obj ) if ( Object.prototype.hasOwnProperty.call( obj, i ) ) keys.push(i); return keys; }, objEquiv: function ( a, b ) { if ( this.isUndefinedOrNull( a ) || this.isUndefinedOrNull( b ) ) return false; if ( a.prototype !== b.prototype ) return false; if ( this.isArguments( a ) ) { if ( !this.isArguments( b ) ) return false; return eql( pSlice.call( a ) , pSlice.call( b ) ); } try { var ka = this.keys( a ), kb = this.keys( b ), key, i; if ( ka.length !== kb.length ) return false; ka.sort(); kb.sort(); for ( i = ka.length - 1; i >= 0; i-- ) if ( ka[ i ] != kb[ i ] ) return false; for ( i = ka.length - 1; i >= 0; i-- ) { key = ka[i]; if ( !this.eql( a[ key ], b[ key ] ) ) return false; } return true; } catch ( e ) { return false; } } }; // AMD Compliance if ( "function" === typeof define && define.amd ) { define( 'validator', [],function() { return exports; } ); } } )( 'undefined' === typeof exports ? this[ 'undefined' !== typeof validatorjs_ns ? validatorjs_ns : 'Validator' ] = {} : exports ); var ParsleyValidator = function (validators, catalog) { this.__class__ = 'ParsleyValidator'; this.Validator = Validator; // Default Parsley locale is en this.locale = 'en'; this.init(validators || {}, catalog || {}); }; ParsleyValidator.prototype = { init: function (validators, catalog) { this.catalog = catalog; for (var name in validators) this.addValidator(name, validators[name].fn, validators[name].priority, validators[name].requirementsTransformer); $.emit('parsley:validator:init'); }, // Set new messages locale if we have dictionary loaded in ParsleyConfig.i18n setLocale: function (locale) { if ('undefined' === typeof this.catalog[locale]) throw new Error(locale + ' is not available in the catalog'); this.locale = locale; return this; }, // Add a new messages catalog for a given locale. Set locale for this catalog if set === `true` addCatalog: function (locale, messages, set) { if ('object' === typeof messages) this.catalog[locale] = messages; if (true === set) return this.setLocale(locale); return this; }, // Add a specific message for a given constraint in a given locale addMessage: function (locale, name, message) { if ('undefined' === typeof this.catalog[locale]) this.catalog[locale] = {}; this.catalog[locale][name.toLowerCase()] = message; return this; }, validate: function (value, constraints, priority) { return new this.Validator.Validator().validate.apply(new Validator.Validator(), arguments); }, // Add a new validator addValidator: function (name, fn, priority, requirementsTransformer) { this.validators[name.toLowerCase()] = function (requirements) { return $.extend(new Validator.Assert().Callback(fn, requirements), { priority: priority, requirementsTransformer: requirementsTransformer }); }; return this; }, updateValidator: function (name, fn, priority, requirementsTransformer) { return this.addValidator(name, fn, priority, requirementsTransformer); }, removeValidator: function (name) { delete this.validators[name]; return this; }, getErrorMessage: function (constraint) { var message; // Type constraints are a bit different, we have to match their requirements too to find right error message if ('type' === constraint.name) message = this.catalog[this.locale][constraint.name][constraint.requirements]; else message = this.formatMessage(this.catalog[this.locale][constraint.name], constraint.requirements); return '' !== message ? message : this.catalog[this.locale].defaultMessage; }, // Kind of light `sprintf()` implementation formatMessage: function (string, parameters) { if ('object' === typeof parameters) { for (var i in parameters) string = this.formatMessage(string, parameters[i]); return string; } return 'string' === typeof string ? string.replace(new RegExp('%s', 'i'), parameters) : ''; }, // Here is the Parsley default validators list. // This is basically Validatorjs validators, with different API for some of them // and a Parsley priority set validators: { notblank: function () { return $.extend(new Validator.Assert().NotBlank(), { priority: 2 }); }, required: function () { return $.extend(new Validator.Assert().Required(), { priority: 512 }); }, type: function (type) { var assert; switch (type) { case 'email': assert = new Validator.Assert().Email(); break; // range type just ensure we have a number here case 'range': case 'number': assert = new Validator.Assert().Regexp('^-?(?:\\d+|\\d{1,3}(?:,\\d{3})+)?(?:\\.\\d+)?$'); break; case 'integer': assert = new Validator.Assert().Regexp('^-?\\d+$'); break; case 'digits': assert = new Validator.Assert().Regexp('^\\d+$'); break; case 'alphanum': assert = new Validator.Assert().Regexp('^\\w+$', 'i'); break; case 'url': assert = new Validator.Assert().Regexp('(https?:\\/\\/)?(www\\.)?[-a-zA-Z0-9@:%._\\+~#=]{2,256}\\.[a-z]{2,4}\\b([-a-zA-Z0-9@:%_\\+.~#?&//=]*)', 'i'); break; default: throw new Error('validator type `' + type + '` is not supported'); } return $.extend(assert, { priority: 256 }); }, pattern: function (regexp) { var flags = ''; // Test if RegExp is literal, if not, nothing to be done, otherwise, we need to isolate flags and pattern if (!!(/^\/.*\/(?:[gimy]*)$/.test(regexp))) { // Replace the regexp literal string with the first match group: ([gimy]*) // If no flag is present, this will be a blank string flags = regexp.replace(/.*\/([gimy]*)$/, '$1'); // Again, replace the regexp literal string with the first match group: // everything excluding the opening and closing slashes and the flags regexp = regexp.replace(new RegExp('^/(.*?)/' + flags + '$'), '$1'); } return $.extend(new Validator.Assert().Regexp(regexp, flags), { priority: 64 }); }, minlength: function (value) { return $.extend(new Validator.Assert().Length({ min: value }), { priority: 30, requirementsTransformer: function () { return 'string' === typeof value && !isNaN(value) ? parseInt(value, 10) : value; } }); }, maxlength: function (value) { return $.extend(new Validator.Assert().Length({ max: value }), { priority: 30, requirementsTransformer: function () { return 'string' === typeof value && !isNaN(value) ? parseInt(value, 10) : value; } }); }, length: function (array) { return $.extend(new Validator.Assert().Length({ min: array[0], max: array[1] }), { priority: 32 }); }, mincheck: function (length) { return this.minlength(length); }, maxcheck: function (length) { return this.maxlength(length); }, check: function (array) { return this.length(array); }, min: function (value) { return $.extend(new Validator.Assert().GreaterThanOrEqual(value), { priority: 30, requirementsTransformer: function () { return 'string' === typeof value && !isNaN(value) ? parseInt(value, 10) : value; } }); }, max: function (value) { return $.extend(new Validator.Assert().LessThanOrEqual(value), { priority: 30, requirementsTransformer: function () { return 'string' === typeof value && !isNaN(value) ? parseInt(value, 10) : value; } }); }, range: function (array) { return $.extend(new Validator.Assert().Range(array[0], array[1]), { priority: 32, requirementsTransformer: function () { for (var i = 0; i < array.length; i++) array[i] = 'string' === typeof array[i] && !isNaN(array[i]) ? parseInt(array[i], 10) : array[i]; return array; } }); }, equalto: function (value) { return $.extend(new Validator.Assert().EqualTo(value), { priority: 256, requirementsTransformer: function () { return $(value).length ? $(value).val() : value; } }); } } }; var ParsleyUI = function (options) { this.__class__ = 'ParsleyUI'; }; ParsleyUI.prototype = { listen: function () { $.listen('parsley:form:init', this, this.setupForm); $.listen('parsley:field:init', this, this.setupField); $.listen('parsley:field:validated', this, this.reflow); $.listen('parsley:form:validated', this, this.focus); $.listen('parsley:field:reset', this, this.reset); $.listen('parsley:form:destroy', this, this.destroy); $.listen('parsley:field:destroy', this, this.destroy); return this; }, reflow: function (fieldInstance) { // If this field has not an active UI (case for multiples) don't bother doing something if ('undefined' === typeof fieldInstance._ui || false === fieldInstance._ui.active) return; // Diff between two validation results var diff = this._diff(fieldInstance.validationResult, fieldInstance._ui.lastValidationResult); // Then store current validation result for next reflow fieldInstance._ui.lastValidationResult = fieldInstance.validationResult; // Field have been validated at least once if here. Useful for binded key events.. fieldInstance._ui.validatedOnce = true; // Handle valid / invalid / none field class this.manageStatusClass(fieldInstance); // Add, remove, updated errors messages this.manageErrorsMessages(fieldInstance, diff); // Triggers impl this.actualizeTriggers(fieldInstance); // If field is not valid for the first time, bind keyup trigger to ease UX and quickly inform user if ((diff.kept.length || diff.added.length) && 'undefined' === typeof fieldInstance._ui.failedOnce) this.manageFailingFieldTrigger(fieldInstance); }, // Returns an array of field's error message(s) getErrorsMessages: function (fieldInstance) { // No error message, field is valid if (true === fieldInstance.validationResult) return []; var messages = []; for (var i = 0; i < fieldInstance.validationResult.length; i++) messages.push(this._getErrorMessage(fieldInstance, fieldInstance.validationResult[i].assert)); return messages; }, manageStatusClass: function (fieldInstance) { if (true === fieldInstance.validationResult) this._successClass(fieldInstance); else if (fieldInstance.validationResult.length > 0) this._errorClass(fieldInstance); else this._resetClass(fieldInstance); }, manageErrorsMessages: function (fieldInstance, diff) { if ('undefined' !== typeof fieldInstance.options.errorsMessagesDisabled) return; // Case where we have errorMessage option that configure an unique field error message, regardless failing validators if ('undefined' !== typeof fieldInstance.options.errorMessage) { if ((diff.added.length || diff.kept.length)) { if (0 === fieldInstance._ui.$errorsWrapper.find('.parsley-custom-error-message').length) fieldInstance._ui.$errorsWrapper .append($(fieldInstance.options.errorTemplate) .addClass('parsley-custom-error-message')); return fieldInstance._ui.$errorsWrapper .addClass('filled') .find('.parsley-custom-error-message') .html(fieldInstance.options.errorMessage); } return fieldInstance._ui.$errorsWrapper .removeClass('filled') .find('.parsley-custom-error-message') .remove(); } // Show, hide, update failing constraints messages for (var i = 0; i < diff.removed.length; i++) this.removeError(fieldInstance, diff.removed[i].assert.name, true); for (i = 0; i < diff.added.length; i++) this.addError(fieldInstance, diff.added[i].assert.name, undefined, diff.added[i].assert, true); for (i = 0; i < diff.kept.length; i++) this.updateError(fieldInstance, diff.kept[i].assert.name, undefined, diff.kept[i].assert, true); }, // TODO: strange API here, intuitive for manual usage with addError(pslyInstance, 'foo', 'bar') // but a little bit complex for above internal usage, with forced undefined parametter.. addError: function (fieldInstance, name, message, assert, doNotUpdateClass) { fieldInstance._ui.$errorsWrapper .addClass('filled') .append($(fieldInstance.options.errorTemplate) .addClass('parsley-' + name) .html(message || this._getErrorMessage(fieldInstance, assert))); if (true !== doNotUpdateClass) this._errorClass(fieldInstance); }, // Same as above updateError: function (fieldInstance, name, message, assert, doNotUpdateClass) { fieldInstance._ui.$errorsWrapper .addClass('filled') .find('.parsley-' + name) .html(message || this._getErrorMessage(fieldInstance, assert)); if (true !== doNotUpdateClass) this._errorClass(fieldInstance); }, // Same as above twice removeError: function (fieldInstance, name, doNotUpdateClass) { fieldInstance._ui.$errorsWrapper .removeClass('filled') .find('.parsley-' + name) .remove(); // edge case possible here: remove a standard Parsley error that is still failing in fieldInstance.validationResult // but highly improbable cuz' manually removing a well Parsley handled error makes no sense. if (true !== doNotUpdateClass) this.manageStatusClass(fieldInstance); }, focus: function (formInstance) { if (true === formInstance.validationResult || 'none' === formInstance.options.focus) return formInstance._focusedField = null; formInstance._focusedField = null; for (var i = 0; i < formInstance.fields.length; i++) if (true !== formInstance.fields[i].validationResult && formInstance.fields[i].validationResult.length > 0 && 'undefined' === typeof formInstance.fields[i].options.noFocus) { if ('first' === formInstance.options.focus) { formInstance._focusedField = formInstance.fields[i].$element; return formInstance._focusedField.focus(); } formInstance._focusedField = formInstance.fields[i].$element; } if (null === formInstance._focusedField) return null; return formInstance._focusedField.focus(); }, _getErrorMessage: function (fieldInstance, constraint) { var customConstraintErrorMessage = constraint.name + 'Message'; if ('undefined' !== typeof fieldInstance.options[customConstraintErrorMessage]) return window.ParsleyValidator.formatMessage(fieldInstance.options[customConstraintErrorMessage], constraint.requirements); return window.ParsleyValidator.getErrorMessage(constraint); }, _diff: function (newResult, oldResult, deep) { var added = [], kept = []; for (var i = 0; i < newResult.length; i++) { var found = false; for (var j = 0; j < oldResult.length; j++) if (newResult[i].assert.name === oldResult[j].assert.name) { found = true; break; } if (found) kept.push(newResult[i]); else added.push(newResult[i]); } return { kept: kept, added: added, removed: !deep ? this._diff(oldResult, newResult, true).added : [] }; }, setupForm: function (formInstance) { formInstance.$element.on('submit.Parsley', false, $.proxy(formInstance.onSubmitValidate, formInstance)); // UI could be disabled if (false === formInstance.options.uiEnabled) return; formInstance.$element.attr('novalidate', ''); }, setupField: function (fieldInstance) { var _ui = { active: false }; // UI could be disabled if (false === fieldInstance.options.uiEnabled) return; _ui.active = true; // Give field its Parsley id in DOM fieldInstance.$element.attr(fieldInstance.options.namespace + 'id', fieldInstance.__id__); /** Generate important UI elements and store them in fieldInstance **/ // $errorClassHandler is the $element that woul have parsley-error and parsley-success classes _ui.$errorClassHandler = this._manageClassHandler(fieldInstance); // $errorsWrapper is a div that would contain the various field errors, it will be appended into $errorsContainer _ui.errorsWrapperId = 'parsley-id-' + ('undefined' !== typeof fieldInstance.options.multiple ? 'multiple-' + fieldInstance.options.multiple : fieldInstance.__id__); _ui.$errorsWrapper = $(fieldInstance.options.errorsWrapper).attr('id', _ui.errorsWrapperId); // ValidationResult UI storage to detect what have changed bwt two validations, and update DOM accordingly _ui.lastValidationResult = []; _ui.validatedOnce = false; _ui.validationInformationVisible = false; // Store it in fieldInstance for later fieldInstance._ui = _ui; /** Mess with DOM now **/ this._insertErrorWrapper(fieldInstance); // Bind triggers first time this.actualizeTriggers(fieldInstance); }, // Determine which element will have `parsley-error` and `parsley-success` classes _manageClassHandler: function (fieldInstance) { // An element selector could be passed through DOM with `data-parsley-class-handler=#foo` if ('string' === typeof fieldInstance.options.classHandler && $(fieldInstance.options.classHandler).length) return $(fieldInstance.options.classHandler); // Class handled could also be determined by function given in Parsley options var $handler = fieldInstance.options.classHandler(fieldInstance); // If this function returned a valid existing DOM element, go for it if ('undefined' !== typeof $handler && $handler.length) return $handler; // Otherwise, if simple element (input, texatrea, select..) it will perfectly host the classes if ('undefined' === typeof fieldInstance.options.multiple || fieldInstance.$element.is('select')) return fieldInstance.$element; // But if multiple element (radio, checkbox), that would be their parent return fieldInstance.$element.parent(); }, _insertErrorWrapper: function (fieldInstance) { var $errorsContainer; if ('string' === typeof fieldInstance.options.errorsContainer) { if ($(fieldInstance.options.errorsContainer).length) return $(fieldInstance.options.errorsContainer).append(fieldInstance._ui.$errorsWrapper); else if (window.console && window.console.warn) window.console.warn('The errors container `' + fieldInstance.options.errorsContainer + '` does not exist in DOM'); } else if ('function' === typeof fieldInstance.options.errorsContainer) $errorsContainer = fieldInstance.options.errorsContainer(fieldInstance); if ('undefined' !== typeof $errorsContainer && $errorsContainer.length) return $errorsContainer.append(fieldInstance._ui.$errorsWrapper); return 'undefined' === typeof fieldInstance.options.multiple ? fieldInstance.$element.after(fieldInstance._ui.$errorsWrapper) : fieldInstance.$element.parent().after(fieldInstance._ui.$errorsWrapper); }, actualizeTriggers: function (fieldInstance) { var that = this; // Remove Parsley events already binded on this field if (fieldInstance.options.multiple) $('[' + fieldInstance.options.namespace + 'multiple="' + fieldInstance.options.multiple + '"]').each(function () { $(this).off('.Parsley'); }); else fieldInstance.$element.off('.Parsley'); // If no trigger is set, all good if (false === fieldInstance.options.trigger) return; var triggers = fieldInstance.options.trigger.replace(/^\s+/g , '').replace(/\s+$/g , ''); if ('' === triggers) return; // Bind fieldInstance.eventValidate if exists (for parsley.ajax for example), ParsleyUI.eventValidate otherwise if (fieldInstance.options.multiple) $('[' + fieldInstance.options.namespace + 'multiple="' + fieldInstance.options.multiple + '"]').each(function () { $(this).on( triggers.split(' ').join('.Parsley ') + '.Parsley', false, $.proxy('function' === typeof fieldInstance.eventValidate ? fieldInstance.eventValidate : that.eventValidate, fieldInstance)); }); else fieldInstance.$element .on( triggers.split(' ').join('.Parsley ') + '.Parsley', false, $.proxy('function' === typeof fieldInstance.eventValidate ? fieldInstance.eventValidate : this.eventValidate, fieldInstance)); }, // Called through $.proxy with fieldInstance. `this` context is ParsleyField eventValidate: function(event) { // For keyup, keypress, keydown.. events that could be a little bit obstrusive // do not validate if val length < min threshold on first validation. Once field have been validated once and info // about success or failure have been displayed, always validate with this trigger to reflect every yalidation change. if (new RegExp('key').test(event.type)) if (!this._ui.validationInformationVisible && this.getValue().length <= this.options.validationThreshold) return; this._ui.validatedOnce = true; this.validate(); }, manageFailingFieldTrigger: function (fieldInstance) { fieldInstance._ui.failedOnce = true; // Radio and checkboxes fields must bind every field multiple if (fieldInstance.options.multiple) $('[' + fieldInstance.options.namespace + 'multiple="' + fieldInstance.options.multiple + '"]').each(function () { if (!new RegExp('change', 'i').test($(this).parsley().options.trigger || '')) return $(this).on('change.ParsleyFailedOnce', false, $.proxy(fieldInstance.validate, fieldInstance)); }); // Select case if (fieldInstance.$element.is('select')) if (!new RegExp('change', 'i').test(fieldInstance.options.trigger || '')) return fieldInstance.$element.on('change.ParsleyFailedOnce', false, $.proxy(fieldInstance.validate, fieldInstance)); // All other inputs fields if (!new RegExp('keyup', 'i').test(fieldInstance.options.trigger || '')) return fieldInstance.$element.on('keyup.ParsleyFailedOnce', false, $.proxy(fieldInstance.validate, fieldInstance)); }, reset: function (parsleyInstance) { // Reset all event listeners parsleyInstance.$element.off('.Parsley'); parsleyInstance.$element.off('.ParsleyFailedOnce'); // Nothing to do if UI never initialized for this field if ('undefined' === typeof parsleyInstance._ui) return; if ('ParsleyForm' === parsleyInstance.__class__) return; // Reset all errors' li parsleyInstance._ui.$errorsWrapper.children().each(function () { $(this).remove(); }); // Reset validation class this._resetClass(parsleyInstance); // Reset validation flags and last validation result parsleyInstance._ui.validatedOnce = false; parsleyInstance._ui.lastValidationResult = []; parsleyInstance._ui.validationInformationVisible = false; }, destroy: function (parsleyInstance) { this.reset(parsleyInstance); if ('ParsleyForm' === parsleyInstance.__class__) return; if ('undefined' !== typeof parsleyInstance._ui) parsleyInstance._ui.$errorsWrapper.remove(); delete parsleyInstance._ui; }, _successClass: function (fieldInstance) { fieldInstance._ui.validationInformationVisible = true; fieldInstance._ui.$errorClassHandler.removeClass(fieldInstance.options.errorClass).addClass(fieldInstance.options.successClass); }, _errorClass: function (fieldInstance) { fieldInstance._ui.validationInformationVisible = true; fieldInstance._ui.$errorClassHandler.removeClass(fieldInstance.options.successClass).addClass(fieldInstance.options.errorClass); }, _resetClass: function (fieldInstance) { fieldInstance._ui.$errorClassHandler.removeClass(fieldInstance.options.successClass).removeClass(fieldInstance.options.errorClass); } }; var ParsleyOptionsFactory = function (defaultOptions, globalOptions, userOptions, namespace) { this.__class__ = 'OptionsFactory'; this.__id__ = ParsleyUtils.hash(4); this.formOptions = null; this.fieldOptions = null; this.staticOptions = $.extend(true, {}, defaultOptions, globalOptions, userOptions, { namespace: namespace }); }; ParsleyOptionsFactory.prototype = { get: function (parsleyInstance) { if ('undefined' === typeof parsleyInstance.__class__) throw new Error('Parsley Instance expected'); switch (parsleyInstance.__class__) { case 'Parsley': return this.staticOptions; case 'ParsleyForm': return this.getFormOptions(parsleyInstance); case 'ParsleyField': case 'ParsleyFieldMultiple': return this.getFieldOptions(parsleyInstance); default: throw new Error('Instance ' + parsleyInstance.__class__ + ' is not supported'); } }, getFormOptions: function (formInstance) { this.formOptions = ParsleyUtils.attr(formInstance.$element, this.staticOptions.namespace); // not deep extend, since formOptions is a 1 level deep object return $.extend({}, this.staticOptions, this.formOptions); }, getFieldOptions: function (fieldInstance) { this.fieldOptions = ParsleyUtils.attr(fieldInstance.$element, this.staticOptions.namespace); if (null === this.formOptions && 'undefined' !== typeof fieldInstance.parent) this.formOptions = this.getFormOptions(fieldInstance.parent); // not deep extend, since formOptions and fieldOptions is a 1 level deep object return $.extend({}, this.staticOptions, this.formOptions, this.fieldOptions); } }; var ParsleyForm = function (element, OptionsFactory) { this.__class__ = 'ParsleyForm'; this.__id__ = ParsleyUtils.hash(4); if ('OptionsFactory' !== ParsleyUtils.get(OptionsFactory, '__class__')) throw new Error('You must give an OptionsFactory instance'); this.OptionsFactory = OptionsFactory; this.$element = $(element); this.validationResult = null; this.options = this.OptionsFactory.get(this); }; ParsleyForm.prototype = { onSubmitValidate: function (event) { this.validate(undefined, undefined, event); // prevent form submission if validation fails if (false === this.validationResult && event instanceof $.Event) { event.stopImmediatePropagation(); event.preventDefault(); } return this; }, // @returns boolean validate: function (group, force, event) { this.submitEvent = event; this.validationResult = true; var fieldValidationResult = []; // Refresh form DOM options and form's fields that could have changed this._refreshFields(); $.emit('parsley:form:validate', this); // loop through fields to validate them one by one for (var i = 0; i < this.fields.length; i++) { // do not validate a field if not the same as given validation group if (group && group !== this.fields[i].options.group) continue; fieldValidationResult = this.fields[i].validate(force); if (true !== fieldValidationResult && fieldValidationResult.length > 0 && this.validationResult) this.validationResult = false; } $.emit('parsley:form:validated', this); return this.validationResult; }, // Iterate over refreshed fields, and stop on first failure isValid: function (group, force) { this._refreshFields(); for (var i = 0; i < this.fields.length; i++) { // do not validate a field if not the same as given validation group if (group && group !== this.fields[i].options.group) continue; if (false === this.fields[i].isValid(force)) return false; } return true; }, _refreshFields: function () { return this.actualizeOptions()._bindFields(); }, _bindFields: function () { var self = this; this.fields = []; this.fieldsMappedById = {}; this.$element.find(this.options.inputs).each(function () { var fieldInstance = new window.Parsley(this, {}, self); // Only add valid and not excluded `ParsleyField` and `ParsleyFieldMultiple` children if (('ParsleyField' === fieldInstance.__class__ || 'ParsleyFieldMultiple' === fieldInstance.__class__) && !fieldInstance.$element.is(fieldInstance.options.excluded)) if ('undefined' === typeof self.fieldsMappedById[fieldInstance.__class__ + '-' + fieldInstance.__id__]) { self.fieldsMappedById[fieldInstance.__class__ + '-' + fieldInstance.__id__] = fieldInstance; self.fields.push(fieldInstance); } }); return this; } }; var ConstraintFactory = function (parsleyField, name, requirements, priority, isDomConstraint) { if (!new RegExp('ParsleyField').test(ParsleyUtils.get(parsleyField, '__class__'))) throw new Error('ParsleyField or ParsleyFieldMultiple instance expected'); if ('function' !== typeof window.ParsleyValidator.validators[name] && 'Assert' !== window.ParsleyValidator.validators[name](requirements).__parentClass__) throw new Error('Valid validator expected'); var getPriority = function (parsleyField, name) { if ('undefined' !== typeof parsleyField.options[name + 'Priority']) return parsleyField.options[name + 'Priority']; return ParsleyUtils.get(window.ParsleyValidator.validators[name](requirements), 'priority') || 2; }; priority = priority || getPriority(parsleyField, name); // If validator have a requirementsTransformer, execute it if ('function' === typeof window.ParsleyValidator.validators[name](requirements).requirementsTransformer) requirements = window.ParsleyValidator.validators[name](requirements).requirementsTransformer(); return $.extend(window.ParsleyValidator.validators[name](requirements), { name: name, requirements: requirements, priority: priority, groups: [priority], isDomConstraint: isDomConstraint || ParsleyUtils.attr(parsleyField.$element, parsleyField.options.namespace, name) }); }; var ParsleyField = function (field, OptionsFactory, parsleyFormInstance) { this.__class__ = 'ParsleyField'; this.__id__ = ParsleyUtils.hash(4); this.$element = $(field); // If we have a parent `ParsleyForm` instance given, use its `OptionsFactory`, and save parent if ('undefined' !== typeof parsleyFormInstance) { this.parent = parsleyFormInstance; this.OptionsFactory = this.parent.OptionsFactory; this.options = this.OptionsFactory.get(this); // Else, take the `Parsley` one } else { this.OptionsFactory = OptionsFactory; this.options = this.OptionsFactory.get(this); } // Initialize some properties this.constraints = []; this.constraintsByName = {}; this.validationResult = []; // Bind constraints this._bindConstraints(); }; ParsleyField.prototype = { // # Public API // Validate field and $.emit some events for mainly `ParsleyUI` // @returns validationResult: // - `true` if all constraint passes // - `[]` if not required field and empty (not validated) // - `[Violation, [Violation..]]` if there were validation errors validate: function (force) { this.value = this.getValue(); // Field Validate event. `this.value` could be altered for custom needs $.emit('parsley:field:validate', this); $.emit('parsley:field:' + (this.isValid(force, this.value) ? 'success' : 'error'), this); // Field validated event. `this.validationResult` could be altered for custom needs too $.emit('parsley:field:validated', this); return this.validationResult; }, // Just validate field. Do not trigger any event // Same @return as `validate()` isValid: function (force, value) { // Recompute options and rebind constraints to have latest changes this.refreshConstraints(); // Sort priorities to validate more important first var priorities = this._getConstraintsSortedPriorities(); // Value could be passed as argument, needed to add more power to 'parsley:field:validate' value = value || this.getValue(); // If a field is empty and not required, leave it alone, it's just fine // Except if `data-parsley-validate-if-empty` explicitely added, useful for some custom validators if (0 === value.length && !this._isRequired() && 'undefined' === typeof this.options.validateIfEmpty && true !== force) return this.validationResult = []; // If we want to validate field against all constraints, just call Validator and let it do the job if (false === this.options.priorityEnabled) return true === (this.validationResult = this.validateThroughValidator(value, this.constraints, 'Any')); // Else, iterate over priorities one by one, and validate related asserts one by one for (var i = 0; i < priorities.length; i++) if (true !== (this.validationResult = this.validateThroughValidator(value, this.constraints, priorities[i]))) return false; return true; }, // @returns Parsley field computed value that could be overrided or configured in DOM getValue: function () { var value; // Value could be overriden in DOM if ('undefined' !== typeof this.options.value) value = this.options.value; else value = this.$element.val(); // Handle wrong DOM or configurations if ('undefined' === typeof value || null === value) return ''; // Use `data-parsley-trim-value="true"` to auto trim inputs entry if (true === this.options.trimValue) return value.replace(/^\s+|\s+$/g, ''); return value; }, // Actualize options that could have change since previous validation // Re-bind accordingly constraints (could be some new, removed or updated) refreshConstraints: function () { return this.actualizeOptions()._bindConstraints(); }, /** * Add a new constraint to a field * * @method addConstraint * @param {String} name * @param {Mixed} requirements optional * @param {Number} priority optional * @param {Boolean} isDomConstraint optional */ addConstraint: function (name, requirements, priority, isDomConstraint) { name = name.toLowerCase(); if ('function' === typeof window.ParsleyValidator.validators[name]) { var constraint = new ConstraintFactory(this, name, requirements, priority, isDomConstraint); // if constraint already exist, delete it and push new version if ('undefined' !== this.constraintsByName[constraint.name]) this.removeConstraint(constraint.name); this.constraints.push(constraint); this.constraintsByName[constraint.name] = constraint; } return this; }, // Remove a constraint removeConstraint: function (name) { for (var i = 0; i < this.constraints.length; i++) if (name === this.constraints[i].name) { this.constraints.splice(i, 1); break; } return this; }, // Update a constraint (Remove + re-add) updateConstraint: function (name, parameters, priority) { return this.removeConstraint(name) .addConstraint(name, parameters, priority); }, // # Internals // Internal only. // Bind constraints from config + options + DOM _bindConstraints: function () { var constraints = []; // clean all existing DOM constraints to only keep javascript user constraints for (var i = 0; i < this.constraints.length; i++) if (false === this.constraints[i].isDomConstraint) constraints.push(this.constraints[i]); this.constraints = constraints; // then re-add Parsley DOM-API constraints for (var name in this.options) this.addConstraint(name, this.options[name]); // finally, bind special HTML5 constraints return this._bindHtml5Constraints(); }, // Internal only. // Bind specific HTML5 constraints to be HTML5 compliant _bindHtml5Constraints: function () { // html5 required if (this.$element.hasClass('required') || this.$element.attr('required')) this.addConstraint('required', true, undefined, true); // html5 pattern if ('string' === typeof this.$element.attr('pattern')) this.addConstraint('pattern', this.$element.attr('pattern'), undefined, true); // range if ('undefined' !== typeof this.$element.attr('min') && 'undefined' !== typeof this.$element.attr('max')) this.addConstraint('range', [this.$element.attr('min'), this.$element.attr('max')], undefined, true); // HTML5 min else if ('undefined' !== typeof this.$element.attr('min')) this.addConstraint('min', this.$element.attr('min'), undefined, true); // HTML5 max else if ('undefined' !== typeof this.$element.attr('max')) this.addConstraint('max', this.$element.attr('max'), undefined, true); // html5 types var type = this.$element.attr('type'); if ('undefined' === typeof type) return this; // Small special case here for HTML5 number, that is in fact an integer validator if ('number' === type) return this.addConstraint('type', 'integer', undefined, true); // Regular other HTML5 supported types else if (new RegExp(type, 'i').test('email url range')) return this.addConstraint('type', type, undefined, true); return this; }, // Internal only. // Field is required if have required constraint without `false` value _isRequired: function () { if ('undefined' === typeof this.constraintsByName.required) return false; return false !== this.constraintsByName.required.requirements; }, // Internal only. // Sort constraints by priority DESC _getConstraintsSortedPriorities: function () { var priorities = []; // Create array unique of priorities for (var i = 0; i < this.constraints.length; i++) if (-1 === priorities.indexOf(this.constraints[i].priority)) priorities.push(this.constraints[i].priority); // Sort them by priority DESC priorities.sort(function (a, b) { return b - a; }); return priorities; } }; var ParsleyMultiple = function () { this.__class__ = 'ParsleyFieldMultiple'; }; ParsleyMultiple.prototype = { // Add new `$element` sibling for multiple field addElement: function ($element) { this.$elements.push($element); return this; }, // See `ParsleyField.refreshConstraints()` refreshConstraints: function () { var fieldConstraints; this.constraints = []; // Select multiple special treatment if (this.$element.is('select')) { this.actualizeOptions()._bindConstraints(); return this; } // Gather all constraints for each input in the multiple group for (var i = 0; i < this.$elements.length; i++) { // Check if element have not been dynamically removed since last binding if (!$('html').has(this.$elements[i]).length) { this.$elements.splice(i, 1); continue; } fieldConstraints = this.$elements[i].data('ParsleyFieldMultiple').refreshConstraints().constraints; for (var j = 0; j < fieldConstraints.length; j++) this.addConstraint(fieldConstraints[j].name, fieldConstraints[j].requirements, fieldConstraints[j].priority, fieldConstraints[j].isDomConstraint); } return this; }, // See `ParsleyField.getValue()` getValue: function () { // Value could be overriden in DOM if ('undefined' !== typeof this.options.value) return this.options.value; // Radio input case if (this.$element.is('input[type=radio]')) return $('[' + this.options.namespace + 'multiple="' + this.options.multiple + '"]:checked').val() || ''; // checkbox input case if (this.$element.is('input[type=checkbox]')) { var values = []; $('[' + this.options.namespace + 'multiple="' + this.options.multiple + '"]:checked').each(function () { values.push($(this).val()); }); return values.length ? values : []; } // Select multiple case if (this.$element.is('select') && null === this.$element.val()) return []; // Default case that should never happen return this.$element.val(); }, _init: function (multiple) { this.$elements = [this.$element]; this.options.multiple = multiple; return this; } }; var o = $({}), subscribed = {}; // $.listen(name, callback); // $.listen(name, context, callback); $.listen = function (name) { if ('undefined' === typeof subscribed[name]) subscribed[name] = []; if ('function' === typeof arguments[1]) return subscribed[name].push({ fn: arguments[1] }); if ('object' === typeof arguments[1] && 'function' === typeof arguments[2]) return subscribed[name].push({ fn: arguments[2], ctxt: arguments[1] }); throw new Error('Wrong parameters'); }; $.listenTo = function (instance, name, fn) { if ('undefined' === typeof subscribed[name]) subscribed[name] = []; if (!(instance instanceof ParsleyField) && !(instance instanceof ParsleyForm)) throw new Error('Must give Parsley instance'); if ('string' !== typeof name || 'function' !== typeof fn) throw new Error('Wrong parameters'); subscribed[name].push({ instance: instance, fn: fn }); }; $.unsubscribe = function (name, fn) { if ('undefined' === typeof subscribed[name]) return; if ('string' !== typeof name || 'function' !== typeof fn) throw new Error('Wrong arguments'); for (var i = 0; i < subscribed[name].length; i++) if (subscribed[name][i].fn === fn) return subscribed[name].splice(i, 1); }; $.unsubscribeTo = function (instance, name) { if ('undefined' === typeof subscribed[name]) return; if (!(instance instanceof ParsleyField) && !(instance instanceof ParsleyForm)) throw new Error('Must give Parsley instance'); for (var i = 0; i < subscribed[name].length; i++) if ('undefined' !== typeof subscribed[name][i].instance && subscribed[name][i].instance.__id__ === instance.__id__) return subscribed[name].splice(i, 1); }; $.unsubscribeAll = function (name) { if ('undefined' === typeof subscribed[name]) return; delete subscribed[name]; }; // $.emit(name [, arguments...]); // $.emit(name, instance [, arguments..]); $.emit = function (name, instance) { if ('undefined' === typeof subscribed[name]) return; // loop through registered callbacks for this event for (var i = 0; i < subscribed[name].length; i++) { // if instance is not registered, simple emit if ('undefined' === typeof subscribed[name][i].instance) { subscribed[name][i].fn.apply('undefined' !== typeof subscribed[name][i].ctxt ? subscribed[name][i].ctxt : o, Array.prototype.slice.call(arguments, 1)); continue; } // if instance registered but no instance given for the emit, continue if (!(instance instanceof ParsleyField) && !(instance instanceof ParsleyForm)) continue; // if instance is registered and same id, emit if (subscribed[name][i].instance.__id__ === instance.__id__) { subscribed[name][i].fn.apply(o, Array.prototype.slice.call(arguments, 1)); continue; } // if registered instance is a Form and fired one is a Field, loop over all its fields and emit if field found if (subscribed[name][i].instance instanceof ParsleyForm && instance instanceof ParsleyField) for (var j = 0; j < subscribed[name][i].instance.fields.length; j++) if (subscribed[name][i].instance.fields[j].__id__ === instance.__id__) { subscribed[name][i].fn.apply(o, Array.prototype.slice.call(arguments, 1)); continue; } } }; $.subscribed = function () { return subscribed; }; // ParsleyConfig definition if not already set window.ParsleyConfig = window.ParsleyConfig || {}; window.ParsleyConfig.i18n = window.ParsleyConfig.i18n || {}; // Define then the messages window.ParsleyConfig.i18n.en = $.extend(window.ParsleyConfig.i18n.en || {}, { defaultMessage: "This value seems to be invalid.", type: { email: "This value should be a valid email.", url: "This value should be a valid url.", number: "This value should be a valid number.", integer: "This value should be a valid integer.", digits: "This value should be digits.", alphanum: "This value should be alphanumeric." }, notblank: "This value should not be blank.", required: "This value is required.", pattern: "This value seems to be invalid.", min: "This value should be greater than or equal to %s.", max: "This value should be lower than or equal to %s.", range: "This value should be between %s and %s.", minlength: "This value is too short. It should have %s characters or more.", maxlength: "This value is too long. It should have %s characters or fewer.", length: "This value length is invalid. It should be between %s and %s characters long.", mincheck: "You must select at least %s choices.", maxcheck: "You must select %s choices or fewer.", check: "You must select between %s and %s choices.", equalto: "This value should be the same." }); // If file is loaded after Parsley main file, auto-load locale if ('undefined' !== typeof window.ParsleyValidator) window.ParsleyValidator.addCatalog('en', window.ParsleyConfig.i18n.en, true); // Parsley.js 2.0.3 // http://parsleyjs.org // (c) 20012-2014 Guillaume Potier, Wisembly // Parsley may be freely distributed under the MIT license. // ### Parsley factory var Parsley = function (element, options, parsleyFormInstance) { this.__class__ = 'Parsley'; this.__version__ = '2.0.3'; this.__id__ = ParsleyUtils.hash(4); // Parsley must be instanciated with a DOM element or jQuery $element if ('undefined' === typeof element) throw new Error('You must give an element'); if ('undefined' !== typeof parsleyFormInstance && 'ParsleyForm' !== parsleyFormInstance.__class__) throw new Error('Parent instance must be a ParsleyForm instance'); return this.init($(element), options, parsleyFormInstance); }; Parsley.prototype = { init: function ($element, options, parsleyFormInstance) { if (!$element.length) throw new Error('You must bind Parsley on an existing element.'); this.$element = $element; // If element have already been binded, returns its saved Parsley instance if (this.$element.data('Parsley')) { var savedparsleyFormInstance = this.$element.data('Parsley'); // If saved instance have been binded without a ParsleyForm parent and there is one given in this call, add it if ('undefined' !== typeof parsleyFormInstance) savedparsleyFormInstance.parent = parsleyFormInstance; return savedparsleyFormInstance; } // Handle 'static' options this.OptionsFactory = new ParsleyOptionsFactory(ParsleyDefaults, ParsleyUtils.get(window, 'ParsleyConfig') || {}, options, this.getNamespace(options)); this.options = this.OptionsFactory.get(this); // A ParsleyForm instance is obviously a `<form>` elem but also every node that is not an input and have `data-parsley-validate` attribute if (this.$element.is('form') || (ParsleyUtils.attr(this.$element, this.options.namespace, 'validate') && !this.$element.is(this.options.inputs))) return this.bind('parsleyForm'); // Every other supported element and not excluded element is binded as a `ParsleyField` or `ParsleyFieldMultiple` else if (this.$element.is(this.options.inputs) && !this.$element.is(this.options.excluded)) return this.isMultiple() ? this.handleMultiple(parsleyFormInstance) : this.bind('parsleyField', parsleyFormInstance); return this; }, isMultiple: function () { return (this.$element.is('input[type=radio], input[type=checkbox]') && 'undefined' === typeof this.options.multiple) || (this.$element.is('select') && 'undefined' !== typeof this.$element.attr('multiple')); }, // Multiples fields are a real nightmare :( // Maybe some refacto would be appreciated here.. handleMultiple: function (parsleyFormInstance) { var that = this, name, multiple, parsleyMultipleInstance; // Get parsleyFormInstance options if exist, mixed with element attributes this.options = $.extend(this.options, parsleyFormInstance ? parsleyFormInstance.OptionsFactory.get(parsleyFormInstance) : {}, ParsleyUtils.attr(this.$element, this.options.namespace)); // Handle multiple name if (this.options.multiple) multiple = this.options.multiple; else if ('undefined' !== typeof this.$element.attr('name') && this.$element.attr('name').length) multiple = name = this.$element.attr('name'); else if ('undefined' !== typeof this.$element.attr('id') && this.$element.attr('id').length) multiple = this.$element.attr('id'); // Special select multiple input if (this.$element.is('select') && 'undefined' !== typeof this.$element.attr('multiple')) { return this.bind('parsleyFieldMultiple', parsleyFormInstance, multiple || this.__id__); // Else for radio / checkboxes, we need a `name` or `data-parsley-multiple` to properly bind it } else if ('undefined' === typeof multiple) { if (window.console && window.console.warn) window.console.warn('To be binded by Parsley, a radio, a checkbox and a multiple select input must have either a name or a multiple option.', this.$element); return this; } // Remove special chars multiple = multiple.replace(/(:|\.|\[|\]|\$)/g, ''); // Add proper `data-parsley-multiple` to siblings if we have a valid multiple name if ('undefined' !== typeof name) { $('input[name="' + name + '"]').each(function () { if ($(this).is('input[type=radio], input[type=checkbox]')) $(this).attr(that.options.namespace + 'multiple', multiple); }); } // Check here if we don't already have a related multiple instance saved if ($('[' + this.options.namespace + 'multiple=' + multiple +']').length) { for (var i = 0; i < $('[' + this.options.namespace + 'multiple=' + multiple +']').length; i++) { if ('undefined' !== typeof $($('[' + this.options.namespace + 'multiple=' + multiple +']').get(i)).data('Parsley')) { parsleyMultipleInstance = $($('[' + this.options.namespace + 'multiple=' + multiple +']').get(i)).data('Parsley'); if (!this.$element.data('ParsleyFieldMultiple')) { parsleyMultipleInstance.addElement(this.$element); this.$element.attr(this.options.namespace + 'id', parsleyMultipleInstance.__id__); } break; } } } // Create a secret ParsleyField instance for every multiple field. It would be stored in `data('ParsleyFieldMultiple')` // And would be useful later to access classic `ParsleyField` stuff while being in a `ParsleyFieldMultiple` instance this.bind('parsleyField', parsleyFormInstance, multiple, true); return parsleyMultipleInstance || this.bind('parsleyFieldMultiple', parsleyFormInstance, multiple); }, // Retrieve namespace used for DOM-API getNamespace: function (options) { // `data-parsley-namespace=<namespace>` if ('undefined' !== typeof this.$element.data('parsleyNamespace')) return this.$element.data('parsleyNamespace'); if ('undefined' !== typeof ParsleyUtils.get(options, 'namespace')) return options.namespace; if ('undefined' !== typeof ParsleyUtils.get(window, 'ParsleyConfig.namespace')) return window.ParsleyConfig.namespace; return ParsleyDefaults.namespace; }, // Return proper `ParsleyForm`, `ParsleyField` or `ParsleyFieldMultiple` bind: function (type, parentParsleyFormInstance, multiple, doNotStore) { var parsleyInstance; switch (type) { case 'parsleyForm': parsleyInstance = $.extend( new ParsleyForm(this.$element, this.OptionsFactory), new ParsleyAbstract(), window.ParsleyExtend )._bindFields(); break; case 'parsleyField': parsleyInstance = $.extend( new ParsleyField(this.$element, this.OptionsFactory, parentParsleyFormInstance), new ParsleyAbstract(), window.ParsleyExtend ); break; case 'parsleyFieldMultiple': parsleyInstance = $.extend( new ParsleyField(this.$element, this.OptionsFactory, parentParsleyFormInstance), new ParsleyAbstract(), new ParsleyMultiple(), window.ParsleyExtend )._init(multiple); break; default: throw new Error(type + 'is not a supported Parsley type'); } if ('undefined' !== typeof multiple) ParsleyUtils.setAttr(this.$element, this.options.namespace, 'multiple', multiple); if ('undefined' !== typeof doNotStore) { this.$element.data('ParsleyFieldMultiple', parsleyInstance); return parsleyInstance; } // Store instance if `ParsleyForm`, `ParsleyField` or `ParsleyFieldMultiple` if (new RegExp('ParsleyF', 'i').test(parsleyInstance.__class__)) { // Store for later access the freshly binded instance in DOM element itself using jQuery `data()` this.$element.data('Parsley', parsleyInstance); // Tell the world we got a new ParsleyForm or ParsleyField instance! $.emit('parsley:' + ('parsleyForm' === type ? 'form' : 'field') + ':init', parsleyInstance); } return parsleyInstance; } }; // ### jQuery API // `$('.elem').parsley(options)` or `$('.elem').psly(options)` $.fn.parsley = $.fn.psly = function (options) { if (this.length > 1) { var instances = []; this.each(function () { instances.push($(this).parsley(options)); }); return instances; } // Return undefined if applied to non existing DOM element if (!$(this).length) { if (window.console && window.console.warn) window.console.warn('You must bind Parsley on an existing element.'); return; } return new Parsley(this, options); }; // ### ParsleyUI // UI is a class apart that only listen to some events and them modify DOM accordingly // Could be overriden by defining a `window.ParsleyConfig.ParsleyUI` appropriate class (with `listen()` method basically) window.ParsleyUI = 'function' === typeof ParsleyUtils.get(window, 'ParsleyConfig.ParsleyUI') ? new window.ParsleyConfig.ParsleyUI().listen() : new ParsleyUI().listen(); // ### ParsleyField and ParsleyForm extension // Ensure that defined if not already the case if ('undefined' === typeof window.ParsleyExtend) window.ParsleyExtend = {}; // ### ParsleyConfig // Ensure that defined if not already the case if ('undefined' === typeof window.ParsleyConfig) window.ParsleyConfig = {}; // ### Globals window.Parsley = window.psly = Parsley; window.ParsleyUtils = ParsleyUtils; window.ParsleyValidator = new ParsleyValidator(window.ParsleyConfig.validators, window.ParsleyConfig.i18n); // ### PARSLEY auto-binding // Prevent it by setting `ParsleyConfig.autoBind` to `false` if (false !== ParsleyUtils.get(window, 'ParsleyConfig.autoBind')) $(document).ready(function () { // Works only on `data-parsley-validate`. if ($('[data-parsley-validate]').length) $('[data-parsley-validate]').parsley(); }); }));
// Array.indexOf polyfill for IE8 if (!Array.prototype.indexOf) { Array.prototype.indexOf = function (searchElement, fromIndex) { var k; // 1. Let O be the result of calling ToObject passing // the this value as the argument. if (this == null) { throw new TypeError('"this" is null or not defined'); } var O = Object(this); // 2. Let lenValue be the result of calling the Get // internal method of O with the argument "length". // 3. Let len be ToUint32(lenValue). var len = O.length >>> 0; // 4. If len is 0, return -1. if (len === 0) { return -1; } // 5. If argument fromIndex was passed let n be // ToInteger(fromIndex); else let n be 0. var n = +fromIndex || 0; if (Math.abs(n) === Infinity) { n = 0; } // 6. If n >= len, return -1. if (n >= len) { return -1; } // 7. If n >= 0, then Let k be n. // 8. Else, n<0, Let k be len - abs(n). // If k is less than 0, then let k be 0. k = Math.max(n >= 0 ? n : len - Math.abs(n), 0); // 9. Repeat, while k < len while (k < len) { // a. Let Pk be ToString(k). // This is implicit for LHS operands of the in operator // b. Let kPresent be the result of calling the // HasProperty internal method of O with argument Pk. // This step can be combined with c // c. If kPresent is true, then // i. Let elementK be the result of calling the Get // internal method of O with the argument ToString(k). // ii. Let same be the result of applying the // Strict Equality Comparison Algorithm to // searchElement and elementK. // iii. If same is true, return k. if (k in O && O[k] === searchElement) { return k; } k++; } return -1; }; }
(function(root) { (function(root) { var StringScanner; StringScanner = (function() { function StringScanner(str) { this.str = str != null ? str : ''; this.str = '' + this.str; this.pos = 0; this.lastMatch = { reset: function() { this.str = null; this.captures = []; return this; } }.reset(); this; } StringScanner.prototype.bol = function() { return this.pos <= 0 || (this.str[this.pos - 1] === "\n"); }; StringScanner.prototype.captures = function() { return this.lastMatch.captures; }; StringScanner.prototype.check = function(pattern) { var matches; if (this.str.substr(this.pos).search(pattern) !== 0) { this.lastMatch.reset(); return null; } matches = this.str.substr(this.pos).match(pattern); this.lastMatch.str = matches[0]; this.lastMatch.captures = matches.slice(1); return this.lastMatch.str; }; StringScanner.prototype.checkUntil = function(pattern) { var matches, patternPos; patternPos = this.str.substr(this.pos).search(pattern); if (patternPos < 0) { this.lastMatch.reset(); return null; } matches = this.str.substr(this.pos + patternPos).match(pattern); this.lastMatch.captures = matches.slice(1); return this.lastMatch.str = this.str.substr(this.pos, patternPos) + matches[0]; }; StringScanner.prototype.clone = function() { var clone, prop, value, _ref; clone = new this.constructor(this.str); clone.pos = this.pos; clone.lastMatch = {}; _ref = this.lastMatch; for (prop in _ref) { value = _ref[prop]; clone.lastMatch[prop] = value; } return clone; }; StringScanner.prototype.concat = function(str) { this.str += str; return this; }; StringScanner.prototype.eos = function() { return this.pos === this.str.length; }; StringScanner.prototype.exists = function(pattern) { var matches, patternPos; patternPos = this.str.substr(this.pos).search(pattern); if (patternPos < 0) { this.lastMatch.reset(); return null; } matches = this.str.substr(this.pos + patternPos).match(pattern); this.lastMatch.str = matches[0]; this.lastMatch.captures = matches.slice(1); return patternPos; }; StringScanner.prototype.getch = function() { return this.scan(/./); }; StringScanner.prototype.match = function() { return this.lastMatch.str; }; StringScanner.prototype.matches = function(pattern) { this.check(pattern); return this.matchSize(); }; StringScanner.prototype.matched = function() { return this.lastMatch.str != null; }; StringScanner.prototype.matchSize = function() { if (this.matched()) { return this.match().length; } else { return null; } }; StringScanner.prototype.peek = function(len) { return this.str.substr(this.pos, len); }; StringScanner.prototype.pointer = function() { return this.pos; }; StringScanner.prototype.setPointer = function(pos) { pos = +pos; if (pos < 0) { pos = 0; } if (pos > this.str.length) { pos = this.str.length; } return this.pos = pos; }; StringScanner.prototype.reset = function() { this.lastMatch.reset(); this.pos = 0; return this; }; StringScanner.prototype.rest = function() { return this.str.substr(this.pos); }; StringScanner.prototype.scan = function(pattern) { var chk; chk = this.check(pattern); if (chk != null) { this.pos += chk.length; } return chk; }; StringScanner.prototype.scanUntil = function(pattern) { var chk; chk = this.checkUntil(pattern); if (chk != null) { this.pos += chk.length; } return chk; }; StringScanner.prototype.skip = function(pattern) { this.scan(pattern); return this.matchSize(); }; StringScanner.prototype.skipUntil = function(pattern) { this.scanUntil(pattern); return this.matchSize(); }; StringScanner.prototype.string = function() { return this.str; }; StringScanner.prototype.terminate = function() { this.pos = this.str.length; this.lastMatch.reset(); return this; }; StringScanner.prototype.toString = function() { return "#<StringScanner " + (this.eos() ? 'fin' : "" + this.pos + "/" + this.str.length + " @ " + (this.str.length > 8 ? "" + (this.str.substr(0, 5)) + "..." : this.str)) + ">"; }; return StringScanner; })(); StringScanner.prototype.beginningOfLine = StringScanner.prototype.bol; StringScanner.prototype.clear = StringScanner.prototype.terminate; StringScanner.prototype.dup = StringScanner.prototype.clone; StringScanner.prototype.endOfString = StringScanner.prototype.eos; StringScanner.prototype.exist = StringScanner.prototype.exists; StringScanner.prototype.getChar = StringScanner.prototype.getch; StringScanner.prototype.position = StringScanner.prototype.pointer; StringScanner.StringScanner = StringScanner; this.StringScanner = StringScanner; })(this); var StringScanner = this.StringScanner; // lib/emblem.js var Emblem; this.Emblem = {}; Emblem = this.Emblem; Emblem.VERSION = "0.2.0"; ; // lib/parser.js Emblem.Parser = (function() { /* * Generated by PEG.js 0.7.0. * * http://pegjs.majda.cz/ */ function peg$subclass(child, parent) { function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); } function SyntaxError(expected, found, offset, line, column) { function buildMessage(expected, found) { function stringEscape(s) { function hex(ch) { return ch.charCodeAt(0).toString(16).toUpperCase(); } return s .replace(/\\/g, '\\\\') .replace(/"/g, '\\"') .replace(/\x08/g, '\\b') .replace(/\t/g, '\\t') .replace(/\n/g, '\\n') .replace(/\f/g, '\\f') .replace(/\r/g, '\\r') .replace(/[\x00-\x07\x0B\x0E\x0F]/g, function(ch) { return '\\x0' + hex(ch); }) .replace(/[\x10-\x1F\x80-\xFF]/g, function(ch) { return '\\x' + hex(ch); }) .replace(/[\u0180-\u0FFF]/g, function(ch) { return '\\u0' + hex(ch); }) .replace(/[\u1080-\uFFFF]/g, function(ch) { return '\\u' + hex(ch); }); } var expectedDesc, foundDesc; switch (expected.length) { case 0: expectedDesc = "end of input"; break; case 1: expectedDesc = expected[0]; break; default: expectedDesc = expected.slice(0, -1).join(", ") + " or " + expected[expected.length - 1]; } foundDesc = found ? "\"" + stringEscape(found) + "\"" : "end of input"; return "Expected " + expectedDesc + " but " + foundDesc + " found."; } this.expected = expected; this.found = found; this.offset = offset; this.line = line; this.column = column; this.name = "SyntaxError"; this.message = buildMessage(expected, found); } peg$subclass(SyntaxError, Error); function parse(input) { var options = arguments.length > 1 ? arguments[1] : {}, peg$startRuleFunctions = { start: peg$parsestart }, peg$startRuleFunction = peg$parsestart, peg$c0 = null, peg$c1 = "", peg$c2 = function(c) {return c;}, peg$c3 = function(c, i) { return new AST.ProgramNode(c, i || []); }, peg$c4 = "=", peg$c5 = "\"=\"", peg$c6 = "else", peg$c7 = "\"else\"", peg$c8 = [], peg$c9 = function(statements) { // Coalesce all adjacent ContentNodes into one. var compressedStatements = []; var buffer = []; for(var i = 0; i < statements.length; ++i) { var nodes = statements[i]; for(var j = 0; j < nodes.length; ++j) { var node = nodes[j] if(node.type === "content") { if(node.string) { // Ignore empty strings (comments). buffer.push(node.string); } continue; } // Flush content if present. if(buffer.length) { compressedStatements.push(new AST.ContentNode(buffer.join(''))); buffer = []; } compressedStatements.push(node); } } if(buffer.length) { compressedStatements.push(new AST.ContentNode(buffer.join(''))); } return compressedStatements; }, peg$c10 = "BeginStatement", peg$c11 = "ContentStatement", peg$c12 = function() { return []; }, peg$c13 = ">", peg$c14 = "\">\"", peg$c15 = function(n, params) { return [new AST.PartialNode(n, params[0])]; }, peg$c16 = /^[a-zA-Z0-9_$-\/]/, peg$c17 = "[a-zA-Z0-9_$-\\/]", peg$c18 = function(s) { return new AST.PartialNameNode(s); }, peg$c19 = function(m) { return [m]; }, peg$c20 = "/", peg$c21 = "\"/\"", peg$c22 = /^[A-Z]/, peg$c23 = "[A-Z]", peg$c24 = function(ret) { // TODO make this configurable var defaultCapitalizedHelper = 'view'; if(ret.mustache) { // Block. Modify inner MustacheNode and return. // Make sure a suffix modifier hasn't already been applied. var ch = ret.mustache.id.string.charAt(0); if(!IS_EMBER || !ch.match(/[A-Z]/)) return ret; ret.mustache = unshiftParam(ret.mustache, defaultCapitalizedHelper); return ret; } else { // Make sure a suffix modifier hasn't already been applied. var ch = ret.id.string.charAt(0); if(!IS_EMBER || !ch.match(/[A-Z]/)) return ret; return unshiftParam(ret, defaultCapitalizedHelper); } }, peg$c25 = " ", peg$c26 = "\" \"", peg$c27 = function(ret, multilineContent) { if(multilineContent) { multilineContent = multilineContent[1]; for(var i = 0, len = multilineContent.length; i < len; ++i) { ret.push(new AST.ContentNode(' ')); ret = ret.concat(multilineContent[i]); } } return ret; }, peg$c28 = function(c) { return c; }, peg$c29 = function(m) { return [m]; }, peg$c30 = function(h, nested) { // h is [[open tag content], closing tag ContentNode] var ret = h[0]; if(nested) { ret = ret.concat(nested); } // Push the closing tag ContentNode if it exists (self-closing if not) if(h[1]) { ret.push(h[1]); } return ret; }, peg$c31 = function(mustacheNode, nestedContentProgramNode) { if (!nestedContentProgramNode) { return mustacheNode; } return new AST.BlockNode(mustacheNode, nestedContentProgramNode, nestedContentProgramNode.inverse, mustacheNode.id); }, peg$c32 = ": ", peg$c33 = "\": \"", peg$c34 = function(statements) { return new AST.ProgramNode(statements, []); }, peg$c35 = function(block) { return block && block[2]; }, peg$c36 = function(e, ret) { var mustache = ret.mustache || ret; mustache.escaped = e; return ret; }, peg$c37 = function(isPartial, path, params, hash) { if(isPartial) { var n = new AST.PartialNameNode(path.string); return new AST.PartialNode(n, params[0]); } var actualParams = []; var attrs = {}; var hasAttrs = false; // Convert shorthand html attributes (e.g. % = tagName, . = class, etc) for(var i = 0; i < params.length; ++i) { var p = params[i]; var attrKey = p[0]; if(attrKey == 'tagName' || attrKey == 'elementId' || attrKey == 'class') { hasAttrs = true; attrs[attrKey] = attrs[attrKey] || []; attrs[attrKey].push(p[1]); } else { actualParams.push(p); } } if(hasAttrs) { hash = hash || new AST.HashNode([]); for(var k in attrs) { if(!attrs.hasOwnProperty(k)) continue; hash.pairs.push([k, new AST.StringNode(attrs[k].join(' '))]); } } actualParams.unshift(path); var mustacheNode = new AST.MustacheNode(actualParams, hash); var tm = path._emblemSuffixModifier; if(tm === '!') { return unshiftParam(mustacheNode, 'unbound'); } else if(tm === '?') { return unshiftParam(mustacheNode, 'if'); } else if(tm === '^') { return unshiftParam(mustacheNode, 'unless'); } return mustacheNode; }, peg$c38 = function(t) { return ['tagName', t]; }, peg$c39 = function(i) { return ['elementId', i]; }, peg$c40 = function(c) { return ['class', c]; }, peg$c41 = function(id, classes) { return [id, classes]; }, peg$c42 = function(classes) { return [null, classes]; }, peg$c43 = function(a) { return a; }, peg$c44 = function(h) { return new AST.HashNode(h); }, peg$c45 = "PathIdent", peg$c46 = "..", peg$c47 = "\"..\"", peg$c48 = ".", peg$c49 = "\".\"", peg$c50 = /^[a-zA-Z0-9_$\-!?\^]/, peg$c51 = "[a-zA-Z0-9_$\\-!?\\^]", peg$c52 = function(s) { return s; }, peg$c53 = "Key", peg$c54 = function(h) { return [h[0], h[2]]; }, peg$c55 = function(p) { return p; }, peg$c56 = function(first, tail) { var ret = [first]; for(var i = 0; i < tail.length; ++i) { //ret = ret.concat(tail[i]); ret.push(tail[i]); } return ret; }, peg$c57 = "PathSeparator", peg$c58 = /^[\/.]/, peg$c59 = "[\\/.]", peg$c60 = function(v) { var last = v[v.length - 1]; var match; var suffixModifier; if(match = last.match(/[!\?\^]$/)) { suffixModifier = match[0]; v[v.length - 1] = last.slice(0, -1); } var idNode = new AST.IdNode(v); idNode._emblemSuffixModifier = suffixModifier; return idNode; }, peg$c61 = function(v) { return new AST.StringNode(v); }, peg$c62 = function(v) { return new AST.IntegerNode(v); }, peg$c63 = function(v) { return new AST.BooleanNode(v); }, peg$c64 = "Boolean", peg$c65 = "true", peg$c66 = "\"true\"", peg$c67 = "false", peg$c68 = "\"false\"", peg$c69 = "Integer", peg$c70 = /^[0-9]/, peg$c71 = "[0-9]", peg$c72 = function(s) { return parseInt(s); }, peg$c73 = "\"", peg$c74 = "\"\\\"\"", peg$c75 = "'", peg$c76 = "\"'\"", peg$c77 = function(p) { return p[1]; }, peg$c78 = /^[^"}]/, peg$c79 = "[^\"}]", peg$c80 = /^[^'}]/, peg$c81 = "[^'}]", peg$c82 = /^[A-Za-z]/, peg$c83 = "[A-Za-z]", peg$c84 = function(ind, nodes, w) { nodes.unshift(new AST.ContentNode(ind)); for(var i = 0; i < w.length; ++i) { nodes.push(new AST.ContentNode(ind)); nodes = nodes.concat(w[i]); nodes.push("\n"); } return nodes; }, peg$c85 = /^[|`']/, peg$c86 = "[|`']", peg$c87 = "<", peg$c88 = "\"<\"", peg$c89 = function() { return '<'; }, peg$c90 = function(s, nodes, indentedNodes) { if(nodes.length || !indentedNodes) { nodes.push("\n"); } if(indentedNodes) { indentedNodes = indentedNodes[1]; for(var i = 0; i < indentedNodes.length; ++i) { /*nodes.push(new AST.ContentNode("#"));*/ nodes = nodes.concat(indentedNodes[i]); nodes.push("\n"); } } var ret = []; var strip = s !== '`'; for(var i = 0; i < nodes.length; ++i) { var node = nodes[i]; if(node == "\n") { if(!strip) { ret.push(new AST.ContentNode("\n")); } } else { ret.push(node); } } if(s === "'") { ret.push(new AST.ContentNode(" ")); } return ret; }, peg$c91 = function(first, tail) { return textNodesResult(first, tail); }, peg$c92 = function(first, tail) { return textNodesResult(first, tail); }, peg$c93 = function(m) { m.escaped = true; return m; }, peg$c94 = function(m) { m.escaped = false; return m; }, peg$c95 = function(a) { return new AST.ContentNode(a); }, peg$c96 = "any character", peg$c97 = "SingleMustacheOpen", peg$c98 = "{", peg$c99 = "\"{\"", peg$c100 = "DoubleMustacheOpen", peg$c101 = "{{", peg$c102 = "\"{{\"", peg$c103 = "TripleMustacheOpen", peg$c104 = "{{{", peg$c105 = "\"{{{\"", peg$c106 = "SingleMustacheClose", peg$c107 = "}", peg$c108 = "\"}\"", peg$c109 = "DoubleMustacheClose", peg$c110 = "}}", peg$c111 = "\"}}\"", peg$c112 = "TripleMustacheClose", peg$c113 = "}}}", peg$c114 = "\"}}}\"", peg$c115 = "InterpolationOpen", peg$c116 = "#{", peg$c117 = "\"#{\"", peg$c118 = "InterpolationClose", peg$c119 = "==", peg$c120 = "\"==\"", peg$c121 = function() { return false; }, peg$c122 = function() { return true; }, peg$c123 = function(h, s) { return h || s; }, peg$c124 = function(h, inTagMustaches, fullAttributes) { var tagName = h[0] || 'div', shorthandAttributes = h[1] || [], id = shorthandAttributes[0], classes = shorthandAttributes[1]; var tagOpenContent = []; tagOpenContent.push(new AST.ContentNode('<' + tagName)); if(id) { tagOpenContent.push(new AST.ContentNode(' id="' + id + '"')); } if(classes && classes.length) { tagOpenContent.push(new AST.ContentNode(' class="' + classes.join(' ') + '"')); } // Pad in tag mustaches with spaces. for(var i = 0; i < inTagMustaches.length; ++i) { tagOpenContent.push(new AST.ContentNode(' ')); tagOpenContent.push(inTagMustaches[i]); } for(var i = 0; i < fullAttributes.length; ++i) { tagOpenContent = tagOpenContent.concat(fullAttributes[i]); } if(SELF_CLOSING_TAG[tagName]) { tagOpenContent.push(new AST.ContentNode(' />')); return [tagOpenContent]; } else { tagOpenContent.push(new AST.ContentNode('>')); return [tagOpenContent, new AST.ContentNode('</' + tagName + '>')]; } }, peg$c125 = function(s) { return { shorthand: s, id: true}; }, peg$c126 = function(s) { return { shorthand: s }; }, peg$c127 = function(shorthands) { var id, classes = []; for(var i = 0, len = shorthands.length; i < len; ++i) { var shorthand = shorthands[i]; if(shorthand.id) { id = shorthand.shorthand; } else { classes.push(shorthand.shorthand); } } return [id, classes]; }, peg$c128 = function(a) { return [new AST.ContentNode(' ')].concat(a); }, peg$c129 = /^[A-Za-z.:0-9_\-]/, peg$c130 = "[A-Za-z.:0-9_\\-]", peg$c131 = function(id) { return new AST.MustacheNode([id]); }, peg$c132 = function(event, mustacheNode) { // Unshift the action helper and augment the hash return [unshiftParam(mustacheNode, 'action', [['on', new AST.StringNode(event)]])]; }, peg$c133 = function(value) { return value.replace(/ *$/, ''); }, peg$c134 = "!", peg$c135 = "\"!\"", peg$c136 = function(key, value) { return IS_EMBER; }, peg$c137 = function(key, value) { var hashNode = new AST.HashNode([[key, new AST.StringNode(value)]]); var params = [new AST.IdNode(['bindAttr'])]; var mustacheNode = new AST.MustacheNode(params, hashNode); /* if(whatever) { mustacheNode = return unshiftParam(mustacheNode, 'unbound'); } */ return [mustacheNode]; }, peg$c138 = function(key, id) { var mustacheNode = new AST.MustacheNode([id]); if(IS_EMBER && id._emblemSuffixModifier === '!') { mustacheNode = unshiftParam(mustacheNode, 'unbound'); } return [ new AST.ContentNode(key + '=' + '"'), mustacheNode, new AST.ContentNode('"'), ]; }, peg$c139 = function(key, nodes) { var result = [ new AST.ContentNode(key + '=' + '"') ].concat(nodes); return result.concat([new AST.ContentNode('"')]); }, peg$c140 = "_", peg$c141 = "\"_\"", peg$c142 = "-", peg$c143 = "\"-\"", peg$c144 = "%", peg$c145 = "\"%\"", peg$c146 = "#", peg$c147 = "\"#\"", peg$c148 = function(c) { return c;}, peg$c149 = "CSSIdentifier", peg$c150 = function(nmstart, nmchars) { return nmstart + nmchars; }, peg$c151 = /^[_a-zA-Z0-9\-]/, peg$c152 = "[_a-zA-Z0-9\\-]", peg$c153 = /^[_a-zA-Z]/, peg$c154 = "[_a-zA-Z]", peg$c155 = /^[\x80-\xFF]/, peg$c156 = "[\\x80-\\xFF]", peg$c157 = "KnownHTMLTagName", peg$c158 = function(t) { return !!KNOWN_TAGS[t]; }, peg$c159 = function(t) { return t; }, peg$c160 = ":", peg$c161 = "\":\"", peg$c162 = "a JS event", peg$c163 = function(t) { return !!KNOWN_EVENTS[t]; }, peg$c164 = "INDENT", peg$c165 = "\uEFEF", peg$c166 = "\"\\uEFEF\"", peg$c167 = function() { return ''; }, peg$c168 = "DEDENT", peg$c169 = "\uEFFE", peg$c170 = "\"\\uEFFE\"", peg$c171 = "Unmatched DEDENT", peg$c172 = "\uEFEE", peg$c173 = "\"\\uEFEE\"", peg$c174 = "LineEnd", peg$c175 = "\uEFFF", peg$c176 = "\"\\uEFFF\"", peg$c177 = "\n", peg$c178 = "\"\\n\"", peg$c179 = "ANYDEDENT", peg$c180 = "RequiredWhitespace", peg$c181 = "OptionalWhitespace", peg$c182 = "InlineWhitespace", peg$c183 = /^[ \t]/, peg$c184 = "[ \\t]", peg$currPos = 0, peg$reportedPos = 0, peg$cachedPos = 0, peg$cachedPosDetails = { line: 1, column: 1, seenCR: false }, peg$maxFailPos = 0, peg$maxFailExpected = [], peg$silentFails = 0, peg$result; if ("startRule" in options) { if (!(options.startRule in peg$startRuleFunctions)) { throw new Error("Can't start parsing from rule \"" + options.startRule + "\"."); } peg$startRuleFunction = peg$startRuleFunctions[options.startRule]; } function text() { return input.substring(peg$reportedPos, peg$currPos); } function offset() { return peg$reportedPos; } function line() { return peg$computePosDetails(peg$reportedPos).line; } function column() { return peg$computePosDetails(peg$reportedPos).column; } function peg$computePosDetails(pos) { function advance(details, pos) { var p, ch; for (p = 0; p < pos; p++) { ch = input.charAt(p); if (ch === "\n") { if (!details.seenCR) { details.line++; } details.column = 1; details.seenCR = false; } else if (ch === "\r" || ch === "\u2028" || ch === "\u2029") { details.line++; details.column = 1; details.seenCR = true; } else { details.column++; details.seenCR = false; } } } if (peg$cachedPos !== pos) { if (peg$cachedPos > pos) { peg$cachedPos = 0; peg$cachedPosDetails = { line: 1, column: 1, seenCR: false }; } peg$cachedPos = pos; advance(peg$cachedPosDetails, peg$cachedPos); } return peg$cachedPosDetails; } function peg$fail(expected) { if (peg$currPos < peg$maxFailPos) { return; } if (peg$currPos > peg$maxFailPos) { peg$maxFailPos = peg$currPos; peg$maxFailExpected = []; } peg$maxFailExpected.push(expected); } function peg$cleanupExpected(expected) { var i = 0; expected.sort(); while (i < expected.length) { if (expected[i - 1] === expected[i]) { expected.splice(i, 1); } else { i++; } } } function peg$parsestart() { var s0; s0 = peg$parseinvertibleContent(); return s0; } function peg$parseinvertibleContent() { var s0, s1, s2, s3, s4, s5, s6, s7, s8; s0 = peg$currPos; s1 = peg$parsecontent(); if (s1 !== null) { s2 = peg$currPos; s3 = peg$parseDEDENT(); if (s3 !== null) { s4 = peg$parseelse(); if (s4 !== null) { s5 = peg$parse_(); if (s5 !== null) { s6 = peg$parseTERM(); if (s6 !== null) { s7 = peg$parseindentation(); if (s7 !== null) { s8 = peg$parsecontent(); if (s8 !== null) { peg$reportedPos = s2; s3 = peg$c2(s8); if (s3 === null) { peg$currPos = s2; s2 = s3; } else { s2 = s3; } } else { peg$currPos = s2; s2 = peg$c0; } } else { peg$currPos = s2; s2 = peg$c0; } } else { peg$currPos = s2; s2 = peg$c0; } } else { peg$currPos = s2; s2 = peg$c0; } } else { peg$currPos = s2; s2 = peg$c0; } } else { peg$currPos = s2; s2 = peg$c0; } if (s2 === null) { s2 = peg$c1; } if (s2 !== null) { peg$reportedPos = s0; s1 = peg$c3(s1,s2); if (s1 === null) { peg$currPos = s0; s0 = s1; } else { s0 = s1; } } else { peg$currPos = s0; s0 = peg$c0; } } else { peg$currPos = s0; s0 = peg$c0; } return s0; } function peg$parseelse() { var s0, s1, s2, s3; s0 = peg$currPos; s1 = peg$currPos; if (input.charCodeAt(peg$currPos) === 61) { s2 = peg$c4; peg$currPos++; } else { s2 = null; if (peg$silentFails === 0) { peg$fail(peg$c5); } } if (s2 !== null) { s3 = peg$parse_(); if (s3 !== null) { s2 = [s2, s3]; s1 = s2; } else { peg$currPos = s1; s1 = peg$c0; } } else { peg$currPos = s1; s1 = peg$c0; } if (s1 === null) { s1 = peg$c1; } if (s1 !== null) { if (input.substr(peg$currPos, 4) === peg$c6) { s2 = peg$c6; peg$currPos += 4; } else { s2 = null; if (peg$silentFails === 0) { peg$fail(peg$c7); } } if (s2 !== null) { s1 = [s1, s2]; s0 = s1; } else { peg$currPos = s0; s0 = peg$c0; } } else { peg$currPos = s0; s0 = peg$c0; } return s0; } function peg$parsecontent() { var s0, s1, s2; s0 = peg$currPos; s1 = []; s2 = peg$parsestatement(); while (s2 !== null) { s1.push(s2); s2 = peg$parsestatement(); } if (s1 !== null) { peg$reportedPos = s0; s1 = peg$c9(s1); } if (s1 === null) { peg$currPos = s0; s0 = s1; } else { s0 = s1; } return s0; } function peg$parsestatement() { var s0, s1; peg$silentFails++; s0 = peg$parseblankLine(); if (s0 === null) { s0 = peg$parsecomment(); if (s0 === null) { s0 = peg$parsecontentStatement(); } } peg$silentFails--; if (s0 === null) { s1 = null; if (peg$silentFails === 0) { peg$fail(peg$c10); } } return s0; } function peg$parsecontentStatement() { var s0, s1; peg$silentFails++; s0 = peg$parselegacyPartialInvocation(); if (s0 === null) { s0 = peg$parsehtmlElement(); if (s0 === null) { s0 = peg$parsetextLine(); if (s0 === null) { s0 = peg$parsemustache(); } } } peg$silentFails--; if (s0 === null) { s1 = null; if (peg$silentFails === 0) { peg$fail(peg$c11); } } return s0; } function peg$parseblankLine() { var s0, s1, s2; s0 = peg$currPos; s1 = peg$parse_(); if (s1 !== null) { s2 = peg$parseTERM(); if (s2 !== null) { peg$reportedPos = s0; s1 = peg$c12(); if (s1 === null) { peg$currPos = s0; s0 = s1; } else { s0 = s1; } } else { peg$currPos = s0; s0 = peg$c0; } } else { peg$currPos = s0; s0 = peg$c0; } return s0; } function peg$parselegacyPartialInvocation() { var s0, s1, s2, s3, s4, s5, s6, s7; s0 = peg$currPos; if (input.charCodeAt(peg$currPos) === 62) { s1 = peg$c13; peg$currPos++; } else { s1 = null; if (peg$silentFails === 0) { peg$fail(peg$c14); } } if (s1 !== null) { s2 = peg$parse_(); if (s2 !== null) { s3 = peg$parselegacyPartialName(); if (s3 !== null) { s4 = peg$parse_(); if (s4 !== null) { s5 = []; s6 = peg$parseinMustacheParam(); while (s6 !== null) { s5.push(s6); s6 = peg$parseinMustacheParam(); } if (s5 !== null) { s6 = peg$parse_(); if (s6 !== null) { s7 = peg$parseTERM(); if (s7 !== null) { peg$reportedPos = s0; s1 = peg$c15(s3,s5); if (s1 === null) { peg$currPos = s0; s0 = s1; } else { s0 = s1; } } else { peg$currPos = s0; s0 = peg$c0; } } else { peg$currPos = s0; s0 = peg$c0; } } else { peg$currPos = s0; s0 = peg$c0; } } else { peg$currPos = s0; s0 = peg$c0; } } else { peg$currPos = s0; s0 = peg$c0; } } else { peg$currPos = s0; s0 = peg$c0; } } else { peg$currPos = s0; s0 = peg$c0; } return s0; } function peg$parselegacyPartialName() { var s0, s1, s2, s3; s0 = peg$currPos; s1 = peg$currPos; s2 = []; if (peg$c16.test(input.charAt(peg$currPos))) { s3 = input.charAt(peg$currPos); peg$currPos++; } else { s3 = null; if (peg$silentFails === 0) { peg$fail(peg$c17); } } if (s3 !== null) { while (s3 !== null) { s2.push(s3); if (peg$c16.test(input.charAt(peg$currPos))) { s3 = input.charAt(peg$currPos); peg$currPos++; } else { s3 = null; if (peg$silentFails === 0) { peg$fail(peg$c17); } } } } else { s2 = peg$c0; } if (s2 !== null) { s2 = input.substring(s1, peg$currPos); } s1 = s2; if (s1 !== null) { peg$reportedPos = s0; s1 = peg$c18(s1); } if (s1 === null) { peg$currPos = s0; s0 = s1; } else { s0 = s1; } return s0; } function peg$parsemustache() { var s0, s1; s0 = peg$currPos; s1 = peg$parseexplicitMustache(); if (s1 === null) { s1 = peg$parselineStartingMustache(); } if (s1 !== null) { peg$reportedPos = s0; s1 = peg$c19(s1); } if (s1 === null) { peg$currPos = s0; s0 = s1; } else { s0 = s1; } return s0; } function peg$parsecommentContent() { var s0, s1, s2, s3, s4, s5, s6, s7; s0 = peg$currPos; s1 = peg$parselineContent(); if (s1 !== null) { s2 = peg$parseTERM(); if (s2 !== null) { s3 = []; s4 = peg$currPos; s5 = peg$parseindentation(); if (s5 !== null) { s6 = []; s7 = peg$parsecommentContent(); if (s7 !== null) { while (s7 !== null) { s6.push(s7); s7 = peg$parsecommentContent(); } } else { s6 = peg$c0; } if (s6 !== null) { s7 = peg$parseanyDedent(); if (s7 !== null) { s5 = [s5, s6, s7]; s4 = s5; } else { peg$currPos = s4; s4 = peg$c0; } } else { peg$currPos = s4; s4 = peg$c0; } } else { peg$currPos = s4; s4 = peg$c0; } while (s4 !== null) { s3.push(s4); s4 = peg$currPos; s5 = peg$parseindentation(); if (s5 !== null) { s6 = []; s7 = peg$parsecommentContent(); if (s7 !== null) { while (s7 !== null) { s6.push(s7); s7 = peg$parsecommentContent(); } } else { s6 = peg$c0; } if (s6 !== null) { s7 = peg$parseanyDedent(); if (s7 !== null) { s5 = [s5, s6, s7]; s4 = s5; } else { peg$currPos = s4; s4 = peg$c0; } } else { peg$currPos = s4; s4 = peg$c0; } } else { peg$currPos = s4; s4 = peg$c0; } } if (s3 !== null) { peg$reportedPos = s0; s1 = peg$c12(); if (s1 === null) { peg$currPos = s0; s0 = s1; } else { s0 = s1; } } else { peg$currPos = s0; s0 = peg$c0; } } else { peg$currPos = s0; s0 = peg$c0; } } else { peg$currPos = s0; s0 = peg$c0; } return s0; } function peg$parsecomment() { var s0, s1, s2; s0 = peg$currPos; if (input.charCodeAt(peg$currPos) === 47) { s1 = peg$c20; peg$currPos++; } else { s1 = null; if (peg$silentFails === 0) { peg$fail(peg$c21); } } if (s1 !== null) { s2 = peg$parsecommentContent(); if (s2 !== null) { peg$reportedPos = s0; s1 = peg$c12(); if (s1 === null) { peg$currPos = s0; s0 = s1; } else { s0 = s1; } } else { peg$currPos = s0; s0 = peg$c0; } } else { peg$currPos = s0; s0 = peg$c0; } return s0; } function peg$parselineStartingMustache() { var s0; s0 = peg$parsecapitalizedLineStarterMustache(); if (s0 === null) { s0 = peg$parsemustacheOrBlock(); } return s0; } function peg$parsecapitalizedLineStarterMustache() { var s0, s1, s2; s0 = peg$currPos; s1 = peg$currPos; peg$silentFails++; if (peg$c22.test(input.charAt(peg$currPos))) { s2 = input.charAt(peg$currPos); peg$currPos++; } else { s2 = null; if (peg$silentFails === 0) { peg$fail(peg$c23); } } peg$silentFails--; if (s2 !== null) { peg$currPos = s1; s1 = peg$c1; } else { s1 = peg$c0; } if (s1 !== null) { s2 = peg$parsemustacheOrBlock(); if (s2 !== null) { peg$reportedPos = s0; s1 = peg$c24(s2); if (s1 === null) { peg$currPos = s0; s0 = s1; } else { s0 = s1; } } else { peg$currPos = s0; s0 = peg$c0; } } else { peg$currPos = s0; s0 = peg$c0; } return s0; } function peg$parsehtmlNestedTextNodes() { var s0, s1, s2, s3, s4, s5, s6; s0 = peg$currPos; if (input.charCodeAt(peg$currPos) === 32) { s1 = peg$c25; peg$currPos++; } else { s1 = null; if (peg$silentFails === 0) { peg$fail(peg$c26); } } if (s1 !== null) { s2 = peg$parsetextNodes(); if (s2 !== null) { s3 = peg$currPos; s4 = peg$parseindentation(); if (s4 !== null) { s5 = []; s6 = peg$parsewhitespaceableTextNodes(); if (s6 !== null) { while (s6 !== null) { s5.push(s6); s6 = peg$parsewhitespaceableTextNodes(); } } else { s5 = peg$c0; } if (s5 !== null) { s6 = peg$parseDEDENT(); if (s6 !== null) { s4 = [s4, s5, s6]; s3 = s4; } else { peg$currPos = s3; s3 = peg$c0; } } else { peg$currPos = s3; s3 = peg$c0; } } else { peg$currPos = s3; s3 = peg$c0; } if (s3 === null) { s3 = peg$c1; } if (s3 !== null) { peg$reportedPos = s0; s1 = peg$c27(s2,s3); if (s1 === null) { peg$currPos = s0; s0 = s1; } else { s0 = s1; } } else { peg$currPos = s0; s0 = peg$c0; } } else { peg$currPos = s0; s0 = peg$c0; } } else { peg$currPos = s0; s0 = peg$c0; } return s0; } function peg$parseindentedContent() { var s0, s1, s2, s3, s4; s0 = peg$currPos; s1 = []; s2 = peg$parseblankLine(); while (s2 !== null) { s1.push(s2); s2 = peg$parseblankLine(); } if (s1 !== null) { s2 = peg$parseindentation(); if (s2 !== null) { s3 = peg$parsecontent(); if (s3 !== null) { s4 = peg$parseDEDENT(); if (s4 !== null) { peg$reportedPos = s0; s1 = peg$c28(s3); if (s1 === null) { peg$currPos = s0; s0 = s1; } else { s0 = s1; } } else { peg$currPos = s0; s0 = peg$c0; } } else { peg$currPos = s0; s0 = peg$c0; } } else { peg$currPos = s0; s0 = peg$c0; } } else { peg$currPos = s0; s0 = peg$c0; } return s0; } function peg$parsehtmlTerminator() { var s0, s1, s2, s3; s0 = peg$parsecolonContent(); if (s0 === null) { s0 = peg$currPos; s1 = peg$parse_(); if (s1 !== null) { s2 = peg$parseexplicitMustache(); if (s2 !== null) { peg$reportedPos = s0; s1 = peg$c29(s2); if (s1 === null) { peg$currPos = s0; s0 = s1; } else { s0 = s1; } } else { peg$currPos = s0; s0 = peg$c0; } } else { peg$currPos = s0; s0 = peg$c0; } if (s0 === null) { s0 = peg$currPos; s1 = peg$parse_(); if (s1 !== null) { s2 = peg$parseTERM(); if (s2 !== null) { s3 = peg$parseindentedContent(); if (s3 === null) { s3 = peg$c1; } if (s3 !== null) { peg$reportedPos = s0; s1 = peg$c28(s3); if (s1 === null) { peg$currPos = s0; s0 = s1; } else { s0 = s1; } } else { peg$currPos = s0; s0 = peg$c0; } } else { peg$currPos = s0; s0 = peg$c0; } } else { peg$currPos = s0; s0 = peg$c0; } if (s0 === null) { s0 = peg$parsehtmlNestedTextNodes(); } } } return s0; } function peg$parsehtmlElement() { var s0, s1, s2; s0 = peg$currPos; s1 = peg$parseinHtmlTag(); if (s1 !== null) { s2 = peg$parsehtmlTerminator(); if (s2 !== null) { peg$reportedPos = s0; s1 = peg$c30(s1,s2); if (s1 === null) { peg$currPos = s0; s0 = s1; } else { s0 = s1; } } else { peg$currPos = s0; s0 = peg$c0; } } else { peg$currPos = s0; s0 = peg$c0; } return s0; } function peg$parsemustacheOrBlock() { var s0, s1, s2, s3; s0 = peg$currPos; s1 = peg$parseinMustache(); if (s1 !== null) { s2 = peg$parse_(); if (s2 !== null) { s3 = peg$parsemustacheNestedContent(); if (s3 !== null) { peg$reportedPos = s0; s1 = peg$c31(s1,s3); if (s1 === null) { peg$currPos = s0; s0 = s1; } else { s0 = s1; } } else { peg$currPos = s0; s0 = peg$c0; } } else { peg$currPos = s0; s0 = peg$c0; } } else { peg$currPos = s0; s0 = peg$c0; } return s0; } function peg$parseinvertibleContent() { var s0, s1, s2, s3, s4, s5, s6, s7, s8; s0 = peg$currPos; s1 = peg$parsecontent(); if (s1 !== null) { s2 = peg$currPos; s3 = peg$parseDEDENT(); if (s3 !== null) { s4 = peg$parseelse(); if (s4 !== null) { s5 = peg$parse_(); if (s5 !== null) { s6 = peg$parseTERM(); if (s6 !== null) { s7 = peg$parseindentation(); if (s7 !== null) { s8 = peg$parsecontent(); if (s8 !== null) { peg$reportedPos = s2; s3 = peg$c2(s8); if (s3 === null) { peg$currPos = s2; s2 = s3; } else { s2 = s3; } } else { peg$currPos = s2; s2 = peg$c0; } } else { peg$currPos = s2; s2 = peg$c0; } } else { peg$currPos = s2; s2 = peg$c0; } } else { peg$currPos = s2; s2 = peg$c0; } } else { peg$currPos = s2; s2 = peg$c0; } } else { peg$currPos = s2; s2 = peg$c0; } if (s2 === null) { s2 = peg$c1; } if (s2 !== null) { peg$reportedPos = s0; s1 = peg$c3(s1,s2); if (s1 === null) { peg$currPos = s0; s0 = s1; } else { s0 = s1; } } else { peg$currPos = s0; s0 = peg$c0; } } else { peg$currPos = s0; s0 = peg$c0; } return s0; } function peg$parsecolonContent() { var s0, s1, s2, s3; s0 = peg$currPos; if (input.substr(peg$currPos, 2) === peg$c32) { s1 = peg$c32; peg$currPos += 2; } else { s1 = null; if (peg$silentFails === 0) { peg$fail(peg$c33); } } if (s1 !== null) { s2 = peg$parse_(); if (s2 !== null) { s3 = peg$parsecontentStatement(); if (s3 !== null) { peg$reportedPos = s0; s1 = peg$c28(s3); if (s1 === null) { peg$currPos = s0; s0 = s1; } else { s0 = s1; } } else { peg$currPos = s0; s0 = peg$c0; } } else { peg$currPos = s0; s0 = peg$c0; } } else { peg$currPos = s0; s0 = peg$c0; } return s0; } function peg$parsemustacheNestedContent() { var s0, s1, s2, s3, s4, s5, s6; s0 = peg$currPos; s1 = peg$parsecolonContent(); if (s1 === null) { s1 = peg$parsetextLine(); } if (s1 !== null) { peg$reportedPos = s0; s1 = peg$c34(s1); } if (s1 === null) { peg$currPos = s0; s0 = s1; } else { s0 = s1; } if (s0 === null) { s0 = peg$currPos; s1 = peg$parseTERM(); if (s1 !== null) { s2 = peg$currPos; s3 = []; s4 = peg$parseblankLine(); while (s4 !== null) { s3.push(s4); s4 = peg$parseblankLine(); } if (s3 !== null) { s4 = peg$parseindentation(); if (s4 !== null) { s5 = peg$parseinvertibleContent(); if (s5 !== null) { s6 = peg$parseDEDENT(); if (s6 !== null) { s3 = [s3, s4, s5, s6]; s2 = s3; } else { peg$currPos = s2; s2 = peg$c0; } } else { peg$currPos = s2; s2 = peg$c0; } } else { peg$currPos = s2; s2 = peg$c0; } } else { peg$currPos = s2; s2 = peg$c0; } if (s2 === null) { s2 = peg$c1; } if (s2 !== null) { peg$reportedPos = s0; s1 = peg$c35(s2); if (s1 === null) { peg$currPos = s0; s0 = s1; } else { s0 = s1; } } else { peg$currPos = s0; s0 = peg$c0; } } else { peg$currPos = s0; s0 = peg$c0; } } return s0; } function peg$parseexplicitMustache() { var s0, s1, s2; s0 = peg$currPos; s1 = peg$parseequalSign(); if (s1 !== null) { s2 = peg$parsemustacheOrBlock(); if (s2 !== null) { peg$reportedPos = s0; s1 = peg$c36(s1,s2); if (s1 === null) { peg$currPos = s0; s0 = s1; } else { s0 = s1; } } else { peg$currPos = s0; s0 = peg$c0; } } else { peg$currPos = s0; s0 = peg$c0; } return s0; } function peg$parseinMustache() { var s0, s1, s2, s3, s4, s5; s0 = peg$currPos; if (input.charCodeAt(peg$currPos) === 62) { s1 = peg$c13; peg$currPos++; } else { s1 = null; if (peg$silentFails === 0) { peg$fail(peg$c14); } } if (s1 === null) { s1 = peg$c1; } if (s1 !== null) { s2 = peg$parse_(); if (s2 !== null) { s3 = peg$parsepathIdNode(); if (s3 !== null) { s4 = []; s5 = peg$parseinMustacheParam(); while (s5 !== null) { s4.push(s5); s5 = peg$parseinMustacheParam(); } if (s4 !== null) { s5 = peg$parsehash(); if (s5 === null) { s5 = peg$c1; } if (s5 !== null) { peg$reportedPos = s0; s1 = peg$c37(s1,s3,s4,s5); if (s1 === null) { peg$currPos = s0; s0 = s1; } else { s0 = s1; } } else { peg$currPos = s0; s0 = peg$c0; } } else { peg$currPos = s0; s0 = peg$c0; } } else { peg$currPos = s0; s0 = peg$c0; } } else { peg$currPos = s0; s0 = peg$c0; } } else { peg$currPos = s0; s0 = peg$c0; } return s0; } function peg$parsehtmlMustacheAttribute() { var s0, s1; s0 = peg$currPos; s1 = peg$parsetagNameShorthand(); if (s1 !== null) { peg$reportedPos = s0; s1 = peg$c38(s1); } if (s1 === null) { peg$currPos = s0; s0 = s1; } else { s0 = s1; } if (s0 === null) { s0 = peg$currPos; s1 = peg$parseidShorthand(); if (s1 !== null) { peg$reportedPos = s0; s1 = peg$c39(s1); } if (s1 === null) { peg$currPos = s0; s0 = s1; } else { s0 = s1; } if (s0 === null) { s0 = peg$currPos; s1 = peg$parseclassShorthand(); if (s1 !== null) { peg$reportedPos = s0; s1 = peg$c40(s1); } if (s1 === null) { peg$currPos = s0; s0 = s1; } else { s0 = s1; } } } return s0; } function peg$parseshorthandAttributes() { var s0; s0 = peg$parseattributesAtLeastID(); if (s0 === null) { s0 = peg$parseattributesAtLeastClass(); } return s0; } function peg$parseattributesAtLeastID() { var s0, s1, s2, s3; s0 = peg$currPos; s1 = peg$parseidShorthand(); if (s1 !== null) { s2 = []; s3 = peg$parseclassShorthand(); while (s3 !== null) { s2.push(s3); s3 = peg$parseclassShorthand(); } if (s2 !== null) { peg$reportedPos = s0; s1 = peg$c41(s1,s2); if (s1 === null) { peg$currPos = s0; s0 = s1; } else { s0 = s1; } } else { peg$currPos = s0; s0 = peg$c0; } } else { peg$currPos = s0; s0 = peg$c0; } return s0; } function peg$parseattributesAtLeastClass() { var s0, s1, s2; s0 = peg$currPos; s1 = []; s2 = peg$parseclassShorthand(); if (s2 !== null) { while (s2 !== null) { s1.push(s2); s2 = peg$parseclassShorthand(); } } else { s1 = peg$c0; } if (s1 !== null) { peg$reportedPos = s0; s1 = peg$c42(s1); } if (s1 === null) { peg$currPos = s0; s0 = s1; } else { s0 = s1; } return s0; } function peg$parseinMustacheParam() { var s0, s1, s2; s0 = peg$currPos; s1 = peg$parse_(); if (s1 !== null) { s2 = peg$parsehtmlMustacheAttribute(); if (s2 === null) { s2 = peg$parseparam(); } if (s2 !== null) { peg$reportedPos = s0; s1 = peg$c43(s2); if (s1 === null) { peg$currPos = s0; s0 = s1; } else { s0 = s1; } } else { peg$currPos = s0; s0 = peg$c0; } } else { peg$currPos = s0; s0 = peg$c0; } return s0; } function peg$parsehash() { var s0, s1, s2; s0 = peg$currPos; s1 = []; s2 = peg$parsehashSegment(); if (s2 !== null) { while (s2 !== null) { s1.push(s2); s2 = peg$parsehashSegment(); } } else { s1 = peg$c0; } if (s1 !== null) { peg$reportedPos = s0; s1 = peg$c44(s1); } if (s1 === null) { peg$currPos = s0; s0 = s1; } else { s0 = s1; } return s0; } function peg$parsepathIdent() { var s0, s1, s2, s3; peg$silentFails++; if (input.substr(peg$currPos, 2) === peg$c46) { s0 = peg$c46; peg$currPos += 2; } else { s0 = null; if (peg$silentFails === 0) { peg$fail(peg$c47); } } if (s0 === null) { if (input.charCodeAt(peg$currPos) === 46) { s0 = peg$c48; peg$currPos++; } else { s0 = null; if (peg$silentFails === 0) { peg$fail(peg$c49); } } if (s0 === null) { s0 = peg$currPos; s1 = peg$currPos; s2 = []; if (peg$c50.test(input.charAt(peg$currPos))) { s3 = input.charAt(peg$currPos); peg$currPos++; } else { s3 = null; if (peg$silentFails === 0) { peg$fail(peg$c51); } } if (s3 !== null) { while (s3 !== null) { s2.push(s3); if (peg$c50.test(input.charAt(peg$currPos))) { s3 = input.charAt(peg$currPos); peg$currPos++; } else { s3 = null; if (peg$silentFails === 0) { peg$fail(peg$c51); } } } } else { s2 = peg$c0; } if (s2 !== null) { s2 = input.substring(s1, peg$currPos); } s1 = s2; if (s1 !== null) { s2 = peg$currPos; peg$silentFails++; if (input.charCodeAt(peg$currPos) === 61) { s3 = peg$c4; peg$currPos++; } else { s3 = null; if (peg$silentFails === 0) { peg$fail(peg$c5); } } peg$silentFails--; if (s3 === null) { s2 = peg$c1; } else { peg$currPos = s2; s2 = peg$c0; } if (s2 !== null) { peg$reportedPos = s0; s1 = peg$c52(s1); if (s1 === null) { peg$currPos = s0; s0 = s1; } else { s0 = s1; } } else { peg$currPos = s0; s0 = peg$c0; } } else { peg$currPos = s0; s0 = peg$c0; } } } peg$silentFails--; if (s0 === null) { s1 = null; if (peg$silentFails === 0) { peg$fail(peg$c45); } } return s0; } function peg$parsekey() { var s0, s1; peg$silentFails++; s0 = peg$parseident(); peg$silentFails--; if (s0 === null) { s1 = null; if (peg$silentFails === 0) { peg$fail(peg$c53); } } return s0; } function peg$parsehashSegment() { var s0, s1, s2, s3, s4, s5; s0 = peg$currPos; s1 = peg$parse_(); if (s1 !== null) { s2 = peg$currPos; s3 = peg$parsekey(); if (s3 !== null) { if (input.charCodeAt(peg$currPos) === 61) { s4 = peg$c4; peg$currPos++; } else { s4 = null; if (peg$silentFails === 0) { peg$fail(peg$c5); } } if (s4 !== null) { s5 = peg$parsebooleanNode(); if (s5 !== null) { s3 = [s3, s4, s5]; s2 = s3; } else { peg$currPos = s2; s2 = peg$c0; } } else { peg$currPos = s2; s2 = peg$c0; } } else { peg$currPos = s2; s2 = peg$c0; } if (s2 === null) { s2 = peg$currPos; s3 = peg$parsekey(); if (s3 !== null) { if (input.charCodeAt(peg$currPos) === 61) { s4 = peg$c4; peg$currPos++; } else { s4 = null; if (peg$silentFails === 0) { peg$fail(peg$c5); } } if (s4 !== null) { s5 = peg$parseintegerNode(); if (s5 !== null) { s3 = [s3, s4, s5]; s2 = s3; } else { peg$currPos = s2; s2 = peg$c0; } } else { peg$currPos = s2; s2 = peg$c0; } } else { peg$currPos = s2; s2 = peg$c0; } if (s2 === null) { s2 = peg$currPos; s3 = peg$parsekey(); if (s3 !== null) { if (input.charCodeAt(peg$currPos) === 61) { s4 = peg$c4; peg$currPos++; } else { s4 = null; if (peg$silentFails === 0) { peg$fail(peg$c5); } } if (s4 !== null) { s5 = peg$parsepathIdNode(); if (s5 !== null) { s3 = [s3, s4, s5]; s2 = s3; } else { peg$currPos = s2; s2 = peg$c0; } } else { peg$currPos = s2; s2 = peg$c0; } } else { peg$currPos = s2; s2 = peg$c0; } if (s2 === null) { s2 = peg$currPos; s3 = peg$parsekey(); if (s3 !== null) { if (input.charCodeAt(peg$currPos) === 61) { s4 = peg$c4; peg$currPos++; } else { s4 = null; if (peg$silentFails === 0) { peg$fail(peg$c5); } } if (s4 !== null) { s5 = peg$parsestringNode(); if (s5 !== null) { s3 = [s3, s4, s5]; s2 = s3; } else { peg$currPos = s2; s2 = peg$c0; } } else { peg$currPos = s2; s2 = peg$c0; } } else { peg$currPos = s2; s2 = peg$c0; } } } } if (s2 !== null) { peg$reportedPos = s0; s1 = peg$c54(s2); if (s1 === null) { peg$currPos = s0; s0 = s1; } else { s0 = s1; } } else { peg$currPos = s0; s0 = peg$c0; } } else { peg$currPos = s0; s0 = peg$c0; } return s0; } function peg$parseparam() { var s0; s0 = peg$parsepathIdNode(); if (s0 === null) { s0 = peg$parsestringNode(); if (s0 === null) { s0 = peg$parseintegerNode(); if (s0 === null) { s0 = peg$parsebooleanNode(); } } } return s0; } function peg$parsepath() { var s0, s1, s2, s3, s4, s5; s0 = peg$currPos; s1 = peg$parsepathIdent(); if (s1 !== null) { s2 = []; s3 = peg$currPos; s4 = peg$parseseperator(); if (s4 !== null) { s5 = peg$parsepathIdent(); if (s5 !== null) { peg$reportedPos = s3; s4 = peg$c55(s5); if (s4 === null) { peg$currPos = s3; s3 = s4; } else { s3 = s4; } } else { peg$currPos = s3; s3 = peg$c0; } } else { peg$currPos = s3; s3 = peg$c0; } while (s3 !== null) { s2.push(s3); s3 = peg$currPos; s4 = peg$parseseperator(); if (s4 !== null) { s5 = peg$parsepathIdent(); if (s5 !== null) { peg$reportedPos = s3; s4 = peg$c55(s5); if (s4 === null) { peg$currPos = s3; s3 = s4; } else { s3 = s4; } } else { peg$currPos = s3; s3 = peg$c0; } } else { peg$currPos = s3; s3 = peg$c0; } } if (s2 !== null) { peg$reportedPos = s0; s1 = peg$c56(s1,s2); if (s1 === null) { peg$currPos = s0; s0 = s1; } else { s0 = s1; } } else { peg$currPos = s0; s0 = peg$c0; } } else { peg$currPos = s0; s0 = peg$c0; } return s0; } function peg$parseseperator() { var s0, s1; peg$silentFails++; if (peg$c58.test(input.charAt(peg$currPos))) { s0 = input.charAt(peg$currPos); peg$currPos++; } else { s0 = null; if (peg$silentFails === 0) { peg$fail(peg$c59); } } peg$silentFails--; if (s0 === null) { s1 = null; if (peg$silentFails === 0) { peg$fail(peg$c57); } } return s0; } function peg$parsepathIdNode() { var s0, s1; s0 = peg$currPos; s1 = peg$parsepath(); if (s1 !== null) { peg$reportedPos = s0; s1 = peg$c60(s1); } if (s1 === null) { peg$currPos = s0; s0 = s1; } else { s0 = s1; } return s0; } function peg$parsestringNode() { var s0, s1; s0 = peg$currPos; s1 = peg$parsestring(); if (s1 !== null) { peg$reportedPos = s0; s1 = peg$c61(s1); } if (s1 === null) { peg$currPos = s0; s0 = s1; } else { s0 = s1; } return s0; } function peg$parseintegerNode() { var s0, s1; s0 = peg$currPos; s1 = peg$parseinteger(); if (s1 !== null) { peg$reportedPos = s0; s1 = peg$c62(s1); } if (s1 === null) { peg$currPos = s0; s0 = s1; } else { s0 = s1; } return s0; } function peg$parsebooleanNode() { var s0, s1; s0 = peg$currPos; s1 = peg$parseboolean(); if (s1 !== null) { peg$reportedPos = s0; s1 = peg$c63(s1); } if (s1 === null) { peg$currPos = s0; s0 = s1; } else { s0 = s1; } return s0; } function peg$parseboolean() { var s0, s1; peg$silentFails++; if (input.substr(peg$currPos, 4) === peg$c65) { s0 = peg$c65; peg$currPos += 4; } else { s0 = null; if (peg$silentFails === 0) { peg$fail(peg$c66); } } if (s0 === null) { if (input.substr(peg$currPos, 5) === peg$c67) { s0 = peg$c67; peg$currPos += 5; } else { s0 = null; if (peg$silentFails === 0) { peg$fail(peg$c68); } } } peg$silentFails--; if (s0 === null) { s1 = null; if (peg$silentFails === 0) { peg$fail(peg$c64); } } return s0; } function peg$parseinteger() { var s0, s1, s2, s3; peg$silentFails++; s0 = peg$currPos; s1 = peg$currPos; s2 = []; if (peg$c70.test(input.charAt(peg$currPos))) { s3 = input.charAt(peg$currPos); peg$currPos++; } else { s3 = null; if (peg$silentFails === 0) { peg$fail(peg$c71); } } if (s3 !== null) { while (s3 !== null) { s2.push(s3); if (peg$c70.test(input.charAt(peg$currPos))) { s3 = input.charAt(peg$currPos); peg$currPos++; } else { s3 = null; if (peg$silentFails === 0) { peg$fail(peg$c71); } } } } else { s2 = peg$c0; } if (s2 !== null) { s2 = input.substring(s1, peg$currPos); } s1 = s2; if (s1 !== null) { peg$reportedPos = s0; s1 = peg$c72(s1); } if (s1 === null) { peg$currPos = s0; s0 = s1; } else { s0 = s1; } peg$silentFails--; if (s0 === null) { s1 = null; if (peg$silentFails === 0) { peg$fail(peg$c69); } } return s0; } function peg$parsestring() { var s0, s1, s2, s3, s4; s0 = peg$currPos; s1 = peg$currPos; if (input.charCodeAt(peg$currPos) === 34) { s2 = peg$c73; peg$currPos++; } else { s2 = null; if (peg$silentFails === 0) { peg$fail(peg$c74); } } if (s2 !== null) { s3 = peg$parsehashDoubleQuoteStringValue(); if (s3 !== null) { if (input.charCodeAt(peg$currPos) === 34) { s4 = peg$c73; peg$currPos++; } else { s4 = null; if (peg$silentFails === 0) { peg$fail(peg$c74); } } if (s4 !== null) { s2 = [s2, s3, s4]; s1 = s2; } else { peg$currPos = s1; s1 = peg$c0; } } else { peg$currPos = s1; s1 = peg$c0; } } else { peg$currPos = s1; s1 = peg$c0; } if (s1 === null) { s1 = peg$currPos; if (input.charCodeAt(peg$currPos) === 39) { s2 = peg$c75; peg$currPos++; } else { s2 = null; if (peg$silentFails === 0) { peg$fail(peg$c76); } } if (s2 !== null) { s3 = peg$parsehashSingleQuoteStringValue(); if (s3 !== null) { if (input.charCodeAt(peg$currPos) === 39) { s4 = peg$c75; peg$currPos++; } else { s4 = null; if (peg$silentFails === 0) { peg$fail(peg$c76); } } if (s4 !== null) { s2 = [s2, s3, s4]; s1 = s2; } else { peg$currPos = s1; s1 = peg$c0; } } else { peg$currPos = s1; s1 = peg$c0; } } else { peg$currPos = s1; s1 = peg$c0; } } if (s1 !== null) { peg$reportedPos = s0; s1 = peg$c77(s1); } if (s1 === null) { peg$currPos = s0; s0 = s1; } else { s0 = s1; } return s0; } function peg$parsehashDoubleQuoteStringValue() { var s0, s1, s2, s3, s4; s0 = peg$currPos; s1 = []; s2 = peg$currPos; s3 = peg$currPos; peg$silentFails++; s4 = peg$parseTERM(); peg$silentFails--; if (s4 === null) { s3 = peg$c1; } else { peg$currPos = s3; s3 = peg$c0; } if (s3 !== null) { if (peg$c78.test(input.charAt(peg$currPos))) { s4 = input.charAt(peg$currPos); peg$currPos++; } else { s4 = null; if (peg$silentFails === 0) { peg$fail(peg$c79); } } if (s4 !== null) { s3 = [s3, s4]; s2 = s3; } else { peg$currPos = s2; s2 = peg$c0; } } else { peg$currPos = s2; s2 = peg$c0; } while (s2 !== null) { s1.push(s2); s2 = peg$currPos; s3 = peg$currPos; peg$silentFails++; s4 = peg$parseTERM(); peg$silentFails--; if (s4 === null) { s3 = peg$c1; } else { peg$currPos = s3; s3 = peg$c0; } if (s3 !== null) { if (peg$c78.test(input.charAt(peg$currPos))) { s4 = input.charAt(peg$currPos); peg$currPos++; } else { s4 = null; if (peg$silentFails === 0) { peg$fail(peg$c79); } } if (s4 !== null) { s3 = [s3, s4]; s2 = s3; } else { peg$currPos = s2; s2 = peg$c0; } } else { peg$currPos = s2; s2 = peg$c0; } } if (s1 !== null) { s1 = input.substring(s0, peg$currPos); } s0 = s1; return s0; } function peg$parsehashSingleQuoteStringValue() { var s0, s1, s2, s3, s4; s0 = peg$currPos; s1 = []; s2 = peg$currPos; s3 = peg$currPos; peg$silentFails++; s4 = peg$parseTERM(); peg$silentFails--; if (s4 === null) { s3 = peg$c1; } else { peg$currPos = s3; s3 = peg$c0; } if (s3 !== null) { if (peg$c80.test(input.charAt(peg$currPos))) { s4 = input.charAt(peg$currPos); peg$currPos++; } else { s4 = null; if (peg$silentFails === 0) { peg$fail(peg$c81); } } if (s4 !== null) { s3 = [s3, s4]; s2 = s3; } else { peg$currPos = s2; s2 = peg$c0; } } else { peg$currPos = s2; s2 = peg$c0; } while (s2 !== null) { s1.push(s2); s2 = peg$currPos; s3 = peg$currPos; peg$silentFails++; s4 = peg$parseTERM(); peg$silentFails--; if (s4 === null) { s3 = peg$c1; } else { peg$currPos = s3; s3 = peg$c0; } if (s3 !== null) { if (peg$c80.test(input.charAt(peg$currPos))) { s4 = input.charAt(peg$currPos); peg$currPos++; } else { s4 = null; if (peg$silentFails === 0) { peg$fail(peg$c81); } } if (s4 !== null) { s3 = [s3, s4]; s2 = s3; } else { peg$currPos = s2; s2 = peg$c0; } } else { peg$currPos = s2; s2 = peg$c0; } } if (s1 !== null) { s1 = input.substring(s0, peg$currPos); } s0 = s1; return s0; } function peg$parsealpha() { var s0; if (peg$c82.test(input.charAt(peg$currPos))) { s0 = input.charAt(peg$currPos); peg$currPos++; } else { s0 = null; if (peg$silentFails === 0) { peg$fail(peg$c83); } } return s0; } function peg$parsewhitespaceableTextNodes() { var s0, s1, s2, s3, s4; s0 = peg$currPos; s1 = peg$parseindentation(); if (s1 !== null) { s2 = peg$parsetextNodes(); if (s2 !== null) { s3 = []; s4 = peg$parsewhitespaceableTextNodes(); while (s4 !== null) { s3.push(s4); s4 = peg$parsewhitespaceableTextNodes(); } if (s3 !== null) { s4 = peg$parseanyDedent(); if (s4 !== null) { peg$reportedPos = s0; s1 = peg$c84(s1,s2,s3); if (s1 === null) { peg$currPos = s0; s0 = s1; } else { s0 = s1; } } else { peg$currPos = s0; s0 = peg$c0; } } else { peg$currPos = s0; s0 = peg$c0; } } else { peg$currPos = s0; s0 = peg$c0; } } else { peg$currPos = s0; s0 = peg$c0; } if (s0 === null) { s0 = peg$parsetextNodes(); } return s0; } function peg$parsetextLineStart() { var s0, s1, s2; s0 = peg$currPos; if (peg$c85.test(input.charAt(peg$currPos))) { s1 = input.charAt(peg$currPos); peg$currPos++; } else { s1 = null; if (peg$silentFails === 0) { peg$fail(peg$c86); } } if (s1 !== null) { if (input.charCodeAt(peg$currPos) === 32) { s2 = peg$c25; peg$currPos++; } else { s2 = null; if (peg$silentFails === 0) { peg$fail(peg$c26); } } if (s2 === null) { s2 = peg$c1; } if (s2 !== null) { peg$reportedPos = s0; s1 = peg$c52(s1); if (s1 === null) { peg$currPos = s0; s0 = s1; } else { s0 = s1; } } else { peg$currPos = s0; s0 = peg$c0; } } else { peg$currPos = s0; s0 = peg$c0; } if (s0 === null) { s0 = peg$currPos; s1 = peg$currPos; peg$silentFails++; if (input.charCodeAt(peg$currPos) === 60) { s2 = peg$c87; peg$currPos++; } else { s2 = null; if (peg$silentFails === 0) { peg$fail(peg$c88); } } peg$silentFails--; if (s2 !== null) { peg$currPos = s1; s1 = peg$c1; } else { s1 = peg$c0; } if (s1 !== null) { peg$reportedPos = s0; s1 = peg$c89(); } if (s1 === null) { peg$currPos = s0; s0 = s1; } else { s0 = s1; } } return s0; } function peg$parsetextLine() { var s0, s1, s2, s3, s4, s5, s6; s0 = peg$currPos; s1 = peg$parsetextLineStart(); if (s1 !== null) { s2 = peg$parsetextNodes(); if (s2 !== null) { s3 = peg$currPos; s4 = peg$parseindentation(); if (s4 !== null) { s5 = []; s6 = peg$parsewhitespaceableTextNodes(); while (s6 !== null) { s5.push(s6); s6 = peg$parsewhitespaceableTextNodes(); } if (s5 !== null) { s6 = peg$parseDEDENT(); if (s6 !== null) { s4 = [s4, s5, s6]; s3 = s4; } else { peg$currPos = s3; s3 = peg$c0; } } else { peg$currPos = s3; s3 = peg$c0; } } else { peg$currPos = s3; s3 = peg$c0; } if (s3 === null) { s3 = peg$c1; } if (s3 !== null) { peg$reportedPos = s0; s1 = peg$c90(s1,s2,s3); if (s1 === null) { peg$currPos = s0; s0 = s1; } else { s0 = s1; } } else { peg$currPos = s0; s0 = peg$c0; } } else { peg$currPos = s0; s0 = peg$c0; } } else { peg$currPos = s0; s0 = peg$c0; } return s0; } function peg$parsetextNodes() { var s0, s1, s2, s3, s4, s5; s0 = peg$currPos; s1 = peg$parsepreMustacheText(); if (s1 === null) { s1 = peg$c1; } if (s1 !== null) { s2 = []; s3 = peg$currPos; s4 = peg$parserawMustache(); if (s4 !== null) { s5 = peg$parsepreMustacheText(); if (s5 === null) { s5 = peg$c1; } if (s5 !== null) { s4 = [s4, s5]; s3 = s4; } else { peg$currPos = s3; s3 = peg$c0; } } else { peg$currPos = s3; s3 = peg$c0; } while (s3 !== null) { s2.push(s3); s3 = peg$currPos; s4 = peg$parserawMustache(); if (s4 !== null) { s5 = peg$parsepreMustacheText(); if (s5 === null) { s5 = peg$c1; } if (s5 !== null) { s4 = [s4, s5]; s3 = s4; } else { peg$currPos = s3; s3 = peg$c0; } } else { peg$currPos = s3; s3 = peg$c0; } } if (s2 !== null) { s3 = peg$parseTERM(); if (s3 !== null) { peg$reportedPos = s0; s1 = peg$c91(s1,s2); if (s1 === null) { peg$currPos = s0; s0 = s1; } else { s0 = s1; } } else { peg$currPos = s0; s0 = peg$c0; } } else { peg$currPos = s0; s0 = peg$c0; } } else { peg$currPos = s0; s0 = peg$c0; } return s0; } function peg$parseattributeTextNodes() { var s0, s1, s2, s3; s0 = peg$currPos; if (input.charCodeAt(peg$currPos) === 34) { s1 = peg$c73; peg$currPos++; } else { s1 = null; if (peg$silentFails === 0) { peg$fail(peg$c74); } } if (s1 !== null) { s2 = peg$parseattributeTextNodesInner(); if (s2 !== null) { if (input.charCodeAt(peg$currPos) === 34) { s3 = peg$c73; peg$currPos++; } else { s3 = null; if (peg$silentFails === 0) { peg$fail(peg$c74); } } if (s3 !== null) { peg$reportedPos = s0; s1 = peg$c43(s2); if (s1 === null) { peg$currPos = s0; s0 = s1; } else { s0 = s1; } } else { peg$currPos = s0; s0 = peg$c0; } } else { peg$currPos = s0; s0 = peg$c0; } } else { peg$currPos = s0; s0 = peg$c0; } if (s0 === null) { s0 = peg$currPos; if (input.charCodeAt(peg$currPos) === 39) { s1 = peg$c75; peg$currPos++; } else { s1 = null; if (peg$silentFails === 0) { peg$fail(peg$c76); } } if (s1 !== null) { s2 = peg$parseattributeTextNodesInnerSingle(); if (s2 !== null) { if (input.charCodeAt(peg$currPos) === 39) { s3 = peg$c75; peg$currPos++; } else { s3 = null; if (peg$silentFails === 0) { peg$fail(peg$c76); } } if (s3 !== null) { peg$reportedPos = s0; s1 = peg$c43(s2); if (s1 === null) { peg$currPos = s0; s0 = s1; } else { s0 = s1; } } else { peg$currPos = s0; s0 = peg$c0; } } else { peg$currPos = s0; s0 = peg$c0; } } else { peg$currPos = s0; s0 = peg$c0; } } return s0; } function peg$parseattributeTextNodesInner() { var s0, s1, s2, s3, s4, s5; s0 = peg$currPos; s1 = peg$parsepreAttrMustacheText(); if (s1 === null) { s1 = peg$c1; } if (s1 !== null) { s2 = []; s3 = peg$currPos; s4 = peg$parserawMustache(); if (s4 !== null) { s5 = peg$parsepreAttrMustacheText(); if (s5 === null) { s5 = peg$c1; } if (s5 !== null) { s4 = [s4, s5]; s3 = s4; } else { peg$currPos = s3; s3 = peg$c0; } } else { peg$currPos = s3; s3 = peg$c0; } while (s3 !== null) { s2.push(s3); s3 = peg$currPos; s4 = peg$parserawMustache(); if (s4 !== null) { s5 = peg$parsepreAttrMustacheText(); if (s5 === null) { s5 = peg$c1; } if (s5 !== null) { s4 = [s4, s5]; s3 = s4; } else { peg$currPos = s3; s3 = peg$c0; } } else { peg$currPos = s3; s3 = peg$c0; } } if (s2 !== null) { peg$reportedPos = s0; s1 = peg$c92(s1,s2); if (s1 === null) { peg$currPos = s0; s0 = s1; } else { s0 = s1; } } else { peg$currPos = s0; s0 = peg$c0; } } else { peg$currPos = s0; s0 = peg$c0; } return s0; } function peg$parseattributeTextNodesInnerSingle() { var s0, s1, s2, s3, s4, s5; s0 = peg$currPos; s1 = peg$parsepreAttrMustacheTextSingle(); if (s1 === null) { s1 = peg$c1; } if (s1 !== null) { s2 = []; s3 = peg$currPos; s4 = peg$parserawMustache(); if (s4 !== null) { s5 = peg$parsepreAttrMustacheTextSingle(); if (s5 === null) { s5 = peg$c1; } if (s5 !== null) { s4 = [s4, s5]; s3 = s4; } else { peg$currPos = s3; s3 = peg$c0; } } else { peg$currPos = s3; s3 = peg$c0; } while (s3 !== null) { s2.push(s3); s3 = peg$currPos; s4 = peg$parserawMustache(); if (s4 !== null) { s5 = peg$parsepreAttrMustacheTextSingle(); if (s5 === null) { s5 = peg$c1; } if (s5 !== null) { s4 = [s4, s5]; s3 = s4; } else { peg$currPos = s3; s3 = peg$c0; } } else { peg$currPos = s3; s3 = peg$c0; } } if (s2 !== null) { peg$reportedPos = s0; s1 = peg$c92(s1,s2); if (s1 === null) { peg$currPos = s0; s0 = s1; } else { s0 = s1; } } else { peg$currPos = s0; s0 = peg$c0; } } else { peg$currPos = s0; s0 = peg$c0; } return s0; } function peg$parserawMustache() { var s0; s0 = peg$parserawMustacheUnescaped(); if (s0 === null) { s0 = peg$parserawMustacheEscaped(); } return s0; } function peg$parserawMustacheEscaped() { var s0, s1, s2, s3, s4, s5; s0 = peg$currPos; s1 = peg$parsedoubleOpen(); if (s1 !== null) { s2 = peg$parse_(); if (s2 !== null) { s3 = peg$parseinMustache(); if (s3 !== null) { s4 = peg$parse_(); if (s4 !== null) { s5 = peg$parsedoubleClose(); if (s5 !== null) { peg$reportedPos = s0; s1 = peg$c93(s3); if (s1 === null) { peg$currPos = s0; s0 = s1; } else { s0 = s1; } } else { peg$currPos = s0; s0 = peg$c0; } } else { peg$currPos = s0; s0 = peg$c0; } } else { peg$currPos = s0; s0 = peg$c0; } } else { peg$currPos = s0; s0 = peg$c0; } } else { peg$currPos = s0; s0 = peg$c0; } if (s0 === null) { s0 = peg$currPos; s1 = peg$parsehashStacheOpen(); if (s1 !== null) { s2 = peg$parse_(); if (s2 !== null) { s3 = peg$parseinMustache(); if (s3 !== null) { s4 = peg$parse_(); if (s4 !== null) { s5 = peg$parsehashStacheClose(); if (s5 !== null) { peg$reportedPos = s0; s1 = peg$c93(s3); if (s1 === null) { peg$currPos = s0; s0 = s1; } else { s0 = s1; } } else { peg$currPos = s0; s0 = peg$c0; } } else { peg$currPos = s0; s0 = peg$c0; } } else { peg$currPos = s0; s0 = peg$c0; } } else { peg$currPos = s0; s0 = peg$c0; } } else { peg$currPos = s0; s0 = peg$c0; } } return s0; } function peg$parserawMustacheUnescaped() { var s0, s1, s2, s3, s4, s5; s0 = peg$currPos; s1 = peg$parsetripleOpen(); if (s1 !== null) { s2 = peg$parse_(); if (s2 !== null) { s3 = peg$parseinMustache(); if (s3 !== null) { s4 = peg$parse_(); if (s4 !== null) { s5 = peg$parsetripleClose(); if (s5 !== null) { peg$reportedPos = s0; s1 = peg$c94(s3); if (s1 === null) { peg$currPos = s0; s0 = s1; } else { s0 = s1; } } else { peg$currPos = s0; s0 = peg$c0; } } else { peg$currPos = s0; s0 = peg$c0; } } else { peg$currPos = s0; s0 = peg$c0; } } else { peg$currPos = s0; s0 = peg$c0; } } else { peg$currPos = s0; s0 = peg$c0; } return s0; } function peg$parsepreAttrMustacheText() { var s0, s1, s2, s3; s0 = peg$currPos; s1 = peg$currPos; s2 = []; s3 = peg$parsepreAttrMustacheUnit(); if (s3 !== null) { while (s3 !== null) { s2.push(s3); s3 = peg$parsepreAttrMustacheUnit(); } } else { s2 = peg$c0; } if (s2 !== null) { s2 = input.substring(s1, peg$currPos); } s1 = s2; if (s1 !== null) { peg$reportedPos = s0; s1 = peg$c95(s1); } if (s1 === null) { peg$currPos = s0; s0 = s1; } else { s0 = s1; } return s0; } function peg$parsepreAttrMustacheTextSingle() { var s0, s1, s2, s3; s0 = peg$currPos; s1 = peg$currPos; s2 = []; s3 = peg$parsepreAttrMustacheUnitSingle(); if (s3 !== null) { while (s3 !== null) { s2.push(s3); s3 = peg$parsepreAttrMustacheUnitSingle(); } } else { s2 = peg$c0; } if (s2 !== null) { s2 = input.substring(s1, peg$currPos); } s1 = s2; if (s1 !== null) { peg$reportedPos = s0; s1 = peg$c95(s1); } if (s1 === null) { peg$currPos = s0; s0 = s1; } else { s0 = s1; } return s0; } function peg$parsepreAttrMustacheUnit() { var s0, s1, s2; s0 = peg$currPos; s1 = peg$currPos; peg$silentFails++; s2 = peg$parsenonMustacheUnit(); if (s2 === null) { if (input.charCodeAt(peg$currPos) === 34) { s2 = peg$c73; peg$currPos++; } else { s2 = null; if (peg$silentFails === 0) { peg$fail(peg$c74); } } } peg$silentFails--; if (s2 === null) { s1 = peg$c1; } else { peg$currPos = s1; s1 = peg$c0; } if (s1 !== null) { if (input.length > peg$currPos) { s2 = input.charAt(peg$currPos); peg$currPos++; } else { s2 = null; if (peg$silentFails === 0) { peg$fail(peg$c96); } } if (s2 !== null) { peg$reportedPos = s0; s1 = peg$c28(s2); if (s1 === null) { peg$currPos = s0; s0 = s1; } else { s0 = s1; } } else { peg$currPos = s0; s0 = peg$c0; } } else { peg$currPos = s0; s0 = peg$c0; } return s0; } function peg$parsepreAttrMustacheUnitSingle() { var s0, s1, s2; s0 = peg$currPos; s1 = peg$currPos; peg$silentFails++; s2 = peg$parsenonMustacheUnit(); if (s2 === null) { if (input.charCodeAt(peg$currPos) === 39) { s2 = peg$c75; peg$currPos++; } else { s2 = null; if (peg$silentFails === 0) { peg$fail(peg$c76); } } } peg$silentFails--; if (s2 === null) { s1 = peg$c1; } else { peg$currPos = s1; s1 = peg$c0; } if (s1 !== null) { if (input.length > peg$currPos) { s2 = input.charAt(peg$currPos); peg$currPos++; } else { s2 = null; if (peg$silentFails === 0) { peg$fail(peg$c96); } } if (s2 !== null) { peg$reportedPos = s0; s1 = peg$c28(s2); if (s1 === null) { peg$currPos = s0; s0 = s1; } else { s0 = s1; } } else { peg$currPos = s0; s0 = peg$c0; } } else { peg$currPos = s0; s0 = peg$c0; } return s0; } function peg$parsepreMustacheText() { var s0, s1, s2, s3; s0 = peg$currPos; s1 = peg$currPos; s2 = []; s3 = peg$parsepreMustacheUnit(); if (s3 !== null) { while (s3 !== null) { s2.push(s3); s3 = peg$parsepreMustacheUnit(); } } else { s2 = peg$c0; } if (s2 !== null) { s2 = input.substring(s1, peg$currPos); } s1 = s2; if (s1 !== null) { peg$reportedPos = s0; s1 = peg$c95(s1); } if (s1 === null) { peg$currPos = s0; s0 = s1; } else { s0 = s1; } return s0; } function peg$parsepreMustacheUnit() { var s0, s1, s2; s0 = peg$currPos; s1 = peg$currPos; peg$silentFails++; s2 = peg$parsenonMustacheUnit(); peg$silentFails--; if (s2 === null) { s1 = peg$c1; } else { peg$currPos = s1; s1 = peg$c0; } if (s1 !== null) { if (input.length > peg$currPos) { s2 = input.charAt(peg$currPos); peg$currPos++; } else { s2 = null; if (peg$silentFails === 0) { peg$fail(peg$c96); } } if (s2 !== null) { peg$reportedPos = s0; s1 = peg$c28(s2); if (s1 === null) { peg$currPos = s0; s0 = s1; } else { s0 = s1; } } else { peg$currPos = s0; s0 = peg$c0; } } else { peg$currPos = s0; s0 = peg$c0; } return s0; } function peg$parsenonMustacheUnit() { var s0; s0 = peg$parsetripleOpen(); if (s0 === null) { s0 = peg$parsedoubleOpen(); if (s0 === null) { s0 = peg$parsehashStacheOpen(); if (s0 === null) { s0 = peg$parseanyDedent(); if (s0 === null) { s0 = peg$parseTERM(); } } } } return s0; } function peg$parserawMustacheSingle() { var s0, s1, s2, s3, s4, s5; s0 = peg$currPos; s1 = peg$parsesingleOpen(); if (s1 !== null) { s2 = peg$parse_(); if (s2 !== null) { s3 = peg$parseinMustache(); if (s3 !== null) { s4 = peg$parse_(); if (s4 !== null) { s5 = peg$parsesingleClose(); if (s5 !== null) { peg$reportedPos = s0; s1 = peg$c93(s3); if (s1 === null) { peg$currPos = s0; s0 = s1; } else { s0 = s1; } } else { peg$currPos = s0; s0 = peg$c0; } } else { peg$currPos = s0; s0 = peg$c0; } } else { peg$currPos = s0; s0 = peg$c0; } } else { peg$currPos = s0; s0 = peg$c0; } } else { peg$currPos = s0; s0 = peg$c0; } return s0; } function peg$parseinTagMustache() { var s0; s0 = peg$parserawMustacheSingle(); if (s0 === null) { s0 = peg$parserawMustacheUnescaped(); if (s0 === null) { s0 = peg$parserawMustacheEscaped(); } } return s0; } function peg$parsesingleOpen() { var s0, s1; peg$silentFails++; if (input.charCodeAt(peg$currPos) === 123) { s0 = peg$c98; peg$currPos++; } else { s0 = null; if (peg$silentFails === 0) { peg$fail(peg$c99); } } peg$silentFails--; if (s0 === null) { s1 = null; if (peg$silentFails === 0) { peg$fail(peg$c97); } } return s0; } function peg$parsedoubleOpen() { var s0, s1; peg$silentFails++; if (input.substr(peg$currPos, 2) === peg$c101) { s0 = peg$c101; peg$currPos += 2; } else { s0 = null; if (peg$silentFails === 0) { peg$fail(peg$c102); } } peg$silentFails--; if (s0 === null) { s1 = null; if (peg$silentFails === 0) { peg$fail(peg$c100); } } return s0; } function peg$parsetripleOpen() { var s0, s1; peg$silentFails++; if (input.substr(peg$currPos, 3) === peg$c104) { s0 = peg$c104; peg$currPos += 3; } else { s0 = null; if (peg$silentFails === 0) { peg$fail(peg$c105); } } peg$silentFails--; if (s0 === null) { s1 = null; if (peg$silentFails === 0) { peg$fail(peg$c103); } } return s0; } function peg$parsesingleClose() { var s0, s1; peg$silentFails++; if (input.charCodeAt(peg$currPos) === 125) { s0 = peg$c107; peg$currPos++; } else { s0 = null; if (peg$silentFails === 0) { peg$fail(peg$c108); } } peg$silentFails--; if (s0 === null) { s1 = null; if (peg$silentFails === 0) { peg$fail(peg$c106); } } return s0; } function peg$parsedoubleClose() { var s0, s1; peg$silentFails++; if (input.substr(peg$currPos, 2) === peg$c110) { s0 = peg$c110; peg$currPos += 2; } else { s0 = null; if (peg$silentFails === 0) { peg$fail(peg$c111); } } peg$silentFails--; if (s0 === null) { s1 = null; if (peg$silentFails === 0) { peg$fail(peg$c109); } } return s0; } function peg$parsetripleClose() { var s0, s1; peg$silentFails++; if (input.substr(peg$currPos, 3) === peg$c113) { s0 = peg$c113; peg$currPos += 3; } else { s0 = null; if (peg$silentFails === 0) { peg$fail(peg$c114); } } peg$silentFails--; if (s0 === null) { s1 = null; if (peg$silentFails === 0) { peg$fail(peg$c112); } } return s0; } function peg$parsehashStacheOpen() { var s0, s1; peg$silentFails++; if (input.substr(peg$currPos, 2) === peg$c116) { s0 = peg$c116; peg$currPos += 2; } else { s0 = null; if (peg$silentFails === 0) { peg$fail(peg$c117); } } peg$silentFails--; if (s0 === null) { s1 = null; if (peg$silentFails === 0) { peg$fail(peg$c115); } } return s0; } function peg$parsehashStacheClose() { var s0, s1; peg$silentFails++; if (input.charCodeAt(peg$currPos) === 125) { s0 = peg$c107; peg$currPos++; } else { s0 = null; if (peg$silentFails === 0) { peg$fail(peg$c108); } } peg$silentFails--; if (s0 === null) { s1 = null; if (peg$silentFails === 0) { peg$fail(peg$c118); } } return s0; } function peg$parseequalSign() { var s0, s1, s2; s0 = peg$currPos; if (input.substr(peg$currPos, 2) === peg$c119) { s1 = peg$c119; peg$currPos += 2; } else { s1 = null; if (peg$silentFails === 0) { peg$fail(peg$c120); } } if (s1 !== null) { if (input.charCodeAt(peg$currPos) === 32) { s2 = peg$c25; peg$currPos++; } else { s2 = null; if (peg$silentFails === 0) { peg$fail(peg$c26); } } if (s2 === null) { s2 = peg$c1; } if (s2 !== null) { peg$reportedPos = s0; s1 = peg$c121(); if (s1 === null) { peg$currPos = s0; s0 = s1; } else { s0 = s1; } } else { peg$currPos = s0; s0 = peg$c0; } } else { peg$currPos = s0; s0 = peg$c0; } if (s0 === null) { s0 = peg$currPos; if (input.charCodeAt(peg$currPos) === 61) { s1 = peg$c4; peg$currPos++; } else { s1 = null; if (peg$silentFails === 0) { peg$fail(peg$c5); } } if (s1 !== null) { if (input.charCodeAt(peg$currPos) === 32) { s2 = peg$c25; peg$currPos++; } else { s2 = null; if (peg$silentFails === 0) { peg$fail(peg$c26); } } if (s2 === null) { s2 = peg$c1; } if (s2 !== null) { peg$reportedPos = s0; s1 = peg$c122(); if (s1 === null) { peg$currPos = s0; s0 = s1; } else { s0 = s1; } } else { peg$currPos = s0; s0 = peg$c0; } } else { peg$currPos = s0; s0 = peg$c0; } } return s0; } function peg$parsehtmlStart() { var s0, s1, s2, s3; s0 = peg$currPos; s1 = peg$parsehtmlTagName(); if (s1 === null) { s1 = peg$c1; } if (s1 !== null) { s2 = peg$parseshorthandAttributes(); if (s2 === null) { s2 = peg$c1; } if (s2 !== null) { peg$reportedPos = peg$currPos; s3 = peg$c123(s1,s2); if (s3) { s3 = peg$c1; } else { s3 = peg$c0; } if (s3 !== null) { s1 = [s1, s2, s3]; s0 = s1; } else { peg$currPos = s0; s0 = peg$c0; } } else { peg$currPos = s0; s0 = peg$c0; } } else { peg$currPos = s0; s0 = peg$c0; } return s0; } function peg$parseinHtmlTag() { var s0, s1, s2, s3, s4; s0 = peg$currPos; s1 = peg$parsehtmlStart(); if (s1 !== null) { s2 = []; s3 = peg$parseinTagMustache(); while (s3 !== null) { s2.push(s3); s3 = peg$parseinTagMustache(); } if (s2 !== null) { s3 = []; s4 = peg$parsefullAttribute(); while (s4 !== null) { s3.push(s4); s4 = peg$parsefullAttribute(); } if (s3 !== null) { peg$reportedPos = s0; s1 = peg$c124(s1,s2,s3); if (s1 === null) { peg$currPos = s0; s0 = s1; } else { s0 = s1; } } else { peg$currPos = s0; s0 = peg$c0; } } else { peg$currPos = s0; s0 = peg$c0; } } else { peg$currPos = s0; s0 = peg$c0; } return s0; } function peg$parseshorthandAttributes() { var s0, s1, s2, s3; s0 = peg$currPos; s1 = []; s2 = peg$currPos; s3 = peg$parseidShorthand(); if (s3 !== null) { peg$reportedPos = s2; s3 = peg$c125(s3); } if (s3 === null) { peg$currPos = s2; s2 = s3; } else { s2 = s3; } if (s2 === null) { s2 = peg$currPos; s3 = peg$parseclassShorthand(); if (s3 !== null) { peg$reportedPos = s2; s3 = peg$c126(s3); } if (s3 === null) { peg$currPos = s2; s2 = s3; } else { s2 = s3; } } if (s2 !== null) { while (s2 !== null) { s1.push(s2); s2 = peg$currPos; s3 = peg$parseidShorthand(); if (s3 !== null) { peg$reportedPos = s2; s3 = peg$c125(s3); } if (s3 === null) { peg$currPos = s2; s2 = s3; } else { s2 = s3; } if (s2 === null) { s2 = peg$currPos; s3 = peg$parseclassShorthand(); if (s3 !== null) { peg$reportedPos = s2; s3 = peg$c126(s3); } if (s3 === null) { peg$currPos = s2; s2 = s3; } else { s2 = s3; } } } } else { s1 = peg$c0; } if (s1 !== null) { peg$reportedPos = s0; s1 = peg$c127(s1); } if (s1 === null) { peg$currPos = s0; s0 = s1; } else { s0 = s1; } return s0; } function peg$parsefullAttribute() { var s0, s1, s2; s0 = peg$currPos; s1 = []; if (input.charCodeAt(peg$currPos) === 32) { s2 = peg$c25; peg$currPos++; } else { s2 = null; if (peg$silentFails === 0) { peg$fail(peg$c26); } } if (s2 !== null) { while (s2 !== null) { s1.push(s2); if (input.charCodeAt(peg$currPos) === 32) { s2 = peg$c25; peg$currPos++; } else { s2 = null; if (peg$silentFails === 0) { peg$fail(peg$c26); } } } } else { s1 = peg$c0; } if (s1 !== null) { s2 = peg$parseactionAttribute(); if (s2 === null) { s2 = peg$parseboundAttribute(); if (s2 === null) { s2 = peg$parserawMustacheAttribute(); if (s2 === null) { s2 = peg$parsenormalAttribute(); } } } if (s2 !== null) { peg$reportedPos = s0; s1 = peg$c128(s2); if (s1 === null) { peg$currPos = s0; s0 = s1; } else { s0 = s1; } } else { peg$currPos = s0; s0 = peg$c0; } } else { peg$currPos = s0; s0 = peg$c0; } return s0; } function peg$parseboundAttributeValueChar() { var s0; if (peg$c129.test(input.charAt(peg$currPos))) { s0 = input.charAt(peg$currPos); peg$currPos++; } else { s0 = null; if (peg$silentFails === 0) { peg$fail(peg$c130); } } return s0; } function peg$parseactionValue() { var s0, s1; s0 = peg$parsequotedActionValue(); if (s0 === null) { s0 = peg$currPos; s1 = peg$parsepathIdNode(); if (s1 !== null) { peg$reportedPos = s0; s1 = peg$c131(s1); } if (s1 === null) { peg$currPos = s0; s0 = s1; } else { s0 = s1; } } return s0; } function peg$parsequotedActionValue() { var s0, s1, s2, s3, s4; s0 = peg$currPos; s1 = peg$currPos; if (input.charCodeAt(peg$currPos) === 34) { s2 = peg$c73; peg$currPos++; } else { s2 = null; if (peg$silentFails === 0) { peg$fail(peg$c74); } } if (s2 !== null) { s3 = peg$parseinMustache(); if (s3 !== null) { if (input.charCodeAt(peg$currPos) === 34) { s4 = peg$c73; peg$currPos++; } else { s4 = null; if (peg$silentFails === 0) { peg$fail(peg$c74); } } if (s4 !== null) { s2 = [s2, s3, s4]; s1 = s2; } else { peg$currPos = s1; s1 = peg$c0; } } else { peg$currPos = s1; s1 = peg$c0; } } else { peg$currPos = s1; s1 = peg$c0; } if (s1 === null) { s1 = peg$currPos; if (input.charCodeAt(peg$currPos) === 39) { s2 = peg$c75; peg$currPos++; } else { s2 = null; if (peg$silentFails === 0) { peg$fail(peg$c76); } } if (s2 !== null) { s3 = peg$parseinMustache(); if (s3 !== null) { if (input.charCodeAt(peg$currPos) === 39) { s4 = peg$c75; peg$currPos++; } else { s4 = null; if (peg$silentFails === 0) { peg$fail(peg$c76); } } if (s4 !== null) { s2 = [s2, s3, s4]; s1 = s2; } else { peg$currPos = s1; s1 = peg$c0; } } else { peg$currPos = s1; s1 = peg$c0; } } else { peg$currPos = s1; s1 = peg$c0; } } if (s1 !== null) { peg$reportedPos = s0; s1 = peg$c77(s1); } if (s1 === null) { peg$currPos = s0; s0 = s1; } else { s0 = s1; } return s0; } function peg$parseactionAttribute() { var s0, s1, s2, s3; s0 = peg$currPos; s1 = peg$parseknownEvent(); if (s1 !== null) { if (input.charCodeAt(peg$currPos) === 61) { s2 = peg$c4; peg$currPos++; } else { s2 = null; if (peg$silentFails === 0) { peg$fail(peg$c5); } } if (s2 !== null) { s3 = peg$parseactionValue(); if (s3 !== null) { peg$reportedPos = s0; s1 = peg$c132(s1,s3); if (s1 === null) { peg$currPos = s0; s0 = s1; } else { s0 = s1; } } else { peg$currPos = s0; s0 = peg$c0; } } else { peg$currPos = s0; s0 = peg$c0; } } else { peg$currPos = s0; s0 = peg$c0; } return s0; } function peg$parseboundAttributeValue() { var s0, s1, s2, s3, s4, s5; s0 = peg$currPos; if (input.charCodeAt(peg$currPos) === 123) { s1 = peg$c98; peg$currPos++; } else { s1 = null; if (peg$silentFails === 0) { peg$fail(peg$c99); } } if (s1 !== null) { s2 = peg$parse_(); if (s2 !== null) { s3 = peg$currPos; s4 = []; s5 = peg$parseboundAttributeValueChar(); if (s5 === null) { if (input.charCodeAt(peg$currPos) === 32) { s5 = peg$c25; peg$currPos++; } else { s5 = null; if (peg$silentFails === 0) { peg$fail(peg$c26); } } } if (s5 !== null) { while (s5 !== null) { s4.push(s5); s5 = peg$parseboundAttributeValueChar(); if (s5 === null) { if (input.charCodeAt(peg$currPos) === 32) { s5 = peg$c25; peg$currPos++; } else { s5 = null; if (peg$silentFails === 0) { peg$fail(peg$c26); } } } } } else { s4 = peg$c0; } if (s4 !== null) { s4 = input.substring(s3, peg$currPos); } s3 = s4; if (s3 !== null) { s4 = peg$parse_(); if (s4 !== null) { if (input.charCodeAt(peg$currPos) === 125) { s5 = peg$c107; peg$currPos++; } else { s5 = null; if (peg$silentFails === 0) { peg$fail(peg$c108); } } if (s5 !== null) { peg$reportedPos = s0; s1 = peg$c133(s3); if (s1 === null) { peg$currPos = s0; s0 = s1; } else { s0 = s1; } } else { peg$currPos = s0; s0 = peg$c0; } } else { peg$currPos = s0; s0 = peg$c0; } } else { peg$currPos = s0; s0 = peg$c0; } } else { peg$currPos = s0; s0 = peg$c0; } } else { peg$currPos = s0; s0 = peg$c0; } if (s0 === null) { s0 = peg$currPos; s1 = []; s2 = peg$parseboundAttributeValueChar(); if (s2 !== null) { while (s2 !== null) { s1.push(s2); s2 = peg$parseboundAttributeValueChar(); } } else { s1 = peg$c0; } if (s1 !== null) { s1 = input.substring(s0, peg$currPos); } s0 = s1; } return s0; } function peg$parseboundAttribute() { var s0, s1, s2, s3, s4, s5; s0 = peg$currPos; s1 = peg$parsekey(); if (s1 !== null) { if (input.charCodeAt(peg$currPos) === 61) { s2 = peg$c4; peg$currPos++; } else { s2 = null; if (peg$silentFails === 0) { peg$fail(peg$c5); } } if (s2 !== null) { s3 = peg$parseboundAttributeValue(); if (s3 !== null) { s4 = peg$currPos; peg$silentFails++; if (input.charCodeAt(peg$currPos) === 33) { s5 = peg$c134; peg$currPos++; } else { s5 = null; if (peg$silentFails === 0) { peg$fail(peg$c135); } } peg$silentFails--; if (s5 === null) { s4 = peg$c1; } else { peg$currPos = s4; s4 = peg$c0; } if (s4 !== null) { peg$reportedPos = peg$currPos; s5 = peg$c136(s1,s3); if (s5) { s5 = peg$c1; } else { s5 = peg$c0; } if (s5 !== null) { peg$reportedPos = s0; s1 = peg$c137(s1,s3); if (s1 === null) { peg$currPos = s0; s0 = s1; } else { s0 = s1; } } else { peg$currPos = s0; s0 = peg$c0; } } else { peg$currPos = s0; s0 = peg$c0; } } else { peg$currPos = s0; s0 = peg$c0; } } else { peg$currPos = s0; s0 = peg$c0; } } else { peg$currPos = s0; s0 = peg$c0; } return s0; } function peg$parserawMustacheAttribute() { var s0, s1, s2, s3; s0 = peg$currPos; s1 = peg$parsekey(); if (s1 !== null) { if (input.charCodeAt(peg$currPos) === 61) { s2 = peg$c4; peg$currPos++; } else { s2 = null; if (peg$silentFails === 0) { peg$fail(peg$c5); } } if (s2 !== null) { s3 = peg$parsepathIdNode(); if (s3 !== null) { peg$reportedPos = s0; s1 = peg$c138(s1,s3); if (s1 === null) { peg$currPos = s0; s0 = s1; } else { s0 = s1; } } else { peg$currPos = s0; s0 = peg$c0; } } else { peg$currPos = s0; s0 = peg$c0; } } else { peg$currPos = s0; s0 = peg$c0; } return s0; } function peg$parsenormalAttribute() { var s0, s1, s2, s3; s0 = peg$currPos; s1 = peg$parsekey(); if (s1 !== null) { if (input.charCodeAt(peg$currPos) === 61) { s2 = peg$c4; peg$currPos++; } else { s2 = null; if (peg$silentFails === 0) { peg$fail(peg$c5); } } if (s2 !== null) { s3 = peg$parseattributeTextNodes(); if (s3 !== null) { peg$reportedPos = s0; s1 = peg$c139(s1,s3); if (s1 === null) { peg$currPos = s0; s0 = s1; } else { s0 = s1; } } else { peg$currPos = s0; s0 = peg$c0; } } else { peg$currPos = s0; s0 = peg$c0; } } else { peg$currPos = s0; s0 = peg$c0; } return s0; } function peg$parseattributeName() { var s0, s1, s2; s0 = peg$currPos; s1 = []; s2 = peg$parseattributeChar(); while (s2 !== null) { s1.push(s2); s2 = peg$parseattributeChar(); } if (s1 !== null) { s1 = input.substring(s0, peg$currPos); } s0 = s1; return s0; } function peg$parseattributeValue() { var s0; s0 = peg$parsestring(); if (s0 === null) { s0 = peg$parseparam(); } return s0; } function peg$parseattributeChar() { var s0; s0 = peg$parsealpha(); if (s0 === null) { if (peg$c70.test(input.charAt(peg$currPos))) { s0 = input.charAt(peg$currPos); peg$currPos++; } else { s0 = null; if (peg$silentFails === 0) { peg$fail(peg$c71); } } if (s0 === null) { if (input.charCodeAt(peg$currPos) === 95) { s0 = peg$c140; peg$currPos++; } else { s0 = null; if (peg$silentFails === 0) { peg$fail(peg$c141); } } if (s0 === null) { if (input.charCodeAt(peg$currPos) === 45) { s0 = peg$c142; peg$currPos++; } else { s0 = null; if (peg$silentFails === 0) { peg$fail(peg$c143); } } } } } return s0; } function peg$parsetagNameShorthand() { var s0, s1, s2; s0 = peg$currPos; if (input.charCodeAt(peg$currPos) === 37) { s1 = peg$c144; peg$currPos++; } else { s1 = null; if (peg$silentFails === 0) { peg$fail(peg$c145); } } if (s1 !== null) { s2 = peg$parsecssIdentifier(); if (s2 !== null) { peg$reportedPos = s0; s1 = peg$c28(s2); if (s1 === null) { peg$currPos = s0; s0 = s1; } else { s0 = s1; } } else { peg$currPos = s0; s0 = peg$c0; } } else { peg$currPos = s0; s0 = peg$c0; } return s0; } function peg$parseidShorthand() { var s0, s1, s2; s0 = peg$currPos; if (input.charCodeAt(peg$currPos) === 35) { s1 = peg$c146; peg$currPos++; } else { s1 = null; if (peg$silentFails === 0) { peg$fail(peg$c147); } } if (s1 !== null) { s2 = peg$parsecssIdentifier(); if (s2 !== null) { peg$reportedPos = s0; s1 = peg$c148(s2); if (s1 === null) { peg$currPos = s0; s0 = s1; } else { s0 = s1; } } else { peg$currPos = s0; s0 = peg$c0; } } else { peg$currPos = s0; s0 = peg$c0; } return s0; } function peg$parseclassShorthand() { var s0, s1, s2; s0 = peg$currPos; if (input.charCodeAt(peg$currPos) === 46) { s1 = peg$c48; peg$currPos++; } else { s1 = null; if (peg$silentFails === 0) { peg$fail(peg$c49); } } if (s1 !== null) { s2 = peg$parsecssIdentifier(); if (s2 !== null) { peg$reportedPos = s0; s1 = peg$c28(s2); if (s1 === null) { peg$currPos = s0; s0 = s1; } else { s0 = s1; } } else { peg$currPos = s0; s0 = peg$c0; } } else { peg$currPos = s0; s0 = peg$c0; } return s0; } function peg$parsecssIdentifier() { var s0, s1; peg$silentFails++; s0 = peg$parseident(); peg$silentFails--; if (s0 === null) { s1 = null; if (peg$silentFails === 0) { peg$fail(peg$c149); } } return s0; } function peg$parseident() { var s0, s1, s2, s3, s4; s0 = peg$currPos; s1 = peg$parsenmstart(); if (s1 !== null) { s2 = peg$currPos; s3 = []; s4 = peg$parsenmchar(); while (s4 !== null) { s3.push(s4); s4 = peg$parsenmchar(); } if (s3 !== null) { s3 = input.substring(s2, peg$currPos); } s2 = s3; if (s2 !== null) { peg$reportedPos = s0; s1 = peg$c150(s1,s2); if (s1 === null) { peg$currPos = s0; s0 = s1; } else { s0 = s1; } } else { peg$currPos = s0; s0 = peg$c0; } } else { peg$currPos = s0; s0 = peg$c0; } return s0; } function peg$parsenmchar() { var s0; if (peg$c151.test(input.charAt(peg$currPos))) { s0 = input.charAt(peg$currPos); peg$currPos++; } else { s0 = null; if (peg$silentFails === 0) { peg$fail(peg$c152); } } if (s0 === null) { s0 = peg$parsenonascii(); } return s0; } function peg$parsenmstart() { var s0; if (peg$c153.test(input.charAt(peg$currPos))) { s0 = input.charAt(peg$currPos); peg$currPos++; } else { s0 = null; if (peg$silentFails === 0) { peg$fail(peg$c154); } } if (s0 === null) { s0 = peg$parsenonascii(); } return s0; } function peg$parsenonascii() { var s0; if (peg$c155.test(input.charAt(peg$currPos))) { s0 = input.charAt(peg$currPos); peg$currPos++; } else { s0 = null; if (peg$silentFails === 0) { peg$fail(peg$c156); } } return s0; } function peg$parsetagString() { var s0, s1, s2; s0 = peg$currPos; s1 = []; s2 = peg$parsetagChar(); if (s2 !== null) { while (s2 !== null) { s1.push(s2); s2 = peg$parsetagChar(); } } else { s1 = peg$c0; } if (s1 !== null) { s1 = input.substring(s0, peg$currPos); } s0 = s1; return s0; } function peg$parsehtmlTagName() { var s0, s1, s2, s3; peg$silentFails++; s0 = peg$currPos; if (input.charCodeAt(peg$currPos) === 37) { s1 = peg$c144; peg$currPos++; } else { s1 = null; if (peg$silentFails === 0) { peg$fail(peg$c145); } } if (s1 !== null) { s2 = peg$parse_(); if (s2 !== null) { s3 = peg$parsetagString(); if (s3 !== null) { peg$reportedPos = s0; s1 = peg$c52(s3); if (s1 === null) { peg$currPos = s0; s0 = s1; } else { s0 = s1; } } else { peg$currPos = s0; s0 = peg$c0; } } else { peg$currPos = s0; s0 = peg$c0; } } else { peg$currPos = s0; s0 = peg$c0; } if (s0 === null) { s0 = peg$parseknownTagName(); } peg$silentFails--; if (s0 === null) { s1 = null; if (peg$silentFails === 0) { peg$fail(peg$c157); } } return s0; } function peg$parseknownTagName() { var s0, s1, s2; s0 = peg$currPos; s1 = peg$parsetagString(); if (s1 !== null) { peg$reportedPos = peg$currPos; s2 = peg$c158(s1); if (s2) { s2 = peg$c1; } else { s2 = peg$c0; } if (s2 !== null) { peg$reportedPos = s0; s1 = peg$c159(s1); if (s1 === null) { peg$currPos = s0; s0 = s1; } else { s0 = s1; } } else { peg$currPos = s0; s0 = peg$c0; } } else { peg$currPos = s0; s0 = peg$c0; } return s0; } function peg$parsetagChar() { var s0, s1, s2, s3; if (peg$c151.test(input.charAt(peg$currPos))) { s0 = input.charAt(peg$currPos); peg$currPos++; } else { s0 = null; if (peg$silentFails === 0) { peg$fail(peg$c152); } } if (s0 === null) { s0 = peg$currPos; if (input.charCodeAt(peg$currPos) === 58) { s1 = peg$c160; peg$currPos++; } else { s1 = null; if (peg$silentFails === 0) { peg$fail(peg$c161); } } if (s1 !== null) { s2 = peg$currPos; peg$silentFails++; if (input.charCodeAt(peg$currPos) === 32) { s3 = peg$c25; peg$currPos++; } else { s3 = null; if (peg$silentFails === 0) { peg$fail(peg$c26); } } peg$silentFails--; if (s3 === null) { s2 = peg$c1; } else { peg$currPos = s2; s2 = peg$c0; } if (s2 !== null) { peg$reportedPos = s0; s1 = peg$c28(s1); if (s1 === null) { peg$currPos = s0; s0 = s1; } else { s0 = s1; } } else { peg$currPos = s0; s0 = peg$c0; } } else { peg$currPos = s0; s0 = peg$c0; } } return s0; } function peg$parseknownEvent() { var s0, s1, s2; peg$silentFails++; s0 = peg$currPos; s1 = peg$parsetagString(); if (s1 !== null) { peg$reportedPos = peg$currPos; s2 = peg$c163(s1); if (s2) { s2 = peg$c1; } else { s2 = peg$c0; } if (s2 !== null) { peg$reportedPos = s0; s1 = peg$c159(s1); if (s1 === null) { peg$currPos = s0; s0 = s1; } else { s0 = s1; } } else { peg$currPos = s0; s0 = peg$c0; } } else { peg$currPos = s0; s0 = peg$c0; } peg$silentFails--; if (s0 === null) { s1 = null; if (peg$silentFails === 0) { peg$fail(peg$c162); } } return s0; } function peg$parseindentation() { var s0, s1, s2; s0 = peg$currPos; s1 = peg$parseINDENT(); if (s1 !== null) { s2 = peg$parse__(); if (s2 !== null) { peg$reportedPos = s0; s1 = peg$c52(s2); if (s1 === null) { peg$currPos = s0; s0 = s1; } else { s0 = s1; } } else { peg$currPos = s0; s0 = peg$c0; } } else { peg$currPos = s0; s0 = peg$c0; } return s0; } function peg$parseINDENT() { var s0, s1; peg$silentFails++; s0 = peg$currPos; if (input.charCodeAt(peg$currPos) === 61423) { s1 = peg$c165; peg$currPos++; } else { s1 = null; if (peg$silentFails === 0) { peg$fail(peg$c166); } } if (s1 !== null) { peg$reportedPos = s0; s1 = peg$c167(); } if (s1 === null) { peg$currPos = s0; s0 = s1; } else { s0 = s1; } peg$silentFails--; if (s0 === null) { s1 = null; if (peg$silentFails === 0) { peg$fail(peg$c164); } } return s0; } function peg$parseDEDENT() { var s0, s1; peg$silentFails++; s0 = peg$currPos; if (input.charCodeAt(peg$currPos) === 61438) { s1 = peg$c169; peg$currPos++; } else { s1 = null; if (peg$silentFails === 0) { peg$fail(peg$c170); } } if (s1 !== null) { peg$reportedPos = s0; s1 = peg$c167(); } if (s1 === null) { peg$currPos = s0; s0 = s1; } else { s0 = s1; } peg$silentFails--; if (s0 === null) { s1 = null; if (peg$silentFails === 0) { peg$fail(peg$c168); } } return s0; } function peg$parseUNMATCHED_DEDENT() { var s0, s1; peg$silentFails++; s0 = peg$currPos; if (input.charCodeAt(peg$currPos) === 61422) { s1 = peg$c172; peg$currPos++; } else { s1 = null; if (peg$silentFails === 0) { peg$fail(peg$c173); } } if (s1 !== null) { peg$reportedPos = s0; s1 = peg$c167(); } if (s1 === null) { peg$currPos = s0; s0 = s1; } else { s0 = s1; } peg$silentFails--; if (s0 === null) { s1 = null; if (peg$silentFails === 0) { peg$fail(peg$c171); } } return s0; } function peg$parseTERM() { var s0, s1, s2; peg$silentFails++; s0 = peg$currPos; if (input.charCodeAt(peg$currPos) === 61439) { s1 = peg$c175; peg$currPos++; } else { s1 = null; if (peg$silentFails === 0) { peg$fail(peg$c176); } } if (s1 !== null) { if (input.charCodeAt(peg$currPos) === 10) { s2 = peg$c177; peg$currPos++; } else { s2 = null; if (peg$silentFails === 0) { peg$fail(peg$c178); } } if (s2 !== null) { peg$reportedPos = s0; s1 = peg$c121(); if (s1 === null) { peg$currPos = s0; s0 = s1; } else { s0 = s1; } } else { peg$currPos = s0; s0 = peg$c0; } } else { peg$currPos = s0; s0 = peg$c0; } peg$silentFails--; if (s0 === null) { s1 = null; if (peg$silentFails === 0) { peg$fail(peg$c174); } } return s0; } function peg$parseanyDedent() { var s0, s1; peg$silentFails++; s0 = peg$parseDEDENT(); if (s0 === null) { s0 = peg$parseUNMATCHED_DEDENT(); } peg$silentFails--; if (s0 === null) { s1 = null; if (peg$silentFails === 0) { peg$fail(peg$c179); } } return s0; } function peg$parse__() { var s0, s1, s2; peg$silentFails++; s0 = peg$currPos; s1 = []; s2 = peg$parsewhitespace(); if (s2 !== null) { while (s2 !== null) { s1.push(s2); s2 = peg$parsewhitespace(); } } else { s1 = peg$c0; } if (s1 !== null) { s1 = input.substring(s0, peg$currPos); } s0 = s1; peg$silentFails--; if (s0 === null) { s1 = null; if (peg$silentFails === 0) { peg$fail(peg$c180); } } return s0; } function peg$parse_() { var s0, s1; peg$silentFails++; s0 = []; s1 = peg$parsewhitespace(); while (s1 !== null) { s0.push(s1); s1 = peg$parsewhitespace(); } peg$silentFails--; if (s0 === null) { s1 = null; if (peg$silentFails === 0) { peg$fail(peg$c181); } } return s0; } function peg$parsewhitespace() { var s0, s1; peg$silentFails++; if (peg$c183.test(input.charAt(peg$currPos))) { s0 = input.charAt(peg$currPos); peg$currPos++; } else { s0 = null; if (peg$silentFails === 0) { peg$fail(peg$c184); } } peg$silentFails--; if (s0 === null) { s1 = null; if (peg$silentFails === 0) { peg$fail(peg$c182); } } return s0; } function peg$parselineChar() { var s0, s1, s2; s0 = peg$currPos; s1 = peg$currPos; peg$silentFails++; s2 = peg$parseINDENT(); if (s2 === null) { s2 = peg$parseDEDENT(); if (s2 === null) { s2 = peg$parseTERM(); } } peg$silentFails--; if (s2 === null) { s1 = peg$c1; } else { peg$currPos = s1; s1 = peg$c0; } if (s1 !== null) { if (input.length > peg$currPos) { s2 = input.charAt(peg$currPos); peg$currPos++; } else { s2 = null; if (peg$silentFails === 0) { peg$fail(peg$c96); } } if (s2 !== null) { peg$reportedPos = s0; s1 = peg$c28(s2); if (s1 === null) { peg$currPos = s0; s0 = s1; } else { s0 = s1; } } else { peg$currPos = s0; s0 = peg$c0; } } else { peg$currPos = s0; s0 = peg$c0; } return s0; } function peg$parselineContent() { var s0, s1, s2; s0 = peg$currPos; s1 = []; s2 = peg$parselineChar(); while (s2 !== null) { s1.push(s2); s2 = peg$parselineChar(); } if (s1 !== null) { s1 = input.substring(s0, peg$currPos); } s0 = s1; return s0; } var handlebarsVariant = Emblem.handlebarsVariant; var IS_EMBER = handlebarsVariant.JavaScriptCompiler.prototype.namespace === "Ember.Handlebars"; var AST = handlebarsVariant.AST; var SELF_CLOSING_TAG = { area: true, base: true, br: true, col: true, command: true, embed: true, hr: true, img: true, input: true, keygen: true, link: true, meta: true, param: true, source: true, track: true, wbr: true }; var KNOWN_TAGS = { figcaption: true, blockquote: true, plaintext: true, textarea: true, progress: true, optgroup: true, noscript: true, noframes: true, frameset: true, fieldset: true, datalist: true, colgroup: true, basefont: true, summary: true, section: true, marquee: true, listing: true, isindex: true, details: true, command: true, caption: true, bgsound: true, article: true, address: true, acronym: true, strong: true, strike: true, spacer: true, source: true, select: true, script: true, output: true, option: true, object: true, legend: true, keygen: true, iframe: true, hgroup: true, header: true, footer: true, figure: true, center: true, canvas: true, button: true, applet: true, video: true, track: true, title: true, thead: true, tfoot: true, tbody: true, table: true, style: true, small: true, param: true, meter: true, label: true, input: true, frame: true, embed: true, blink: true, audio: true, aside: true, time: true, span: true, samp: true, ruby: true, nobr: true, meta: true, menu: true, mark: true, main: true, link: true, html: true, head: true, form: true, font: true, data: true, code: true, cite: true, body: true, base: true, area: true, abbr: true, xmp: true, wbr: true, var: true, sup: true, sub: true, pre: true, nav: true, map: true, kbd: true, ins: true, img: true, div: true, dir: true, dfn: true, del: true, col: true, big: true, bdo: true, bdi: true, ul: true, tt: true, tr: true, th: true, td: true, rt: true, rp: true, ol: true, li: true, hr: true, h6: true, h5: true, h4: true, h3: true, h2: true, h1: true, em: true, dt: true, dl: true, dd: true, br: true, u: true, s: true, q: true, p: true, i: true, b: true, a: true }; var KNOWN_EVENTS = { "touchStart": true, "touchMove": true, "touchEnd": true, "touchCancel": true, "keyDown": true, "keyUp": true, "keyPress": true, "mouseDown": true, "mouseUp": true, "contextMenu": true, "click": true, "doubleClick": true, "mouseMove": true, "focusIn": true, "focusOut": true, "mouseEnter": true, "mouseLeave": true, "submit": true, "input": true, "change": true, "dragStart": true, "drag": true, "dragEnter": true, "dragLeave": true, "dragOver": true, "drop": true, "dragEnd": true }; // Returns a new MustacheNode with a new preceding param (id). function unshiftParam(mustacheNode, helperName, newHashPairs) { var hash = mustacheNode.hash; // Merge hash. if(newHashPairs) { hash = hash || new AST.HashNode([]); for(var i = 0; i < newHashPairs.length; ++i) { hash.pairs.push(newHashPairs[i]); } } var params = [mustacheNode.id].concat(mustacheNode.params); params.unshift(new AST.IdNode([helperName])); return new AST.MustacheNode(params, hash, !mustacheNode.escaped); } function textNodesResult(first, tail) { var ret = []; if(first) { ret.push(first); } for(var i = 0; i < tail.length; ++i) { var t = tail[i]; ret.push(t[0]); if(t[1]) { ret.push(t[1]); } } return ret; } // Only for debugging use. function log(msg) { handlebarsVariant.log(9, msg); } peg$result = peg$startRuleFunction(); if (peg$result !== null && peg$currPos === input.length) { return peg$result; } else { peg$cleanupExpected(peg$maxFailExpected); peg$reportedPos = Math.max(peg$currPos, peg$maxFailPos); throw new SyntaxError( peg$maxFailExpected, peg$reportedPos < input.length ? input.charAt(peg$reportedPos) : null, peg$reportedPos, peg$computePosDetails(peg$reportedPos).line, peg$computePosDetails(peg$reportedPos).column ); } } return { SyntaxError: SyntaxError, parse : parse }; })(); ; // lib/compiler.js var Emblem; Emblem.throwCompileError = function(line, msg) { throw new Error("Emblem syntax error, line " + line + ": " + msg); }; Emblem.registerPartial = function(handlebarsVariant, partialName, text) { if (!text) { text = partialName; partialName = handlebarsVariant; handlebarsVariant = Handlebars; } return handlebarsVariant.registerPartial(partialName, Emblem.compile(handlebarsVariant, text)); }; Emblem.parse = function(string) { var line, lines, msg, processed; try { processed = Emblem.Preprocessor.processSync(string); return Emblem.Parser.parse(processed); } catch (e) { if (e instanceof Emblem.Parser.SyntaxError) { lines = string.split("\n"); line = lines[e.line - 1]; msg = "" + e.message + "\n" + line + "\n"; msg += new Array(e.column).join("-"); msg += "^"; return Emblem.throwCompileError(e.line, msg); } else { throw e; } } }; Emblem.precompile = function(handlebarsVariant, string, options) { var ast; if (options == null) { options = {}; } Emblem.handlebarsVariant = handlebarsVariant; ast = Emblem.parse(string); return handlebarsVariant.precompile(ast, options); }; Emblem.compile = function(handlebarsVariant, string, options) { var ast; if (options == null) { options = {}; } Emblem.handlebarsVariant = handlebarsVariant; ast = Emblem.parse(string); return handlebarsVariant.compile(ast, options); }; ; // lib/preprocessor.js var Emblem, Preprocessor, StringScanner; Emblem.Preprocessor = Preprocessor = (function() { var DEDENT, INDENT, TERM, UNMATCHED_DEDENT, anyWhitespaceAndNewlinesTouchingEOF, any_whitespaceFollowedByNewlines_, processInput, ws; ws = '\\t\\x0B\\f \\xA0\\u1680\\u180E\\u2000-\\u200A\\u202F\\u205F\\u3000\\uFEFF'; INDENT = '\uEFEF'; DEDENT = '\uEFFE'; UNMATCHED_DEDENT = '\uEFEE'; TERM = '\uEFFF'; anyWhitespaceAndNewlinesTouchingEOF = RegExp("[" + ws + "\\n]*$"); any_whitespaceFollowedByNewlines_ = RegExp("(?:[" + ws + "]*\\n)+"); function Preprocessor() { this.base = null; this.indents = []; this.context = []; this.context.peek = function() { if (this.length) { return this[this.length - 1]; } else { return null; } }; this.context.err = function(c) { throw new Error("Unexpected " + c); }; this.output = ''; this.context.observe = function(c) { var top; top = this.peek(); switch (c) { case INDENT: this.push(c); break; case DEDENT: if (top !== INDENT) { this.err(c); } this.pop(); break; case '\n': if (top !== '/') { this.err(c); } this.pop(); break; case '/': this.push(c); break; case 'end-\\': if (top !== '\\') { this.err(c); } this.pop(); break; default: throw new Error("undefined token observed: " + c); } return this; }; if (this.StringScanner) { this.ss = new this.StringScanner(''); } else if (Emblem.StringScanner) { this.ss = new Emblem.StringScanner(''); } else { this.ss = new StringScanner(''); } } Preprocessor.prototype.p = function(s) { if (s) { this.output += s; } return s; }; Preprocessor.prototype.scan = function(r) { return this.p(this.ss.scan(r)); }; Preprocessor.prototype.discard = function(r) { return this.ss.scan(r); }; processInput = function(isEnd) { return function(data) { var b, d, indent, s; if (!isEnd) { this.ss.concat(data); this.discard(any_whitespaceFollowedByNewlines_); } while (!this.ss.eos()) { switch (this.context.peek()) { case null: case INDENT: if (this.ss.bol() || this.discard(any_whitespaceFollowedByNewlines_)) { if (this.discard(RegExp("[" + ws + "]*\\n"))) { this.p("" + TERM + "\n"); continue; } if (this.base != null) { if ((this.discard(this.base)) == null) { throw new Error("inconsistent base indentation"); } } else { b = this.discard(RegExp("[" + ws + "]*")); this.base = RegExp("" + b); } if (this.indents.length === 0) { if (this.ss.check(RegExp("[" + ws + "]+"))) { this.p(INDENT); this.context.observe(INDENT); this.indents.push(this.scan(RegExp("([" + ws + "]+)"))); } } else { indent = this.indents[this.indents.length - 1]; if (d = this.ss.check(RegExp("(" + indent + ")"))) { this.discard(d); if (this.ss.check(RegExp("([" + ws + "]+)"))) { this.p(INDENT); this.context.observe(INDENT); this.indents.push(d + this.scan(RegExp("([" + ws + "]+)"))); } } else { while (this.indents.length) { indent = this.indents[this.indents.length - 1]; if (this.discard(RegExp("(?:" + indent + ")"))) { break; } this.context.observe(DEDENT); this.p(DEDENT); this.indents.pop(); } if (s = this.discard(RegExp("[" + ws + "]+"))) { this.output = this.output.slice(0, -1); this.output += UNMATCHED_DEDENT; this.p(INDENT); this.context.observe(INDENT); this.indents.push(s); } } } } this.scan(/[^\n\\]+/); if (this.discard(/\n/)) { this.p("" + TERM + "\n"); } } } if (isEnd) { this.scan(anyWhitespaceAndNewlinesTouchingEOF); while (this.context.length && INDENT === this.context.peek()) { this.context.observe(DEDENT); this.p(DEDENT); } if (this.context.length) { throw new Error('Unclosed ' + (this.context.peek()) + ' at EOF'); } } }; }; Preprocessor.prototype.processData = processInput(false); Preprocessor.prototype.processEnd = processInput(true); Preprocessor.processSync = function(input) { var pre; input += "\n"; pre = new Preprocessor; pre.processData(input); pre.processEnd(); return pre.output; }; return Preprocessor; })(); ; // lib/emberties.js var ENV, Emblem, _base; Emblem.compileScriptTags = function() { if (typeof Ember === "undefined" || Ember === null) { throw new Error("Can't run Emblem.enableEmber before Ember has been defined"); } if (typeof document !== "undefined" && document !== null) { return Ember.$('script[type="text/x-emblem"], script[type="text/x-raw-emblem"]', Ember.$(document)).each(function() { var handlebarsVariant, script, templateName; script = Ember.$(this); handlebarsVariant = script.attr('type') === 'text/x-raw-handlebars' ? Handlebars : Ember.Handlebars; templateName = script.attr('data-template-name') || script.attr('id') || 'application'; Ember.TEMPLATES[templateName] = Emblem.compile(handlebarsVariant, script.html()); return script.remove(); }); } }; this.ENV || (this.ENV = {}); ENV = this.ENV; ENV.EMBER_LOAD_HOOKS || (ENV.EMBER_LOAD_HOOKS = {}); (_base = ENV.EMBER_LOAD_HOOKS).application || (_base.application = []); ENV.EMBER_LOAD_HOOKS.application.push(function() { return Emblem.compileScriptTags(); }); ; root.Emblem = Emblem; }(this));
/* ***** BEGIN LICENSE BLOCK ***** * Distributed under the BSD license: * * Copyright (c) 2010, Ajax.org B.V. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Ajax.org B.V. nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL AJAX.ORG B.V. BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ***** END LICENSE BLOCK ***** */ define(function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var VerilogHighlightRules = function() { var keywords = "always|and|assign|automatic|begin|buf|bufif0|bufif1|case|casex|casez|cell|cmos|config|" + "deassign|default|defparam|design|disable|edge|else|end|endcase|endconfig|endfunction|endgenerate|endmodule|" + "endprimitive|endspecify|endtable|endtask|event|for|force|forever|fork|function|generate|genvar|highz0|" + "highz1|if|ifnone|incdir|include|initial|inout|input|instance|integer|join|large|liblist|library|localparam|" + "macromodule|medium|module|nand|negedge|nmos|nor|noshowcancelled|not|notif0|notif1|or|output|parameter|pmos|" + "posedge|primitive|pull0|pull1|pulldown|pullup|pulsestyle_onevent|pulsestyle_ondetect|rcmos|real|realtime|" + "reg|release|repeat|rnmos|rpmos|rtran|rtranif0|rtranif1|scalared|showcancelled|signed|small|specify|specparam|" + "strong0|strong1|supply0|supply1|table|task|time|tran|tranif0|tranif1|tri|tri0|tri1|triand|trior|trireg|" + "unsigned|use|vectored|wait|wand|weak0|weak1|while|wire|wor|xnor|xor" + "begin|bufif0|bufif1|case|casex|casez|config|else|end|endcase|endconfig|endfunction|" + "endgenerate|endmodule|endprimitive|endspecify|endtable|endtask|for|forever|function|generate|if|ifnone|" + "macromodule|module|primitive|repeat|specify|table|task|while"; var builtinConstants = ( "true|false|null" ); var builtinFunctions = ( "count|min|max|avg|sum|rank|now|coalesce|main" ); var keywordMapper = this.createKeywordMapper({ "support.function": builtinFunctions, "keyword": keywords, "constant.language": builtinConstants }, "identifier", true); this.$rules = { "start" : [ { token : "comment", regex : "//.*$" }, { token : "string", // " string regex : '".*?"' }, { token : "string", // ' string regex : "'.*?'" }, { token : "constant.numeric", // float regex : "[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?\\b" }, { token : keywordMapper, regex : "[a-zA-Z_$][a-zA-Z0-9_$]*\\b" }, { token : "keyword.operator", regex : "\\+|\\-|\\/|\\/\\/|%|<@>|@>|<@|&|\\^|~|<|>|<=|=>|==|!=|<>|=" }, { token : "paren.lparen", regex : "[\\(]" }, { token : "paren.rparen", regex : "[\\)]" }, { token : "text", regex : "\\s+" } ] }; }; oop.inherits(VerilogHighlightRules, TextHighlightRules); exports.VerilogHighlightRules = VerilogHighlightRules; });
YUI.add('io-upload-iframe', function(Y) { /** Extends the IO to enable file uploads, with HTML forms using an iframe as the transport medium. @module io-base @submodule io-upload-iframe @for IO **/ var w = Y.config.win, d = Y.config.doc, _std = (d.documentMode && d.documentMode >= 8), _d = decodeURIComponent; /** * Creates the iframe transported used in file upload * transactions, and binds the response event handler. * * @method _cFrame * @private * @param {Object} o Transaction object generated by _create(). * @param {Object} c Configuration object passed to YUI.io(). * @param {Object} io */ function _cFrame(o, c, io) { var i = Y.Node.create('<iframe src="#" id="io_iframe' + o.id + '" name="io_iframe' + o.id + '" />'); i._node.style.position = 'absolute'; i._node.style.top = '-1000px'; i._node.style.left = '-1000px'; Y.one('body').appendChild(i); // Bind the onload handler to the iframe to detect the file upload response. Y.on("load", function() { io._uploadComplete(o, c); }, '#io_iframe' + o.id); } /** * Removes the iframe transport used in the file upload * transaction. * * @method _dFrame * @private * @param {Number} id The transaction ID used in the iframe's creation. */ function _dFrame(id) { Y.Event.purgeElement('#io_iframe' + id, false); Y.one('body').removeChild(Y.one('#io_iframe' + id)); } Y.mix(Y.IO.prototype, { /** * Parses the POST data object and creates hidden form elements * for each key-value, and appends them to the HTML form object. * @method appendData * @private * @static * @param {Object} f HTML form object. * @param {String} s The key-value POST data. * @return {Array} o Array of created fields. */ _addData: function(f, s) { // Serialize an object into a key-value string using // querystring-stringify-simple. if (Y.Lang.isObject(s)) { s = Y.QueryString.stringify(s); } var o = [], m = s.split('='), i, l; for (i = 0, l = m.length - 1; i < l; i++) { o[i] = d.createElement('input'); o[i].type = 'hidden'; o[i].name = _d(m[i].substring(m[i].lastIndexOf('&') + 1)); o[i].value = (i + 1 === l) ? _d(m[i + 1]) : _d(m[i + 1].substring(0, (m[i + 1].lastIndexOf('&')))); f.appendChild(o[i]); } return o; }, /** * Removes the custom fields created to pass additional POST * data, along with the HTML form fields. * @method _removeData * @private * @static * @param {Object} f HTML form object. * @param {Object} o HTML form fields created from configuration.data. */ _removeData: function(f, o) { var i, l; for (i = 0, l = o.length; i < l; i++) { f.removeChild(o[i]); } }, /** * Sets the appropriate attributes and values to the HTML * form, in preparation of a file upload transaction. * @method _setAttrs * @private * @static * @param {Object} f HTML form object. * @param {Object} id The Transaction ID. * @param {Object} uri Qualified path to transaction resource. */ _setAttrs: function(f, id, uri) { f.setAttribute('action', uri); f.setAttribute('method', 'POST'); f.setAttribute('target', 'io_iframe' + id ); f.setAttribute(Y.UA.ie && !_std ? 'encoding' : 'enctype', 'multipart/form-data'); }, /** * Reset the HTML form attributes to their original values. * @method _resetAttrs * @private * @static * @param {Object} f HTML form object. * @param {Object} a Object of original attributes. */ _resetAttrs: function(f, a) { Y.Object.each(a, function(v, p) { if (v) { f.setAttribute(p, v); } else { f.removeAttribute(p); } }); }, /** * Starts timeout count if the configuration object * has a defined timeout property. * * @method _startUploadTimeout * @private * @static * @param {Object} o Transaction object generated by _create(). * @param {Object} c Configuration object passed to YUI.io(). */ _startUploadTimeout: function(o, c) { var io = this; io._timeout[o.id] = w.setTimeout( function() { o.status = 0; o.statusText = 'timeout'; io.complete(o, c); io.end(o, c); }, c.timeout); }, /** * Clears the timeout interval started by _startUploadTimeout(). * @method _clearUploadTimeout * @private * @static * @param {Number} id - Transaction ID. */ _clearUploadTimeout: function(id) { var io = this; w.clearTimeout(io._timeout[id]); delete io._timeout[id]; }, /** * Bound to the iframe's Load event and processes * the response data. * @method _uploadComplete * @private * @static * @param {Object} o The transaction object * @param {Object} c Configuration object for the transaction. */ _uploadComplete: function(o, c) { var io = this, d = Y.one('#io_iframe' + o.id).get('contentWindow.document'), b = d.one('body'), p; if (c.timeout) { io._clearUploadTimeout(o.id); } try { if (b) { // When a response Content-Type of "text/plain" is used, Firefox and Safari // will wrap the response string with <pre></pre>. p = b.one('pre:first-child'); o.c.responseText = p ? p.get('text') : b.get('text'); } else { o.c.responseXML = d._node; } } catch (e) { o.e = "upload failure"; } io.complete(o, c); io.end(o, c); // The transaction is complete, so call _dFrame to remove // the event listener bound to the iframe transport, and then // destroy the iframe. w.setTimeout( function() { _dFrame(o.id); }, 0); }, /** * Uploads HTML form data, inclusive of files/attachments, * using the iframe created in _create to facilitate the transaction. * @method _upload * @private * @static * @param {Object} o The transaction object * @param {Object} uri Qualified path to transaction resource. * @param {Object} c Configuration object for the transaction. */ _upload: function(o, uri, c) { var io = this, f = (typeof c.form.id === 'string') ? d.getElementById(c.form.id) : c.form.id, // Track original HTML form attribute values. attr = { action: f.getAttribute('action'), target: f.getAttribute('target') }, fields; // Initialize the HTML form properties in case they are // not defined in the HTML form. io._setAttrs(f, o.id, uri); if (c.data) { fields = io._addData(f, c.data); } // Start polling if a callback is present and the timeout // property has been defined. if (c.timeout) { io._startUploadTimeout(o, c); } // Start file upload. f.submit(); io.start(o, c); if (c.data) { io._removeData(f, fields); } // Restore HTML form attributes to their original values. io._resetAttrs(f, attr); return { id: o.id, abort: function() { o.status = 0; o.statusText = 'abort'; if (Y.one('#io_iframe' + o.id)) { _dFrame(o.id); io.complete(o, c); io.end(o, c); } else { return false; } }, isInProgress: function() { return Y.one('#io_iframe' + o.id) ? true : false; }, io: io }; }, upload: function(o, uri, c) { _cFrame(o, c, this); return this._upload(o, uri, c); } }); }, '@VERSION@' ,{requires:['io-base','node-base']});
// 20.2.2.20 Math.log1p(x) module.exports = Math.log1p || function log1p(x) { return (x = +x) > -1e-8 && x < 1e-8 ? x - x * x / 2 : Math.log(1 + x); };
define(function() { Q.module('WebGLRenderer'); });
//Assumes zopfli is installed var glob = require('glob'); var fs = require('fs'); var execSync = require('execSync'); var isThere = require('is-there'); glob("../ajax/libs/**/package.json", function (error, matches) { matches.forEach(function(element){ var package = JSON.parse(fs.readFileSync(element, 'utf8')); package.assets = Array(); var versions = glob.sync("../ajax/libs/"+package.name+"/!(package.json)"); versions.forEach(function(version) { var temp = Object(); temp.files = glob.sync(version + "/**/*.*"); for (var i = 0; i < temp.files.length; i++){ var regex = /(?:^.+\/)?(.+?)?\.((?:js)|(?:css))([\.-](?:gz))?$/ig; var result = regex.exec(temp.files[i]); //result[0] Original Input //result[1] Filename //result[2] js|css //result[3] gz if (result == null) { continue; } if (typeof result[3] == "undefined") { // if (!isThere.sync(temp.files[i] + ".gz")) { console.log('zopfli', temp.files[i]) execSync.exec('zopfli ' + temp.files[i]); console.log('zopfli ended') } } } }); }); });
/*! lazysizes - v1.1.4-rc1 */ !function(a){"use strict";var b,c=a.createElement("img");"srcset"in c&&!("sizes"in c)&&(b=/^picture$/i,a.addEventListener("lazybeforeunveil",function(c){var d,e,f,g,h,i,j;!c.defaultPrevented&&!lazySizesConfig.noIOSFix&&(d=c.target)&&(f=d.getAttribute(lazySizesConfig.srcsetAttr))&&(e=d.parentNode)&&((h=b.test(e.nodeName||""))||(g=d.getAttribute("sizes")||d.getAttribute(lazySizesConfig.sizesAttr)))&&(i=h?e:a.createElement("picture"),d._lazyImgSrc||Object.defineProperty(d,"_lazyImgSrc",{value:a.createElement("source"),writable:!0}),j=d._lazyImgSrc,g&&j.setAttribute("sizes",g),j.setAttribute(lazySizesConfig.srcsetAttr,f),d.setAttribute("data-pfsrcset",f),d.removeAttribute(lazySizesConfig.srcsetAttr),h||(e.insertBefore(i,d),i.appendChild(d)),i.insertBefore(j,d))}))}(document);
/*! UIkit 2.19.0 | http://www.getuikit.com | (c) 2014 YOOtheme | MIT License */ /* * Based on Nestable jQuery Plugin - Copyright (c) 2012 David Bushell - http://dbushell.com/ */ (function(addon) { var component; if (window.UIkit) { component = addon(UIkit); } if (typeof define == "function" && define.amd) { define("uikit-nestable", ["uikit"], function(){ return component || addon(UIkit); }); } })(function(UI) { "use strict"; var hasTouch = 'ontouchstart' in window, html = UI.$html, touchedlists = [], $win = UI.$win, draggingElement, dragSource; /** * Detect CSS pointer-events property * events are normally disabled on the dragging element to avoid conflicts * https://github.com/ausi/Feature-detection-technique-for-pointer-events/blob/master/modernizr-pointerevents.js */ var hasPointerEvents = (function() { var el = document.createElement('div'), docEl = document.documentElement; if (!('pointerEvents' in el.style)) { return false; } el.style.pointerEvents = 'auto'; el.style.pointerEvents = 'x'; docEl.appendChild(el); var supports = window.getComputedStyle && window.getComputedStyle(el, '').pointerEvents === 'auto'; docEl.removeChild(el); return !!supports; })(); var eStart = hasTouch ? 'touchstart' : 'mousedown', eMove = hasTouch ? 'touchmove' : 'mousemove', eEnd = hasTouch ? 'touchend' : 'mouseup', eCancel = hasTouch ? 'touchcancel' : 'mouseup'; UI.component('nestable', { defaults: { prefix : 'uk-', listNodeName : 'ul', itemNodeName : 'li', listBaseClass : '{prefix}nestable', listClass : '{prefix}nestable-list', listitemClass : '{prefix}nestable-list-item', itemClass : '{prefix}nestable-item', dragClass : '{prefix}nestable-list-dragged', movingClass : '{prefix}nestable-moving', handleClass : '{prefix}nestable-handle', collapsedClass : '{prefix}collapsed', placeClass : '{prefix}nestable-placeholder', noDragClass : '{prefix}nestable-nodrag', emptyClass : '{prefix}nestable-empty', group : 0, maxDepth : 10, threshold : 20 }, boot: function() { // adjust document scrolling UI.$html.on('mousemove touchmove', function(e) { if (draggingElement) { var top = draggingElement.offset().top; if (top < UI.$win.scrollTop()) { UI.$win.scrollTop(UI.$win.scrollTop() - Math.ceil(draggingElement.height()/2)); } else if ( (top + draggingElement.height()) > (window.innerHeight + UI.$win.scrollTop()) ) { UI.$win.scrollTop(UI.$win.scrollTop() + Math.ceil(draggingElement.height()/2)); } } }); // init code UI.ready(function(context) { UI.$("[data-uk-nestable]", context).each(function(){ var ele = UI.$(this); if(!ele.data("nestable")) { var plugin = UI.nestable(ele, UI.Utils.options(ele.attr("data-uk-nestable"))); } }); }); }, init: function() { var $this = this; Object.keys(this.options).forEach(function(key){ if(String($this.options[key]).indexOf('{prefix}')!=-1) { $this.options[key] = $this.options[key].replace('{prefix}', $this.options.prefix); } }); this.tplempty = '<div class="' + this.options.emptyClass + '"/>'; this.find(">"+this.options.itemNodeName).addClass(this.options.listitemClass) .end() .find("ul:not(.ignore-list)").addClass(this.options.listClass) .find(">li").addClass(this.options.listitemClass); if (!this.element.children(this.options.itemNodeName).length) { this.element.append(this.tplempty); } this.element.data("nestable-id", "ID"+(new Date().getTime())+"RAND"+(Math.ceil(Math.random() *100000))); this.reset(); this.element.data('nestable-group', this.options.group); this.placeEl = UI.$('<div class="' + this.options.placeClass + '"/>'); this.find(this.options.itemNodeName).each(function() { $this.setParent(UI.$(this)); }); this.on('click', '[data-nestable-action]', function(e) { if ($this.dragEl || (!hasTouch && e.button !== 0)) { return; } e.preventDefault(); var target = UI.$(e.currentTarget), action = target.data('nestableAction'), item = target.closest($this.options.itemNodeName); if (action === 'collapse') { $this.collapseItem(item); } if (action === 'expand') { $this.expandItem(item); } if (action === 'toggle') { $this.toggleItem(item); } }); var onStartEvent = function(e) { var handle = UI.$(e.target); if (!handle.hasClass($this.options.handleClass)) { if (handle.closest('.' + $this.options.noDragClass).length) { return; } handle = handle.closest('.' + $this.options.handleClass); } if (!handle.length || $this.dragEl || (!hasTouch && e.button !== 0) || (hasTouch && e.touches.length !== 1)) { return; } e.preventDefault(); $this.dragStart(hasTouch ? e.touches[0] : e); $this.trigger('start.uk.nestable', [$this]); }; var onMoveEvent = function(e) { if ($this.dragEl) { e.preventDefault(); $this.dragMove(hasTouch ? e.touches[0] : e); $this.trigger('move.uk.nestable', [$this]); } }; var onEndEvent = function(e) { if ($this.dragEl) { e.preventDefault(); $this.dragStop(hasTouch ? e.touches[0] : e); } draggingElement = false; }; if (hasTouch) { this.element[0].addEventListener(eStart, onStartEvent, false); window.addEventListener(eMove, onMoveEvent, false); window.addEventListener(eEnd, onEndEvent, false); window.addEventListener(eCancel, onEndEvent, false); } else { this.on(eStart, onStartEvent); $win.on(eMove, onMoveEvent); $win.on(eEnd, onEndEvent); } }, serialize: function() { var data, depth = 0, list = this, step = function(level, depth) { var array = [ ], items = level.children(list.options.itemNodeName); items.each(function() { var li = UI.$(this), item = {}, attribute, sub = li.children(list.options.listNodeName); for (var i = 0; i < li[0].attributes.length; i++) { attribute = li[0].attributes[i]; if (attribute.name.indexOf('data-') === 0) { item[attribute.name.substr(5)] = UI.Utils.str2json(attribute.value); } } if (sub.length) { item.children = step(sub, depth + 1); } array.push(item); }); return array; }; data = step(list.element, depth); return data; }, list: function(options) { var data = [], list = this, depth = 0, step = function(level, depth, parent) { var items = level.children(options.itemNodeName); items.each(function(index) { var li = UI.$(this), item = UI.$.extend({parent_id: (parent ? parent : null), depth: depth, order: index}, li.data()), sub = li.children(options.listNodeName); data.push(item); if (sub.length) { step(sub, depth + 1, li.data(options.idProperty || 'id')); } }); }; options = UI.$.extend({}, list.options, options); step(list.element, depth); return data; }, reset: function() { this.mouse = { offsetX : 0, offsetY : 0, startX : 0, startY : 0, lastX : 0, lastY : 0, nowX : 0, nowY : 0, distX : 0, distY : 0, dirAx : 0, dirX : 0, dirY : 0, lastDirX : 0, lastDirY : 0, distAxX : 0, distAxY : 0 }; this.moving = false; this.dragEl = null; this.dragRootEl = null; this.dragDepth = 0; this.hasNewRoot = false; this.pointEl = null; for (var i=0; i<touchedlists.length; i++) { this.checkEmptyList(touchedlists[i]); } touchedlists = []; }, toggleItem: function(li) { this[li.hasClass(this.options.collapsedClass) ? "expandItem":"collapseItem"](li); }, expandItem: function(li) { li.removeClass(this.options.collapsedClass); }, collapseItem: function(li) { var lists = li.children(this.options.listNodeName); if (lists.length) { li.addClass(this.options.collapsedClass); } }, expandAll: function() { var list = this; this.find(list.options.itemNodeName).each(function() { list.expandItem(UI.$(this)); }); }, collapseAll: function() { var list = this; this.find(list.options.itemNodeName).each(function() { list.collapseItem(UI.$(this)); }); }, setParent: function(li) { if (li.children(this.options.listNodeName).length) { li.addClass("uk-parent"); } }, unsetParent: function(li) { li.removeClass('uk-parent '+this.options.collapsedClass); li.children(this.options.listNodeName).remove(); }, dragStart: function(e) { var mouse = this.mouse, target = UI.$(e.target), dragItem = target.closest(this.options.itemNodeName), offset = dragItem.offset(); this.placeEl.css('height', dragItem.height()); mouse.offsetX = e.pageX - offset.left; mouse.offsetY = e.pageY - offset.top; mouse.startX = mouse.lastX = offset.left; mouse.startY = mouse.lastY = offset.top; this.dragRootEl = this.element; this.dragEl = UI.$(document.createElement(this.options.listNodeName)).addClass(this.options.listClass + ' ' + this.options.dragClass); this.dragEl.css('width', dragItem.width()); draggingElement = this.dragEl; this.tmpDragOnSiblings = [dragItem[0].previousSibling, dragItem[0].nextSibling]; // fix for zepto.js //dragItem.after(this.placeEl).detach().appendTo(this.dragEl); dragItem.after(this.placeEl); dragItem[0].parentNode.removeChild(dragItem[0]); dragItem.appendTo(this.dragEl); UI.$body.append(this.dragEl); this.dragEl.css({ left : offset.left, top : offset.top }); // total depth of dragging item var i, depth, items = this.dragEl.find(this.options.itemNodeName); for (i = 0; i < items.length; i++) { depth = UI.$(items[i]).parents(this.options.listNodeName).length; if (depth > this.dragDepth) { this.dragDepth = depth; } } html.addClass(this.options.movingClass); }, dragStop: function(e) { // fix for zepto.js //this.placeEl.replaceWith(this.dragEl.children(this.options.itemNodeName + ':first').detach()); var el = this.dragEl.children(this.options.itemNodeName).first(), root = this.placeEl.parents('.'+this.options.listBaseClass+':first'); el[0].parentNode.removeChild(el[0]); this.placeEl.replaceWith(el); this.dragEl.remove(); if (this.element[0] !== root[0]) { root.trigger('change.uk.nestable',[el, "added", root, root.data('nestable')]); this.element.trigger('change.uk.nestable', [el, "removed", this.element, this]); } else { this.element.trigger('change.uk.nestable',[el, "moved", this.element, this]); } this.trigger('stop.uk.nestable', [this, el]); this.reset(); html.removeClass(this.options.movingClass); }, dragMove: function(e) { var list, parent, prev, next, depth, opt = this.options, mouse = this.mouse; this.dragEl.css({ left : e.pageX - mouse.offsetX, top : e.pageY - mouse.offsetY }); // mouse position last events mouse.lastX = mouse.nowX; mouse.lastY = mouse.nowY; // mouse position this events mouse.nowX = e.pageX; mouse.nowY = e.pageY; // distance mouse moved between events mouse.distX = mouse.nowX - mouse.lastX; mouse.distY = mouse.nowY - mouse.lastY; // direction mouse was moving mouse.lastDirX = mouse.dirX; mouse.lastDirY = mouse.dirY; // direction mouse is now moving (on both axis) mouse.dirX = mouse.distX === 0 ? 0 : mouse.distX > 0 ? 1 : -1; mouse.dirY = mouse.distY === 0 ? 0 : mouse.distY > 0 ? 1 : -1; // axis mouse is now moving on var newAx = Math.abs(mouse.distX) > Math.abs(mouse.distY) ? 1 : 0; // do nothing on first move if (!mouse.moving) { mouse.dirAx = newAx; mouse.moving = true; return; } // calc distance moved on this axis (and direction) if (mouse.dirAx !== newAx) { mouse.distAxX = 0; mouse.distAxY = 0; } else { mouse.distAxX += Math.abs(mouse.distX); if (mouse.dirX !== 0 && mouse.dirX !== mouse.lastDirX) { mouse.distAxX = 0; } mouse.distAxY += Math.abs(mouse.distY); if (mouse.dirY !== 0 && mouse.dirY !== mouse.lastDirY) { mouse.distAxY = 0; } } mouse.dirAx = newAx; /** * move horizontal */ if (mouse.dirAx && mouse.distAxX >= opt.threshold) { // reset move distance on x-axis for new phase mouse.distAxX = 0; prev = this.placeEl.prev(opt.itemNodeName); // increase horizontal level if previous sibling exists and is not collapsed if (mouse.distX > 0 && prev.length && !prev.hasClass(opt.collapsedClass)) { // cannot increase level when item above is collapsed list = prev.find(opt.listNodeName).last(); // check if depth limit has reached depth = this.placeEl.parents(opt.listNodeName).length; if (depth + this.dragDepth <= opt.maxDepth) { // create new sub-level if one doesn't exist if (!list.length) { list = UI.$('<' + opt.listNodeName + '/>').addClass(opt.listClass); list.append(this.placeEl); prev.append(list); this.setParent(prev); } else { // else append to next level up list = prev.children(opt.listNodeName).last(); list.append(this.placeEl); } } } // decrease horizontal level if (mouse.distX < 0) { // we can't decrease a level if an item preceeds the current one next = this.placeEl.next(opt.itemNodeName); if (!next.length) { parent = this.placeEl.parent(); this.placeEl.closest(opt.itemNodeName).after(this.placeEl); if (!parent.children().length) { this.unsetParent(parent.parent()); } } } } var isEmpty = false; // find list item under cursor if (!hasPointerEvents) { this.dragEl[0].style.visibility = 'hidden'; } this.pointEl = UI.$(document.elementFromPoint(e.pageX - document.body.scrollLeft, e.pageY - (window.pageYOffset || document.documentElement.scrollTop))); if (!hasPointerEvents) { this.dragEl[0].style.visibility = 'visible'; } if (this.pointEl.hasClass(opt.handleClass)) { this.pointEl = this.pointEl.closest(opt.itemNodeName); } else { var nestableitem = this.pointEl.closest('.'+opt.itemClass); if (nestableitem.length) { this.pointEl = nestableitem.closest(opt.itemNodeName); } } if (this.pointEl.hasClass(opt.emptyClass)) { isEmpty = true; } else if (this.pointEl.data('nestable') && !this.pointEl.children().length) { isEmpty = true; this.pointEl = UI.$(this.tplempty).appendTo(this.pointEl); } else if (!this.pointEl.length || !this.pointEl.hasClass(opt.listitemClass)) { return; } // find parent list of item under cursor var pointElRoot = this.element, tmpRoot = this.pointEl.closest('.'+this.options.listBaseClass), isNewRoot = pointElRoot[0] !== this.pointEl.closest('.'+this.options.listBaseClass)[0]; /** * move vertical */ if (!mouse.dirAx || isNewRoot || isEmpty) { // check if groups match if dragging over new root if (isNewRoot && opt.group !== tmpRoot.data('nestable-group')) { return; } else { touchedlists.push(pointElRoot); } // check depth limit depth = this.dragDepth - 1 + this.pointEl.parents(opt.listNodeName).length; if (depth > opt.maxDepth) { return; } var before = e.pageY < (this.pointEl.offset().top + this.pointEl.height() / 2); parent = this.placeEl.parent(); // if empty create new list to replace empty placeholder if (isEmpty) { this.pointEl.replaceWith(this.placeEl); } else if (before) { this.pointEl.before(this.placeEl); } else { this.pointEl.after(this.placeEl); } if (!parent.children().length) { if(!parent.data("nestable")) this.unsetParent(parent.parent()); } this.checkEmptyList(this.dragRootEl); this.checkEmptyList(pointElRoot); // parent root list has changed if (isNewRoot) { this.dragRootEl = tmpRoot; this.hasNewRoot = this.element[0] !== this.dragRootEl[0]; } } }, checkEmptyList: function(list) { list = list ? UI.$(list) : this.element; if (!list.children().length) { list.find('.'+this.options.emptyClass).remove().end().append(this.tplempty); } } }); return UI.nestable; });
/* eslint-disable react/jsx-props-no-spreading */ import React from 'react'; import { connect, getIn } from 'formik'; import { useTranslation } from 'react-i18next'; import { Col, FormGroup, Label, Input, InputGroup, FormText } from 'reactstrap'; import { FieldProps } from 'utils/types'; const MAX_GRID_SIZE = 12; const FormField = ({ name, label, inputAddonPrepend, inputAddonAppend, formik, check, labelSize, ...props }) => { const { t } = useTranslation(); const error = getIn(formik.errors, name, null); const value = getIn(formik.values, name, undefined); const touched = getIn(formik.touched, name, false); let input = ( <Input {...props} name={name} value={value} touched={`${touched}`} onChange={formik.handleChange} onBlur={formik.handleBlur} invalid={!!(touched && error)} /> ); if (inputAddonPrepend || inputAddonAppend) { input = ( <InputGroup> {inputAddonPrepend || null} {input} {inputAddonAppend || null} </InputGroup> ); } let inputComponent = ( <> {input} {touched && error ? ( <FormText color="danger">{t(error)}</FormText> ) : null} </> ); if (labelSize !== null) { inputComponent = ( <Col md={MAX_GRID_SIZE - labelSize}>{inputComponent}</Col> ); } let labelComponent = null; if (label) { labelComponent = ( <Label for={props.id || name} check={check} md={labelSize}> {label} </Label> ); } return ( <FormGroup row check={check}> {labelComponent} {inputComponent} </FormGroup> ); }; FormField.propTypes = FieldProps.props; FormField.defaultProps = FieldProps.defaults; export default connect(FormField);
var gulp = require('gulp'), gutil = require('gulp-util'), isDist = (gutil.env.dist) ? true: false, isDev = (gutil.env.stat) ? true: false, server = require('./build-tasks/server'), scripts = require('./build-tasks/scripts'), styles = require('./build-tasks/styles'), markup = require('./build-tasks/markup'), deploy = require('./build-tasks/deploy'); //insantiate list of default tasks based on environment var defaultTasks = ((gutil.env.isDist) ? true: false) ? [ 'deploy' ]: [ 'server', 'watch' ]; gulp.task('default', defaultTasks);
/* * jQuery Hotkeys Plugin * Copyright 2010, John Resig * Dual licensed under the MIT or GPL Version 2 licenses. * * Based upon the plugin by Tzury Bar Yochay: * http://github.com/tzuryby/hotkeys * * Original idea by: * Binny V A, http://www.openjs.com/scripts/events/keyboard_shortcuts/ */ (function(jQuery){ jQuery.hotkeys = { version: "0.8", specialKeys: { 8: "backspace", 9: "tab", 13: "return", 16: "shift", 17: "ctrl", 18: "alt", 19: "pause", 20: "capslock", 27: "esc", 32: "space", 33: "pageup", 34: "pagedown", 35: "end", 36: "home", 37: "left", 38: "up", 39: "right", 40: "down", 45: "insert", 46: "del", 96: "0", 97: "1", 98: "2", 99: "3", 100: "4", 101: "5", 102: "6", 103: "7", 104: "8", 105: "9", 106: "*", 107: "+", 109: "-", 110: ".", 111 : "/", 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: "scroll", 191: "/", 224: "meta" }, shiftNums: { "\`": "~", "1": "!", "2": "@", "3": "#", "4": "$", "5": "%", "6": "^", "7": "&", "8": "*", "9": "(", "0": ")", "-": "_", "=": "+", ";": ": ", "'": "\"", ",": "<", ".": ">", "/": "?", "\\": "|" } }; function keyHandler( handleObj ) { // Only care when a possible input has been specified if ( typeof handleObj.data !== "string" ) { return; } var origHandler = handleObj.handler, keys = handleObj.data.toLowerCase().split(" "); handleObj.handler = function( event ) { // Don't fire in text-accepting inputs that we didn't directly bind to if ( this !== event.target && (/textarea|select/i.test( event.target.nodeName ) || event.target.type === "text") ) { return; } // Keypress represents characters, not special keys var special = event.type !== "keypress" && jQuery.hotkeys.specialKeys[ event.which ], character = String.fromCharCode( event.which ).toLowerCase(), key, modif = "", possible = {}; // check combinations (alt|ctrl|shift+anything) if ( event.altKey && special !== "alt" ) { modif += "alt+"; } if ( event.ctrlKey && special !== "ctrl" ) { modif += "ctrl+"; } // TODO: Need to make sure this works consistently across platforms if ( event.metaKey && !event.ctrlKey && special !== "meta" ) { modif += "meta+"; } if ( event.shiftKey && special !== "shift" ) { modif += "shift+"; } if ( special ) { possible[ modif + special ] = true; } else { possible[ modif + character ] = true; possible[ modif + jQuery.hotkeys.shiftNums[ character ] ] = true; // "$" can be triggered as "Shift+4" or "Shift+$" or just "$" if ( modif === "shift+" ) { possible[ jQuery.hotkeys.shiftNums[ character ] ] = true; } } for ( var i = 0, l = keys.length; i < l; i++ ) { if ( possible[ keys[i] ] ) { return origHandler.apply( this, arguments ); } } }; } jQuery.each([ "keydown", "keyup", "keypress" ], function() { jQuery.event.special[ this ] = { add: keyHandler }; }); })( jQuery );
// ==UserScript== // @id iitc-plugin-show-portal-weakness@vita10gy // @name iitc: show portal weakness // @version 0.6 // @namespace https://github.com/breunigs/ingress-intel-total-conversion // @updateURL https://raw.github.com/breunigs/ingress-intel-total-conversion/gh-pages/plugins/show-portal-weakness.user.js // @downloadURL https://raw.github.com/breunigs/ingress-intel-total-conversion/gh-pages/plugins/show-portal-weakness.user.js // @description Uses the fill color of the portals to denote if the portal is weak (Needs recharging, missing a resonator, needs shields) Red, needs energy and shields. Orange, only needs energy (either recharge or resonators). Yellow, only needs shields. // @include https://www.ingress.com/intel* // @match https://www.ingress.com/intel* // ==/UserScript== function wrapper() { // ensure plugin framework is there, even if iitc is not yet loaded if(typeof window.plugin !== 'function') window.plugin = function() {}; // PLUGIN START //////////////////////////////////////////////////////// // use own namespace for plugin window.plugin.portalWeakness = function() {}; window.plugin.portalWeakness.portalAdded = function(data) { var d = data.portal.options.details; var portal_weakness = 0; if(getTeam(d) !== 0) { var only_shields = true; var missing_shields = 0; if(window.getTotalPortalEnergy(d) > 0 && window.getCurrentPortalEnergy(d) < window.getTotalPortalEnergy(d)) { portal_weakness = 1 - (window.getCurrentPortalEnergy(d)/window.getTotalPortalEnergy(d)); only_shields = false; } //Ding the portal for every missing sheild. $.each(d.portalV2.linkedModArray, function(ind, mod) { if(mod === null) { missing_shields++; portal_weakness += .03; } }); //Ding the portal for every missing resonator. var resCount = 0; $.each(d.resonatorArray.resonators, function(ind, reso) { if(reso === null) { portal_weakness += .125; only_shields = false; } else { resCount++; } }); if(portal_weakness < 0) { portal_weakness = 0; } if(portal_weakness > 1) { portal_weakness = 1; } if(portal_weakness > 0) { var fill_opacity = portal_weakness*.7 + .3; var color = 'orange'; if(only_shields) { color = 'yellow'; //If only shields are missing, make portal yellow // but fill more than usual since pale yellow is basically invisible fill_opacity = missing_shields*.15 + .1; } else if(missing_shields > 0) { color = 'red'; } fill_opacity = Math.round(fill_opacity*100)/100; var params = {fillColor: color, fillOpacity: fill_opacity}; if(resCount < 8) { // Hole per missing resonator var dash = new Array(8-resCount + 1).join("1,4,") + "100,0" params["dashArray"] = dash; } data.portal.setStyle(params); } else { data.portal.setStyle({color: COLORS[getTeam(data.portal.options.details)], fillOpacity: 0.5, dashArray: null}); } } } window.plugin.portalWeakness.portalDataLoaded = function(data) { $.each(data.portals, function(ind, portal) { if(window.portals[portal[0]]) { window.plugin.portalWeakness.portalAdded({portal: window.portals[portal[0]]}); } }); } var setup = function() { window.addHook('portalAdded', window.plugin.portalWeakness.portalAdded); window.addHook('portalDataLoaded', window.plugin.portalWeakness.portalDataLoaded); window.COLOR_SELECTED_PORTAL = '#f0f'; } // PLUGIN END ////////////////////////////////////////////////////////// if(window.iitcLoaded && typeof setup === 'function') { setup(); } else { if(window.bootPlugins) window.bootPlugins.push(setup); else window.bootPlugins = [setup]; } } // wrapper end // inject code into site context var script = document.createElement('script'); script.appendChild(document.createTextNode('('+ wrapper +')();')); (document.body || document.head || document.documentElement).appendChild(script);
export const matchOn = (key) => (object) => (cases) => { const type = object[key] if (cases.hasOwnProperty(type)) { return cases[type](object) } else if (cases.hasOwnProperty("_")) { return cases["_"](object) } else { throw new Error(`Unmatched pattern: ${type}`) } } export const matchType = matchOn("type") export default matchType
import mod1207 from './mod1207'; var value=mod1207+1; export default value;
const exp = module.exports = {} const userMdw = require('./mdw') // unauthorized ///////////////////// const unauthHtml = exp.unauthHtml = { wel: '/msa/user/msa-user-signin.js', attrs: { unauthorized: true } } // Perm //////////////////////// exp.Perm = class { constructor(expr, kwargs) { this.expr = expr Object.assign(this, kwargs) } getExpr() { const res = this.expr if (res !== undefined) return res return this.getDefaultExpr() } getDefaultExpr() { } getDefaultValue() { return false } getDefaultExpectedValue() { return true } check(user, expVal, prevVal) { return this.checkExpr(this.getExpr(), user, expVal, prevVal) } checkExpr(expr, user, expVal, prevVal) { if (expVal === undefined) expVal = this.getDefaultExpectedValue() const val = this._solveExpr(expr, user, prevVal) return this._checkValue(expVal, val) } solve(user, prevVal) { return this._solveExpr(this.getExpr(), user, prevVal) } _solveExpr(expr, user, prevVal) { if (this.overwriteSolve) { const overVal = this.overwriteSolve(user) if (overVal !== undefined) return overVal } const val = this.solveExpr(expr, user, prevVal) return (val !== undefined) ? val : this.getDefaultValue() } solveExpr(expr, user, prevVal) { let val = prevVal if (expr !== undefined) { if (isArr(expr)) { for (let i = 0, len = expr.length; i < len; ++i) val = this.solveExpr(expr[i], user, val) } else { const newVal = this._solve(expr, user) if (newVal !== undefined) val = newVal } } return val } _checkValue(expVal, val) { return val === expVal } _solve(expr, user) { if (isObj(expr)) { // user const userId = expr.user if (userId && user && user.id == userId) return expr.value // group const groupId = expr.group if (groupId === "all") return expr.value if (groupId === "signed" && user) return expr.value const userGroups = user && user.groups if (groupId && userGroups && userGroups.indexOf(groupId) != -1) return expr.value } } // MDWS ////////////////////////////// checkMdw(val) { return (req, res, next) => { userMdw(req, res, err => { if (err) return next(err) if (!this.check(req.session.user, val)) next(req.session.user ? 403 : 401) else next() }) } } checkExprMdw(expr, val) { return (req, res, next) => { userMdw(req, res, err => { if (err) return next(err) if (!this.checkExpr(expr, req.session.user, val)) next(req.session.user ? 403 : 401) else next() }) } } checkPage(val) { return (req, res, next) => { userMdw(req, res, err => { if (err) return next(err) if (!this.check(req.session.user, val)) res.sendPage(unauthHtml) else next() }) } } checkExprPage(expr, val) { return (req, res, next) => { userMdw(req, res, err => { if (err) return next(err) if (!this.checkExpr(expr, req.session.user, val)) res.sendPage(unauthHtml) else next() }) } } } // perm instances exp.permAdmin = new exp.Perm({ group: "admin", value: true }) exp.permPublic = new exp.Perm({ group: "all", value: true }) // PermNum ///////////////////////////////// exp.PermNum = class extends exp.Perm { getDefaultValue() { return 0 } getDefaultExpectedValue() { return this.getMaxValue() } getMaxValue() { const labels = this.getLabels() return labels ? (labels.length - 1) : Number.MAX_VALUE } _checkValue(expVal, val) { return val >= expVal } // labels getLabels() { } } exp.permNumAdmin = new exp.PermNum({ group: "all", value: 0 }) exp.permNumPublic = new exp.PermNum({ group: "all", value: Number.MAX_VALUE }) // utils const isArr = Array.isArray function isObj(o) { return (typeof o === 'object') && (o !== null) }
var fs = require('fs'); var url = require('url'); var path = require('path'); var send = require('send'); var conf = require('./router.json'); var cache = {}; var pattern = conf.pattern; var handler = require('../handler'); var confList = conf.list; var shtmlReader = require('../resource/shtml'); /** * 根据正则替换传入的字符串 * str 要替换的字符串 * pattern包含两个部分 * 1: regExp 正则表达式 * 2: replace 替换规则 * @return 返回替换后的字符串 */ function replace(str, pattern) { var reg = pattern && pattern.regExp || null; if (str && reg) { return str.replace(new RegExp(reg), pattern.replace); } return str; } /** * 根据host和pathname和 route.json中配置的转发规则 生成实际的服务器端的url * 并将生成的url放入缓存, 下次请求的时候直接从缓存中获取数据 */ function _getConfig(host, pathname) { var root, fullName = host + pathname, original = fullName; //如果缓存中存在则从缓存中获取 if (cache[original]) { return cache[original]; } //记录初始的url cache[original] = { original: decodeURI(original) }; //pattern为route.json中的默认配置项 所有的url都会通过此规则过滤 if(pattern){ fullName = replace(fullName, pattern); root = replace(host, pattern); if (host === 'concat.lietou-static.com') { root = ''; } } //根据host从配置中获取配置项 若存在则根据配置规则,生成url var ruleObj = confList[host]; if (!ruleObj) { for (var k in confList) { var patten = "^" + k.replace(/\./g, '\\.').replace('*', '.*') + "$"; var reg = new RegExp(patten); if (reg.test(host)) { ruleObj = confList[k]; } } } //若在配置文件中没有找到关于此host的配置 //则使用host匹配配置中的配置项(带有通配符的配置项) //匹配成功则使用该配置 if (ruleObj) { if (typeof ruleObj === 'string') { cache[original].root = cache[original].directory = decodeURI(ruleObj); } else if (typeof ruleObj === 'object') { fullName = replace(fullName, ruleObj); root = replace(root, ruleObj).replace(/^[^\/]*(\/.*)$/, '$1'); cache[original].root = decodeURI(path.join(ruleObj.directory, root)); cache[original].directory = decodeURI(ruleObj.directory); } } //去掉url中的host(域名)部分, 并放入缓存 cache[original].pathname = decodeURI(fullName.replace(/^[^\/]*(\/.*)$/, '$1')); return cache[original]; } /** * 读取目录 * 将目录下的文件放入到一个列表中,并在浏览器端展示 * @param {[type]} dir [目录路径] * @param {[type]} res [响应response] */ function readDir(pathname, dir, res) { fs.readdir(dir, function (err, files) { if (err) { res.writeHead(500, { 'Content-Type': 'text/plain' }); res.end(err.message); return; } var html = ""; html = '<ul>'; if (pathname !== '/') { html += '<li><a href="' + encodeURI(path.dirname(pathname).replace(/\\+/g, '/')) + '">Parent Directory</a></li>'; } for (var i = 0, l = files.length; i < l; i++) { html += '<li><a href="' + encodeURI(path.join(pathname, files[i]).replace(/\\+/g, '/')) + '">' + files[i] + '</a></li>'; } html += '</ul>'; res.writeHead(200, { 'Content-Type': 'text/html' }); res.write(html, 'utf8'); res.end(); }); } /** * 路由 * * 首先根据请求的pathname判断是否有针对此pathname的配置, * @param {[type]} req [description] * @param {[type]} res [description] * @return {[type]} [description] */ function route(req, res) { var host = req.headers.host; var urlObj = url.parse(req.url); var query = urlObj.query; var pathname = urlObj.pathname; var config = _getConfig(host, pathname); // 首先判断此次请求的Root目录是否存在, // 若目录不存在且没有配置针对此次请求的pathname的handler // 返回404的错误信息 if (!config.directory && typeof handler[pathname] !== 'function') { res.writeHead(404, { 'Content-Type': 'text/plain' }); res.end('file:(' + config.original + ') Not Found'); return; } //根据pathname判断是否存在对应的handler,有则走handler if (typeof handler[pathname] === 'function') { return handler[pathname](req, res); } var fp = path.join(config.directory, config.pathname); var filetype = pathname.replace(/.*[\.\\\/]/gi, '').toLowerCase(); //字体跨域 if (/^(eot|ttf|woff|otf|svg)$/.test(filetype)) { res.setHeader('Access-Control-Allow-Origin', '*'); } console.log(pathname) //判断请求的是否是shtml文件 是则按照shtml文件解析并返回 //否则通过send模块读取文件并返回给浏览器 if (filetype === 'shtml') { shtmlReader.readFile(config.root, fp, function (err, data, encoding, filetype) { if (err) { res.writeHead(404, { 'Content-Type': 'text/plain' }); res.end('file:(' + config.original + ') Not Found'); } else { res.writeHead(200, { 'Content-Type': 'text/html' }); res.write(data, encoding || 'utf8'); res.end(); } }); } else { send(req, config.pathname, { root: config.directory }) .on('error', function (err) { //若是根目录下找不到index.html则按目录处理 if (err.status === 404 && pathname === '/') { readDir(pathname, fp, res); } else { res.statusCode = err.status || 500; res.end(err.message); } }) .on('directory', function () { readDir(pathname, fp, res); }).pipe(res); } } module.exports = route;
'use strict'; let express = require('express'); let userStory = require('mongoose').model('User_Story'); let router = express.Router(); router.post('/', userStory.exCreate); router.get('/:projectID', userStory.exGetAll); router.put('/', userStory.exEdit); router.put('/priority', userStory.exEditPriority); router.delete('/', userStory.exDelete); module.exports = router;
import React from "react" import { Link } from "react-router" import moment from "moment" const General = (props) => { return ( <div className="form-horizontal"> <div className="form-group"> <label className="col-sm-2 control-label">NAME</label> <p className="form-control-static d-inline-block"> { props.name } </p> </div> <div className="form-group"> <label className="col-sm-2 control-label">CREATED AT</label> <p className="form-control-static d-inline-block"> { moment(props.created).format("MMMM Do YYYY, h:mm:ss a") } </p> </div> </div> ) } export default General
var View = require('./view'); module.exports = View.extend({ name: 'content', initialize: function (options) { this.template = options.template; } });
<% if (sm === 'redux') { %> import React, { PropTypes } from 'react'; import { connect } from 'react-redux'; import { List } from 'immutable'; import { action } from '../actions'; import TASK from '../actions/task'; import selector from '../selectors/task';<% } else { %> import React from 'react'; import { observer, PropTypes } from 'mobx-react';<% } %> import Hello from '../components/hello'; import Tasks from '../components/tasks'; import styles from './home.css'; <% if (sm === 'redux') { %> @connect((state, props) => ({ tasks: selector(state, props), })) export default class Home extends React.PureComponent { static propTypes = { dispatch: PropTypes.func.isRequired, tasks: PropTypes.instanceOf(List).isRequired, } componentWillMount() { this.props.dispatch(action(TASK.GET_LIST.REQUEST)); } onToggle = (task) => { this.props.dispatch(action(TASK.UPDATE.REQUEST, task.set('isDone', !task.isDone))); } onAdd = () => { this.props.dispatch(action(TASK.ADD.REQUEST, { content: this.task.value })); } render() { return ( <div> <Hello styles={styles}> reactapp </Hello> <input ref={(ref) => { this.task = ref; }} type="text" placeholder="Enter task" /> <button onClick={this.onAdd}>Add</button> <Tasks tasks={this.props.tasks} onToggle={this.onToggle} /> </div> ); } } <% } else { %> @observer(['task']) export default class Home extends React.PureComponent { static propTypes = { task: PropTypes.observableObject.isRequired, } componentWillMount() { this.props.task.getList(); } onAdd = () => { this.props.task.add({ isDone: false, content: this.task.value }); this.task.value = ''; } onToggle = (task) => { this.props.task.update({ ...task, isDone: !task.isDone }); } render() { return ( <div> <Hello styles={styles}> reactapp </Hello> <input ref={(ref) => { this.task = ref; }} type="text" placeholder="Enter task" /> <button onClick={this.onAdd}>Add</button> <Tasks tasks={this.props.task.tasks} onToggle={this.onToggle} /> </div> ); } } <% } %>
// see http://vuejs-templates.github.io/webpack for documentation. var path = require('path') module.exports = { build: { env: require('./prod.env'), index: path.resolve(__dirname, '../dist/index.html'), assetsRoot: path.resolve(__dirname, '../dist'), assetsSubDirectory: 'static', assetsPublicPath: '/', productionSourceMap: true, // Gzip off by default as many popular static hosts such as // Surge or Netlify already gzip all static assets for you. // Before setting to `true`, make sure to: // npm install --save-dev compression-webpack-plugin productionGzip: false, productionGzipExtensions: ['js', 'css'], // Run the build command with an extra argument to // View the bundle analyzer report after build finishes: // `npm run build --report` // Set to `true` or `false` to always turn it on or off bundleAnalyzerReport: process.env.npm_config_report }, dev: { env: require('./dev.env'), port: 5566, autoOpenBrowser: true, assetsSubDirectory: 'static', assetsPublicPath: '/', proxyTable: {}, // CSS Sourcemaps off by default because relative paths are "buggy" // with this option, according to the CSS-Loader README // (https://github.com/webpack/css-loader#sourcemaps) // In our experience, they generally work as expected, // just be aware of this issue when enabling this option. cssSourceMap: false } }
"use strict" let cnt = 0 const mergeSort = (xs, left, right) => { if (left + 1 < right) { const mid = Math.floor((left + right) / 2) mergeSort(xs, left, mid) mergeSort(xs, mid, right) merge(xs, left, mid, right) } } const merge = (xs, left, mid, right) => { const n1 = mid - left const n2 = right - mid const ls = [] for (let i = 0; i < n1; i++) { ls[i] = xs[left + i] } ls.push(1000000000) const rs = [] for (let i = 0; i < n2; i++) { rs[i] = xs[mid + i] } rs.push(1000000000) let i = 0 let j = 0 for (let k = left; k < right; k++) { cnt++ if (ls[i] < rs[j]) { xs[k] = ls[i] i++ } else { xs[k] = rs[j] j++ } } } const solver = (n, xs) => { mergeSort(xs, 0, n) return xs } let rows = 0 let n = 0 const reader = require("readline").createInterface({ input: process.stdin, output: process.stdout, }) reader.on("line", (line) => { rows++ if (rows === 1) { n = Number(line.trim()) } else { const xs = line.trim().split(" ").map(x => Number(x)) const result = solver(n, xs) console.log(result.reduce((acc, x) => `${acc} ${x}`)) console.log(cnt) process.exit(0) } })
/* * This is a JavaScript Scratchpad. * * Enter some JavaScript, then Right Click or choose from the Execute Menu: * 1. Run to evaluate the selected text (Ctrl+R), * 2. Inspect to bring up an Object Inspector on the result (Ctrl+I), or, * 3. Display to insert the result in a comment after the selection. (Ctrl+L) */ /* * This is a JavaScript Scratchpad. * * Enter some JavaScript, then Right Click or choose from the Execute Menu: * 1. Run to evaluate the selected text (Ctrl+R), * 2. Inspect to bring up an Object Inspector on the result (Ctrl+I), or, * 3. Display to insert the result in a comment after the selection. (Ctrl+L) */ var src = new proj4.Proj('+proj=stere +lat_0=90 +lat_ts=70 +lon_0=-45 +k=1 +x_0=0 +y_0=0 +ellps=WGS84 +datum=WGS84 +units=m +no_defs'); var dst = new proj4.Proj('EPSG:4326'); var p = new proj4.Point(0.0, 0.0); //any object will do as long as it has 'x' and 'y' properties var t = proj4.transform(src, dst, p); t
var pluralize = require('pluralize') var unionKeys = require('../vendor/unionKeys') var columnExtend = require('./modelExtend') var Model = require('./Model') function setModel(name, modelDefinition, dialect, defaults) { var model = new Model() if (defaults) defaults = {} model.tableName = dialect.escapeIdentifier(pluralize.plural(name).toLowerCase()) var columns = model.columns = modelExtend(this.defaults, modelNormalizer(modelDefinition)) var primaryKey = model.primaryKey = [] for (var name in columns) { var column = columns[name] column.type = dialect.validateType(column.type) column.columnName = dialect.escapeIdentifier(name) if (column.primaryKey) { primaryKey.push(column.primaryKey) } delete column.primaryKey } return model } module.exports = setModel
var vec3 = require("vec3"), color = require("color"), createPool = require("create_pool"); var ParticlePrototype; module.exports = Particle; function Particle() { this.drag = 0.01; this.currentLife = 0; this.lifeTime = 1; this.size = 1; this.color = color.create(); this.alpha = 1; this.position = vec3.create(); this.velocity = vec3.create(); this.acceleration = vec3.create(); this.angle = 0; this.angularVelocity = 0; this.angularAcceleration = 0; } createPool(Particle); ParticlePrototype = Particle.prototype; ParticlePrototype.update = function(dt) { var pos = this.position, vel = this.velocity, acc = this.acceleration; vel[0] += acc[0] * dt; vel[1] += acc[1] * dt; vel[2] += acc[2] * dt; pos[0] += vel[0] * dt; pos[1] += vel[1] * dt; pos[2] += vel[2] * dt; this.angularVelocity += this.angularAcceleration * dt; this.angle += this.angularVelocity * dt; this.currentLife += dt; };
'use strict'; var app = require('electron').app; var BrowserWindow = require('electron').BrowserWindow; var mainWindow = null; app.on('ready', function() { mainWindow = new BrowserWindow({ height: 600, width: 800 }); //mainWindow.openDevTools(); mainWindow.loadURL('file://' + __dirname + '/index.html'); });
window.shipData = { "(无)": { chineseName: "", nameForSearch: "", shipType: "", rare: false }, "長門": { chineseName: "长门", nameForSearch: "长门,changmen,chang men,Nagato,nagato", shipType: "战舰", rare: true }, "陸奥": { chineseName: "陆奥", nameForSearch: "陆奥,luao,lu ao,Mutsu,mutsu", shipType: "战舰", rare: true }, "伊勢": { chineseName: "伊势", nameForSearch: "伊势,yishi,yi shi,Ise,ise", shipType: "战舰", rare: false }, "日向": { chineseName: "日向", nameForSearch: "日向,rixiang,ri xiang,Hyuuga,hyuuga", shipType: "战舰", rare: false }, "雪風": { chineseName: "雪风", nameForSearch: "雪风,xuefeng,xue feng,Yukikaze,yukikaze", shipType: "驱逐舰", rare: true }, "赤城": { chineseName: "赤城", nameForSearch: "赤城,chicheng,chi cheng,Akagi,akagi", shipType: "空母", rare: true }, "加賀": { chineseName: "加贺", nameForSearch: "加贺,jiahe,jia he,Kaga,kaga", shipType: "空母", rare: false }, "蒼龍": { chineseName: "苍龙", nameForSearch: "苍龙,canglong,cang long,Souryuu,souryuu", shipType: "空母", rare: false }, "飛龍": { chineseName: "飞龙", nameForSearch: "飞龙,feilong,fei long,Hiryuu,hiryuu", shipType: "空母", rare: true }, "島風": { chineseName: "岛风", nameForSearch: "岛风,daofeng,dao feng,Shimakaze,shimakaze", shipType: "驱逐舰", rare: true }, "吹雪": { chineseName: "吹雪", nameForSearch: "吹雪,chuixue,chui xue,Fubuki,fubuki", shipType: "驱逐舰", rare: false }, "白雪": { chineseName: "白雪", nameForSearch: "白雪,baixue,bai xue,Shirayuki,shirayuki", shipType: "驱逐舰", rare: false }, "初雪": { chineseName: "初雪", nameForSearch: "初雪,chuxue,chu xue,Hatsuyuki,hatsuyuki", shipType: "驱逐舰", rare: false }, "深雪": { chineseName: "深雪", nameForSearch: "深雪,shenxue,shen xue,Miyuki,miyuki", shipType: "驱逐舰", rare: false }, "叢雲": { chineseName: "丛云", nameForSearch: "丛云,congyun,cong yun,Murakumo,murakumo", shipType: "驱逐舰", rare: false }, "磯波": { chineseName: "矶波", nameForSearch: "矶波,jibo,ji bo,Isonami,isonami", shipType: "驱逐舰", rare: false }, "綾波": { chineseName: "绫波", nameForSearch: "绫波,lingbo,ling bo,Ayanami,ayanami", shipType: "驱逐舰", rare: false }, "敷波": { chineseName: "敷波", nameForSearch: "敷波,fubo,fu bo,Shikinami,shikinami", shipType: "驱逐舰", rare: false }, "大井": { chineseName: "大井", nameForSearch: "大井,dajing,da jing,Ooi,ooi", shipType: "轻巡洋舰", rare: true }, "北上": { chineseName: "北上", nameForSearch: "北上,beishang,bei shang,Kitakami,kitakami", shipType: "轻巡洋舰", rare: false }, "金剛": { chineseName: "金刚", nameForSearch: "金刚,jingang,jin gang,Kongou,kongou", shipType: "战舰", rare: false }, "比叡": { chineseName: "比睿", nameForSearch: "比睿,birui,bi rui,Hiei,hiei", shipType: "战舰", rare: false }, "榛名": { chineseName: "榛名", nameForSearch: "榛名,zhenming,zhen ming,Haruna,haruna", shipType: "战舰", rare: false }, "霧島": { chineseName: "雾岛", nameForSearch: "雾岛,wudao,wu dao,Kirishima,kirishima", shipType: "战舰", rare: false }, "鳳翔": { chineseName: "凤翔", nameForSearch: "凤翔,fengxiang,feng xiang,Houshou,houshou", shipType: "轻空母", rare: false }, "扶桑": { chineseName: "扶桑", nameForSearch: "扶桑,fusang,fu sang,Fusou,fusou", shipType: "战舰", rare: false }, "山城": { chineseName: "山城", nameForSearch: "山城,shancheng,shan cheng,Yamashiro,yamashiro", shipType: "战舰", rare: false }, "天龍": { chineseName: "天龙", nameForSearch: "天龙,tianlong,tian long,Tenryuu,tenryuu", shipType: "轻巡洋舰", rare: false }, "龍田": { chineseName: "龙田", nameForSearch: "龙田,longtian,long tian,Tatsuta,tatsuta", shipType: "轻巡洋舰", rare: false }, "龍驤": { chineseName: "龙骧", nameForSearch: "龙骧,longxiang,long xiang,Ryuujou,ryuujou", shipType: "轻空母", rare: false }, "睦月": { chineseName: "睦月", nameForSearch: "睦月,muyue,mu yue,Mutsuki,mutsuki", shipType: "驱逐舰", rare: false }, "如月": { chineseName: "如月", nameForSearch: "如月,ruyue,ru yue,Kisaragi,kisaragi", shipType: "驱逐舰", rare: false }, "皐月": { chineseName: "皋月", nameForSearch: "皋月,gaoyue,gao yue,Satsuki,satsuki", shipType: "驱逐舰", rare: false }, "文月": { chineseName: "文月", nameForSearch: "文月,wenyue,wen yue,Fumizuki,fumizuki", shipType: "驱逐舰", rare: false }, "長月": { chineseName: "长月", nameForSearch: "长月,changyue,chang yue,Nagatsuki,nagatsuki", shipType: "驱逐舰", rare: false }, "菊月": { chineseName: "菊月", nameForSearch: "菊月,juyue,ju yue,Kikuzuki,kikuzuki", shipType: "驱逐舰", rare: false }, "三日月": { chineseName: "三日月", nameForSearch: "三日月,sanriyue,san ri yue,Mikazuki,mikazuki", shipType: "驱逐舰", rare: false }, "望月": { chineseName: "望月", nameForSearch: "望月,wangyue,wang yue,Mochizuki,mochizuki", shipType: "驱逐舰", rare: false }, "球磨": { chineseName: "球磨", nameForSearch: "球磨,qiumo,qiu mo,Kuma,kuma", shipType: "轻巡洋舰", rare: false }, "多摩": { chineseName: "多摩", nameForSearch: "多摩,duomo,duo mo,Tama,tama", shipType: "轻巡洋舰", rare: false }, "木曾": { chineseName: "木曾", nameForSearch: "木曾,muzeng,mu zeng,Kiso,kiso", shipType: "轻巡洋舰", rare: false }, "長良": { chineseName: "长良", nameForSearch: "长良,changliang,chang liang,Nagara,nagara", shipType: "轻巡洋舰", rare: false }, "五十鈴": { chineseName: "五十铃", nameForSearch: "五十铃,wushiling,wu shi ling,500,Isuzu,isuzu", shipType: "轻巡洋舰", rare: false }, "名取": { chineseName: "名取", nameForSearch: "名取,mingqu,ming qu,Natori,natori", shipType: "轻巡洋舰", rare: false }, "由良": { chineseName: "由良", nameForSearch: "由良,youliang,you liang,Yura,yura", shipType: "轻巡洋舰", rare: false }, "川内": { chineseName: "川内", nameForSearch: "川内,chuannei,chuan nei,Sendai,sendai", shipType: "轻巡洋舰", rare: false }, "神通": { chineseName: "神通", nameForSearch: "神通,shentong,shen tong,Jintsuu,jintsuu", shipType: "轻巡洋舰", rare: false }, "那珂": { chineseName: "那珂", nameForSearch: "那珂,nake,na ke,Naka,naka", shipType: "轻巡洋舰", rare: false }, "千歳": { chineseName: "千岁", nameForSearch: "千岁,qiansui,qian sui,Chitose,chitose", shipType: "水母", rare: false }, "千代田": { chineseName: "千代田", nameForSearch: "千代田,qiandaitian,qian dai tian,Chiyoda,chiyoda", shipType: "水母", rare: false }, "最上": { chineseName: "最上", nameForSearch: "最上,zuishang,zui shang,Mogami,mogami", shipType: "重巡洋舰", rare: false }, "古鷹": { chineseName: "古鹰", nameForSearch: "古鹰,guying,gu ying,Furutaka,furutaka", shipType: "重巡洋舰", rare: false }, "加古": { chineseName: "加古", nameForSearch: "加古,jiagu,jia gu,Kako,kako", shipType: "重巡洋舰", rare: false }, "青葉": { chineseName: "青叶", nameForSearch: "青叶,qingye,qing ye,Aoba,aoba", shipType: "重巡洋舰", rare: false }, "妙高": { chineseName: "妙高", nameForSearch: "妙高,miaogao,miao gao,Myoukou,myoukou", shipType: "重巡洋舰", rare: false }, "那智": { chineseName: "那智", nameForSearch: "那智,nazhi,na zhi,Nachi,nachi", shipType: "重巡洋舰", rare: false }, "足柄": { chineseName: "足柄", nameForSearch: "足柄,zubing,zu bing,Ashigara,ashigara", shipType: "重巡洋舰", rare: false }, "羽黒": { chineseName: "羽黑", nameForSearch: "羽黑,yuhei,yu hei,Haguro,haguro", shipType: "重巡洋舰", rare: false }, "高雄": { chineseName: "高雄", nameForSearch: "高雄,gaoxiong,gao xiong,Takao,takao", shipType: "重巡洋舰", rare: false }, "愛宕": { chineseName: "爱宕", nameForSearch: "爱宕,aidang,ai dang,Atago,atago", shipType: "重巡洋舰", rare: false }, "摩耶": { chineseName: "摩耶", nameForSearch: "摩耶,moye,mo ye,Maya,maya", shipType: "重巡洋舰", rare: false }, "鳥海": { chineseName: "鸟海", nameForSearch: "鸟海,niaohai,niao hai,Choukai,choukai", shipType: "重巡洋舰", rare: false }, "利根": { chineseName: "利根", nameForSearch: "利根,ligen,li gen,Tone,tone", shipType: "重巡洋舰", rare: false }, "筑摩": { chineseName: "筑摩", nameForSearch: "筑摩,zhumo,zhu mo,Chikuma,chikuma", shipType: "重巡洋舰", rare: false }, "飛鷹": { chineseName: "飞鹰", nameForSearch: "飞鹰,feiying,fei ying,Hiyou,hiyou", shipType: "轻空母", rare: false }, "隼鷹": { chineseName: "隼鹰", nameForSearch: "隼鹰,sunying,sun ying,Junyou,junyou", shipType: "轻空母", rare: false }, "朧": { chineseName: "胧", nameForSearch: "胧,long,Oboro,oboro", shipType: "驱逐舰", rare: false }, "曙": { chineseName: "曙", nameForSearch: "曙,shu,Akebono,akebono", shipType: "驱逐舰", rare: false }, "漣": { chineseName: "涟", nameForSearch: "涟,lian,Sazanami,sazanami", shipType: "驱逐舰", rare: false }, "潮": { chineseName: "潮", nameForSearch: "潮,chao,Ushio,ushio", shipType: "驱逐舰", rare: false }, "暁": { chineseName: "晓", nameForSearch: "晓,xiao,Akatsuki,akatsuki", shipType: "驱逐舰", rare: false }, "響": { chineseName: "响", nameForSearch: "响,xiang,Hibiki,hibiki", shipType: "驱逐舰", rare: false }, "雷": { chineseName: "雷", nameForSearch: "雷,lei,Ikazuchi,ikazuchi", shipType: "驱逐舰", rare: false }, "電": { chineseName: "电", nameForSearch: "电,dian,Inazuma,inazuma", shipType: "驱逐舰", rare: false }, "初春": { chineseName: "初春", nameForSearch: "初春,chuchun,chu chun,Hatsuharu,hatsuharu", shipType: "驱逐舰", rare: false }, "子日": { chineseName: "子日", nameForSearch: "子日,ziri,zi ri,Nenohi,nenohi", shipType: "驱逐舰", rare: false }, "若葉": { chineseName: "若叶", nameForSearch: "若叶,ruoye,ruo ye,Wakaba,wakaba", shipType: "驱逐舰", rare: false }, "初霜": { chineseName: "初霜", nameForSearch: "初霜,chushuang,chu shuang,Hatsushimo,hatsushimo", shipType: "驱逐舰", rare: false }, "白露": { chineseName: "白露", nameForSearch: "白露,bailu,bai lu,Shiratsuyu,shiratsuyu", shipType: "驱逐舰", rare: false }, "時雨": { chineseName: "时雨", nameForSearch: "时雨,shiyu,shi yu,Shigure,shigure", shipType: "驱逐舰", rare: false }, "村雨": { chineseName: "村雨", nameForSearch: "村雨,cunyu,cun yu,Murasame,murasame", shipType: "驱逐舰", rare: false }, "夕立": { chineseName: "夕立", nameForSearch: "夕立,xili,xi li,poi,Yuudachi,yuudachi", shipType: "驱逐舰", rare: false }, "五月雨": { chineseName: "五月雨", nameForSearch: "五月雨,wuyueyu,wu yue yu,Samidare,samidare", shipType: "驱逐舰", rare: false }, "涼風": { chineseName: "凉风", nameForSearch: "凉风,liangfeng,liang feng,Suzukaze,suzukaze", shipType: "驱逐舰", rare: false }, "朝潮": { chineseName: "朝潮", nameForSearch: "朝潮,zhaochao,zhao chao,Asashio,asashio", shipType: "驱逐舰", rare: false }, "大潮": { chineseName: "大潮", nameForSearch: "大潮,dachao,da chao,Ooshio,ooshio", shipType: "驱逐舰", rare: false }, "満潮": { chineseName: "满潮", nameForSearch: "满潮,manchao,man chao,Michishio,michishio", shipType: "驱逐舰", rare: false }, "荒潮": { chineseName: "荒潮", nameForSearch: "荒潮,huangchao,huang chao,Arashio,arashio", shipType: "驱逐舰", rare: false }, "霰": { chineseName: "霰", nameForSearch: "霰,xian,Arare,arare", shipType: "驱逐舰", rare: false }, "霞": { chineseName: "霞", nameForSearch: "霞,xia,Kasumi,kasumi", shipType: "驱逐舰", rare: false }, "陽炎": { chineseName: "阳炎", nameForSearch: "阳炎,yangyan,yang yan,Kagerou,kagerou", shipType: "驱逐舰", rare: false }, "不知火": { chineseName: "不知火", nameForSearch: "不知火,buzhihuo,bu zhi huo,Shiranui,shiranui", shipType: "驱逐舰", rare: false }, "黒潮": { chineseName: "黑潮", nameForSearch: "黑潮,heichao,hei chao,Kuroshio,kuroshio", shipType: "驱逐舰", rare: false }, "祥鳳": { chineseName: "祥凤", nameForSearch: "祥凤,xiangfeng,xiang feng,Shouhou,shouhou", shipType: "轻空母", rare: false }, "翔鶴": { chineseName: "翔鹤", nameForSearch: "翔鹤,xianghe,xiang he,Shoukaku,shoukaku", shipType: "空母", rare: true }, "瑞鶴": { chineseName: "瑞鹤", nameForSearch: "瑞鹤,ruihe,rui he,Zuikaku,zuikaku", shipType: "空母", rare: true }, "鬼怒": { chineseName: "鬼怒", nameForSearch: "鬼怒,guinu,gui nu,Kinu,kinu", shipType: "轻巡洋舰", rare: true }, "阿武隈": { chineseName: "阿武隈", nameForSearch: "阿武隈,awuwei,a wu wei,aww,Abukuma,abukuma", shipType: "轻巡洋舰", rare: true }, "夕張": { chineseName: "夕张", nameForSearch: "夕张,xizhang,xi zhang,Yuubari,yuubari", shipType: "轻巡洋舰", rare: true }, "瑞鳳": { chineseName: "瑞凤", nameForSearch: "瑞凤,ruifeng,rui feng,Zuihou,zuihou", shipType: "轻空母", rare: true }, "三隈": { chineseName: "三隈", nameForSearch: "三隈,sanwei,san wei,Mikuma,mikuma", shipType: "重巡洋舰", rare: true }, "初風": { chineseName: "初风", nameForSearch: "初风,chufeng,chu feng,Hatsukaze,hatsukaze", shipType: "驱逐舰", rare: true }, "舞風": { chineseName: "舞风", nameForSearch: "舞风,wufeng,wu feng,Maikaze,maikaze", shipType: "驱逐舰", rare: true }, "衣笠": { chineseName: "衣笠", nameForSearch: "衣笠,yili,yi li,Kinugasa,kinugasa", shipType: "重巡洋舰", rare: true }, "伊19": { chineseName: "伊19", nameForSearch: "伊19,I19,i19,Iku,iku,I-19,i-19", shipType: "潜水舰", rare: true }, "鈴谷": { chineseName: "铃谷", nameForSearch: "铃谷,linggu,ling gu,Suzuya,suzuya", shipType: "重巡洋舰", rare: true }, "熊野": { chineseName: "熊野", nameForSearch: "熊野,xiongye,xiong ye,Kumano,kumano", shipType: "重巡洋舰", rare: true }, "伊168": { chineseName: "伊168", nameForSearch: "伊168,I168,i168,Imuya,imuya,I-168,i-168", shipType: "潜水舰", rare: true }, "伊58": { chineseName: "伊58", nameForSearch: "伊58,I58,i58,Goya,goya,I-58,i-58", shipType: "潜水舰", rare: true }, "伊8": { chineseName: "伊8", nameForSearch: "伊8,I8,i8,Hachi,hachi,I-8,i-8", shipType: "潜水舰", rare: true }, "秋雲": { chineseName: "秋云", nameForSearch: "秋云,qiuyun,qiu yun,Akigumo,akigumo", shipType: "驱逐舰", rare: true }, "夕雲": { chineseName: "夕云", nameForSearch: "夕云,xiyun,xi yun,Yuugumo,yuugumo", shipType: "驱逐舰", rare: true }, "巻雲": { chineseName: "卷云", nameForSearch: "卷云,juanyun,juan yun,Makigumo,makigumo", shipType: "驱逐舰", rare: true }, "長波": { chineseName: "长波", nameForSearch: "长波,changbo,chang bo,Naganami,naganami", shipType: "驱逐舰", rare: true }, "阿賀野": { chineseName: "阿贺野", nameForSearch: "阿贺野,aheye,a he ye,Agano,agano", shipType: "轻巡洋舰", rare: true }, "能代": { chineseName: "能代", nameForSearch: "能代,nengdai,neng dai,Noshiro,noshiro", shipType: "轻巡洋舰", rare: true }, "矢矧": { chineseName: "矢矧", nameForSearch: "矢矧,shishen,shi shen,Yahagi,yahagi", shipType: "轻巡洋舰", rare: true }, "酒匂": { chineseName: "酒匂", nameForSearch: "酒匂,jiuxiong,jiu xiong,Sakawa,sakawa", shipType: "轻巡洋舰", rare: true }, "香取": { chineseName: "香取", nameForSearch: "香取,xiangqu,xiang qu,Katori,katori", shipType: "练习巡洋舰", rare: true }, "伊401": { chineseName: "伊401", nameForSearch: "伊401,I401,i401,Iona,iona,I-401,i-401", shipType: "潜水空母", rare: true }, "あきつ丸": { chineseName: "秋津丸", nameForSearch: "秋津丸,qiujinwan,qiu jin wan,Akitsu Maru,akitsu maru", shipType: "扬陆舰", rare: true }, "まるゆ": { chineseName: "丸输", nameForSearch: "丸输,wanshu,wan shu,maluyou,ma lu you,Maruyu,maruyu", shipType: "潜水舰", rare: true }, "弥生": { chineseName: "弥生", nameForSearch: "弥生,misheng,mi sheng,Yayoi,yayoi", shipType: "驱逐舰", rare: true }, "卯月": { chineseName: "卯月", nameForSearch: "卯月,maoyue,mao yue,Uzuki,uzuki", shipType: "驱逐舰", rare: true }, "磯風": { chineseName: "矶风", nameForSearch: "矶风,jifeng,ji feng,Isokaze,isokaze", shipType: "驱逐舰", rare: true }, "浦風": { chineseName: "浦风", nameForSearch: "浦风,pufeng,pu feng,Urakaze,urakaze", shipType: "驱逐舰", rare: true }, "谷風": { chineseName: "谷风", nameForSearch: "谷风,gufeng,gu feng,Tanikaze,tanikaze", shipType: "驱逐舰", rare: true }, "浜風": { chineseName: "滨风", nameForSearch: "滨风,binfeng,bin feng,Hamakaze,hamakaze", shipType: "驱逐舰", rare: true }, "Z1": { chineseName: "Z1", nameForSearch: "Z1", shipType: "驱逐舰", rare: true }, "Z3": { chineseName: "Z3", nameForSearch: "Z3", shipType: "驱逐舰", rare: true }, "Prinz Eugen": { chineseName: "Prinz Eugen", nameForSearch: "Prinz Eugen,prinz eugen,prinzeugen,欧根亲王,ougenqinwang,ou gen qin wang", shipType: "重巡洋舰", rare: true }, "天津風": { chineseName: "天津风", nameForSearch: "天津风,tianjinfeng,tian jin feng,Amatsukaze,amatsukaze", shipType: "驱逐舰", rare: true }, "明石": { chineseName: "明石", nameForSearch: "明石,mingshi,ming shi,Akashi,akashi", shipType: "工作舰", rare: true }, "大淀": { chineseName: "大淀", nameForSearch: "大淀,dadian,da dian,Ooyodo,ooyodo", shipType: "轻巡洋舰", rare: true }, "大鯨": { chineseName: "大鲸", nameForSearch: "大鲸,dajing,da jing,Taigei,taigei", shipType: "潜水母舰", rare: true }, "時津風": { chineseName: "时津风", nameForSearch: "时津风,shijinfeng,shi jin feng,Tokitsukaze,tokitsukaze", shipType: "驱逐舰", rare: true }, "雲龍": { chineseName: "云龙", nameForSearch: "云龙,yunlong,yun long,Unryuu,unryuu", shipType: "空母", rare: true }, "天城": { chineseName: "天城", nameForSearch: "天城,tiancheng,tian cheng,Amagi,amagi", shipType: "空母", rare: true }, "葛城": { chineseName: "葛城", nameForSearch: "葛城,gecheng,ge cheng,Katsuragi,katsuragi", shipType: "空母", rare: true }, "春雨": { chineseName: "春雨", nameForSearch: "春雨,chunyu,chun yu,Harusame,harusame", shipType: "驱逐舰", rare: true }, "早霜": { chineseName: "早霜", nameForSearch: "早霜,zaoshuang,zao shuang,Hayashimo,hayashimo", shipType: "驱逐舰", rare: true }, "清霜": { chineseName: "清霜", nameForSearch: "清霜,qingshuang,qing shuang,Kiyoshimo,kiyoshimo", shipType: "驱逐舰", rare: true }, "朝雲": { chineseName: "朝云", nameForSearch: "朝云,zhaoyun,zhao yun,Asagumo,asagumo", shipType: "驱逐舰", rare: true }, "山雲": { chineseName: "山云", nameForSearch: "山云,shanyun,shan yun,Yamagumo,yamagumo", shipType: "驱逐舰", rare: true }, "野分": { chineseName: "野分", nameForSearch: "野分,yefen,ye fen,Nowaki,nowaki", shipType: "驱逐舰", rare: true }, "秋月": { chineseName: "秋月", nameForSearch: "秋月,qiuyue,qiu yue,Akizuki,akizuki", shipType: "驱逐舰", rare: true }, "高波": { chineseName: "高波", nameForSearch: "高波,gaobo,gao bo,Takanami,takanami", shipType: "驱逐舰", rare: true }, "朝霜": { chineseName: "朝霜", nameForSearch: "朝霜,zhaoshuang,zhao shuang,Asashimo,asashimo", shipType: "驱逐舰", rare: true }, "U-511": { chineseName: "U-511", nameForSearch: "U-511,u-511,U511,u511", shipType: "潜水舰", rare: true }, "Littorio": { chineseName: "Littorio", nameForSearch: "Littorio,littorio,利托里奥,lituoliao,li tuo li ao", shipType: "战舰", rare: true }, "Roma": { chineseName: "Roma", nameForSearch: "Roma,roma,罗马,luoma,luo ma", shipType: "战舰", rare: true }, "秋津洲": { chineseName: "秋津洲", nameForSearch: "秋津洲,qiujinzhou,qiu jin zhou,Akitsushima,akitsushima", shipType: "水母", rare: true }, "瑞穂": { chineseName: "瑞穗", nameForSearch: "瑞穗,ruisui,rui sui,Mizuho,mizuho", shipType: "水母", rare: true }, "風雲": { chineseName: "风云", nameForSearch: "风云,fengyun,feng yun,Kazagumo,kazagumo", shipType: "驱逐舰", rare: true }, "海風": { chineseName: "海风", nameForSearch: "海风,haifeng,hai feng,Umikaze,umikaze", shipType: "驱逐舰", rare: true }, "江風": { chineseName: "江风", nameForSearch: "江风,jiangfeng,jiang feng,Kawakaze,kawakaze", shipType: "驱逐舰", rare: true }, "速吸": { chineseName: "速吸", nameForSearch: "速吸,suxi,su xi,Hayasui,hayasui", shipType: "补给舰", rare: true }, "Libeccio": { chineseName: "Libeccio", nameForSearch: "利伯齐奥,liboqiao,li bo qi ao,libeccio", shipType: "驱逐舰", rare: true }, "照月": { chineseName: "照月", nameForSearch: "照月,zhaoyue,zhao yue,Teruzuki,teruzuki", shipType: "驱逐舰", rare: true }, "Graf Zeppelin": { chineseName: "Graf Zeppelin", nameForSearch: "齐柏林,qibolin,qi bo lin", shipType: "空母", rare: true }, "萩風": { chineseName: "萩风", nameForSearch: "萩风,qiufeng,qiu feng", shipType: "驱逐舰", rare: true }, "嵐": { chineseName: "岚", nameForSearch: "岚,lan", shipType: "驱逐舰", rare: true }, "初月": { chineseName: "初月", nameForSearch: "初月,chuyue,chu yue", shipType: "驱逐舰", rare: true }, "Zara": { chineseName: "Zara", nameForSearch: "Zara,zara", shipType: "重巡洋舰", rare: true }, "沖波": { chineseName: "冲波", nameForSearch: "冲波,chongbo,chong bo", shipType: "驱逐舰", rare: true }, "鹿島": { chineseName: "鹿岛", nameForSearch: "鹿岛,ludao,lu dao,kashima", shipType: "练习巡洋舰", rare: true }, "親潮": { chineseName: "亲潮", nameForSearch: "亲潮,qinchao,qin chao", shipType: "驱逐舰", rare: true }, "春風": { chineseName: "春风", nameForSearch: "春风,chunfeng,chun feng", shipType: "驱逐舰", rare: true }, "Warspite": { chineseName: "Warspite", nameForSearch: "", shipType: "战舰", rare: true }, "Aquila": { chineseName: "Aquila", nameForSearch: "", shipType: "空母", rare: true }, "水無月": { chineseName: "水无月", nameForSearch: "", shipType: "驱逐舰", rare: true }, "伊26": { chineseName: "伊26", nameForSearch: "", shipType: "潜水舰", rare: true }, "浦波": { chineseName: "浦波", nameForSearch: "", shipType: "驱逐舰", rare: true }, "山風": { chineseName: "山风", nameForSearch: "", shipType: "驱逐舰", rare: true }, "Commandant Teste": { chineseName: "塔斯特司令官", nameForSearch: "", shipType: "水母", rare: true }, "神風": { chineseName: "神风", nameForSearch: "", shipType: "驱逐舰", rare: true }, "朝風": { chineseName: "朝风", nameForSearch: "", shipType: "驱逐舰", rare: true }, "Pola": { chineseName: "Pola", nameForSearch: "", shipType: "重巡洋舰", rare: true }, "藤波": { chineseName: "藤波", nameForSearch: "", shipType: "驱逐舰", rare: true }, "伊13": { chineseName: "伊13", nameForSearch: "", shipType: "潜水舰", rare: true }, "伊14": { chineseName: "伊14", nameForSearch: "", shipType: "潜水舰", rare: true }, "国後": { chineseName: "国後", nameForSearch: "", shipType: "海防舰", rare: true }, "占守": { chineseName: "占守", nameForSearch: "", shipType: "海防舰", rare: true }, "神威": { chineseName: "神威", nameForSearch: "", shipType: "补给舰", rare: true }, "択捉": { chineseName: "泽捉", nameForSearch: "", shipType: "海防舰", rare: true }, "天霧": { chineseName: "天雾", nameForSearch: "", shipType: "驱逐舰", rare: true }, "狭霧": { chineseName: "狭雾", nameForSearch: "", shipType: "驱逐舰", rare: true }, "Luigi Torelli": { chineseName: "Luigi Torelli", nameForSearch: "", shipType: "潜水舰", rare: true }, "松輪": { chineseName: "松轮", nameForSearch: "", shipType: "海防舰", rare: true }, "Iowa": { chineseName: "Iowa", nameForSearch: "", shipType: "战舰", rare: true }, "Saratoga": { chineseName: "Saratoga", nameForSearch: "", shipType: "空母", rare: true }, "Bismarck": { chineseName: "Bismarck", nameForSearch: "", shipType: "战舰", rare: true }, "Ark Royal": { chineseName: "Ark Royal", nameForSearch: "", shipType: "空母", rare: true }, "Richelieu": { chineseName: "Richelieu", nameForSearch: "", shipType: "战舰", rare: true }, "Гангут": { chineseName: "Гангут", nameForSearch: "", shipType: "战舰", rare: true }, "Ташкент": { chineseName: "Ташкент", nameForSearch: "", shipType: "驱逐舰", rare: true }, "Jervis": { chineseName: "Jervis", nameForSearch: "", shipType: "驱逐舰", rare: true }, "浜波": { chineseName: "浜波", nameForSearch: "", shipType: "驱逐舰", rare: true }, "松風": { chineseName: "松風", nameForSearch: "", shipType: "海防舰", rare: true }, "大東": { chineseName: "大東", nameForSearch: "", shipType: "海防舰", rare: true }, "春日丸": { chineseName: "春日丸", nameForSearch: "", shipType: "轻空母", rare: true }, "岸波": { chineseName: "岸波", nameForSearch: "", shipType: "驱逐舰", rare: true }, "伊400": { chineseName: "伊400", nameForSearch: "", shipType: "潜水舰", rare: true }, "日振": { chineseName: "日振", nameForSearch: "", shipType: "海防舰", rare: true } }; window.shipSearchTag = { "驱逐舰": ":dd", "轻巡洋舰": ":cl", "重巡洋舰": ":ca", "空母": ":cv", "轻空母": ":cvl", "战舰": ":bb", "潜水舰": ":ss", "潜水空母": ":ssv", "水母": ":av", "扬陆舰": ":lha", "工作舰": ":ar", "潜水母舰": ":as", "练习巡洋舰": ":clp", "补给舰": ":ao", "稀有": ":稀有,:rare,:sr,:ur", "海防舰": ":de", " ": "" }; window.mapWikiData = { 11: '1-1', 12: '1-2', 13: '1-3', 14: '1-4', 15: '1-5', 16: '1-6', 21: '2-1', 22: '2-2', 23: '2-3', 24: '2-4', 25: '2-5', 31: '3-1', 32: '3-2', 33: '3-3', 34: '3-4', 35: '3-5', 41: '4-1', 42: '4-2', 43: '4-3', 44: '4-4', 45: '4-5', 51: '5-1', 52: '5-2', 53: '5-3', 54: '5-4', 55: '5-5', 61: '6-1', 62: '6-2', 63: '6-3', 64: '6-4', 65: '6-5', 71: '7-1', 72: '7-2', 311: '2015年夏季活动/主作战#E-1', 312: '2015年夏季活动/主作战#E-2', 313: '2015年夏季活动/主作战#E-3', 314: '2015年夏季活动/主作战#E-4', 315: '2015年夏季活动/扩展作战#E-5', 316: '2015年夏季活动/扩展作战#E-6', 317: '2015年夏季活动/扩展作战#E-7', 321: '2015年秋季活动/E-1', 322: '2015年秋季活动/E-2', 323: '2015年秋季活动/E-3', 324: '2015年秋季活动/E-4', 325: '2015年秋季活动/E-5', 331: '2016年冬季活动/E-1', 332: '2016年冬季活动/E-2', 333: '2016年冬季活动/E-3', 341: '2016年春季活动/E-1', 342: '2016年春季活动/E-2', 343: '2016年春季活动/E-3', 344: '2016年春季活动/E-4', 345: '2016年春季活动/E-5', 346: '2016年春季活动/E-6', 347: '2016年春季活动/E-7', 351: '2016年夏季活动/E-1', 352: '2016年夏季活动/E-2', 353: '2016年夏季活动/E-3', 354: '2016年夏季活动/E-4', 361: '2016年秋季活动/E-1', 362: '2016年秋季活动/E-2', 363: '2016年秋季活动/E-3', 364: '2016年秋季活动/E-4', 365: '2016年秋季活动/E-5', 371: '2017年冬季活动/E-1', 372: '2017年冬季活动/E-2', 373: '2017年冬季活动/E-3', 381: '2017年春季活动/E-1', 382: '2017年春季活动/E-2', 383: '2017年春季活动/E-3', 384: '2017年春季活动/E-4', 385: '2017年春季活动/E-5', 391: '2017年夏季活动/E-1', 392: '2017年夏季活动/E-2', 393: '2017年夏季活动/E-3', 394: '2017年夏季活动/E-4', 395: '2017年夏季活动/E-5', 396: '2017年夏季活动/E-6', 397: '2017年夏季活动/E-7', 401: '2017年秋季活动/E-1', 402: '2017年秋季活动/E-2', 403: '2017年秋季活动/E-3', 404: '2017年秋季活动/E-4', 411: '2018年冬季活动/E-1', 412: '2018年冬季活动/E-2', 413: '2018年冬季活动/E-3', 414: '2018年冬季活动/E-4', 415: '2018年冬季活动/E-5', 416: '2018年冬季活动/E-6', 417: '2018年冬季活动/E-7', 421: '2018年初秋活动/E-1', 422: '2018年初秋活动/E-2', 423: '2018年初秋活动/E-3', 424: '2018年初秋活动/E-4', 425: '2018年初秋活动/E-5', 431: '2019年冬季活动/E-1', 432: '2019年冬季活动/E-2', 433: '2019年冬季活动/E-3', 441: '2019年春季活动/E-1', 442: '2019年春季活动/E-2', 443: '2019年春季活动/E-3', 444: '2019年春季活动/E-4', 445: '2019年春季活动/E-5', 451: '2019年夏季活动/E-1', 452: '2019年夏季活动/E-2', 453: '2019年夏季活动/E-3', 454: '2019年夏季活动/E-4', 455: '2019年夏季活动/E-5', 461: '2019年秋季活动/E-1', 462: '2019年秋季活动/E-2', 463: '2019年秋季活动/E-3', 464: '2019年秋季活动/E-4', 465: '2019年秋季活动/E-5', 466: '2019年秋季活动/E-6', 471: '2020年桃之节句期间限定海域/E-1', 481: '2020年夏季活动/E-1', 482: '2020年夏季活动/E-2', 483: '2020年夏季活动/E-3', 484: '2020年夏季活动/E-4', 485: '2020年夏季活动/E-5', 486: '2020年夏季活动/E-6', 487: '2020年夏季活动/E-7' };
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _bluebirdLst; function _load_bluebirdLst() { return _bluebirdLst = require("bluebird-lst"); } var _bluebirdLst2; function _load_bluebirdLst2() { return _bluebirdLst2 = _interopRequireDefault(require("bluebird-lst")); } var _builderUtil; function _load_builderUtil() { return _builderUtil = require("builder-util"); } var _electronOsxSign; function _load_electronOsxSign() { return _electronOsxSign = require("electron-osx-sign"); } var _fsExtraP; function _load_fsExtraP() { return _fsExtraP = require("fs-extra-p"); } var _path = _interopRequireWildcard(require("path")); var _deepAssign; function _load_deepAssign() { return _deepAssign = require("read-config-file/out/deepAssign"); } var _appInfo; function _load_appInfo() { return _appInfo = require("./appInfo"); } var _codeSign; function _load_codeSign() { return _codeSign = require("./codeSign"); } var _core; function _load_core() { return _core = require("./core"); } var _platformPackager; function _load_platformPackager() { return _platformPackager = require("./platformPackager"); } var _dmg; function _load_dmg() { return _dmg = require("./targets/dmg"); } var _pkg; function _load_pkg() { return _pkg = require("./targets/pkg"); } var _targetFactory; function _load_targetFactory() { return _targetFactory = require("./targets/targetFactory"); } var _ArchiveTarget; function _load_ArchiveTarget() { return _ArchiveTarget = require("./targets/ArchiveTarget"); } var _semver; function _load_semver() { return _semver = _interopRequireWildcard(require("semver")); } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } class MacPackager extends (_platformPackager || _load_platformPackager()).PlatformPackager { constructor(info) { super(info); if (this.packagerOptions.cscLink == null || process.platform !== "darwin") { this.codeSigningInfo = (_bluebirdLst2 || _load_bluebirdLst2()).default.resolve({ keychainName: process.env.CSC_KEYCHAIN || null }); } else { this.codeSigningInfo = (0, (_codeSign || _load_codeSign()).createKeychain)({ tmpDir: info.tempDirManager, cscLink: this.packagerOptions.cscLink, cscKeyPassword: this.getCscPassword(), cscILink: this.packagerOptions.cscInstallerLink, cscIKeyPassword: this.packagerOptions.cscInstallerKeyPassword, currentDir: this.projectDir }); } } get defaultTarget() { const electronUpdaterCompatibility = this.platformSpecificBuildOptions.electronUpdaterCompatibility; return electronUpdaterCompatibility == null || (_semver || _load_semver()).satisfies("2.16.0", electronUpdaterCompatibility) ? ["zip", "dmg"] : ["dmg"]; } prepareAppInfo(appInfo) { return new (_appInfo || _load_appInfo()).AppInfo(this.info, this.platformSpecificBuildOptions.bundleVersion); } getIconPath() { var _this = this; return (0, (_bluebirdLst || _load_bluebirdLst()).coroutine)(function* () { let iconPath = _this.platformSpecificBuildOptions.icon || _this.config.icon; if (iconPath != null && !iconPath.endsWith(".icns")) { iconPath += ".icns"; } return iconPath == null ? yield _this.getDefaultIcon("icns") : yield _this.getResource(iconPath); })(); } createTargets(targets, mapper) { for (const name of targets) { switch (name) { case (_core || _load_core()).DIR_TARGET: break; case "dmg": mapper(name, outDir => new (_dmg || _load_dmg()).DmgTarget(this, outDir)); break; case "zip": const electronUpdaterCompatibility = this.platformSpecificBuildOptions.electronUpdaterCompatibility; mapper(name, outDir => new (_ArchiveTarget || _load_ArchiveTarget()).ArchiveTarget(name, outDir, this, targets.some(it => it === "dmg") && (electronUpdaterCompatibility == null || (_semver || _load_semver()).satisfies("2.16.0", electronUpdaterCompatibility)))); break; case "pkg": mapper(name, outDir => new (_pkg || _load_pkg()).PkgTarget(this, outDir)); break; default: mapper(name, outDir => name === "mas" || name === "mas-dev" ? new (_targetFactory || _load_targetFactory()).NoOpTarget(name) : (0, (_targetFactory || _load_targetFactory()).createCommonTarget)(name, outDir, this)); break; } } } get platform() { return (_core || _load_core()).Platform.MAC; } pack(outDir, arch, targets, taskManager) { var _this2 = this; return (0, (_bluebirdLst || _load_bluebirdLst()).coroutine)(function* () { let nonMasPromise = null; const hasMas = targets.length !== 0 && targets.some(function (it) { return it.name === "mas" || it.name === "mas-dev"; }); const prepackaged = _this2.packagerOptions.prepackaged; if (!hasMas || targets.length > 1) { const appPath = prepackaged == null ? _path.join(_this2.computeAppOutDir(outDir, arch), `${_this2.appInfo.productFilename}.app`) : prepackaged; nonMasPromise = (prepackaged ? (_bluebirdLst2 || _load_bluebirdLst2()).default.resolve() : _this2.doPack(outDir, _path.dirname(appPath), _this2.platform.nodeName, arch, _this2.platformSpecificBuildOptions, targets)).then(function () { return _this2.sign(appPath, null, null); }).then(function () { return _this2.packageInDistributableFormat(appPath, (_builderUtil || _load_builderUtil()).Arch.x64, targets, taskManager); }); } for (const target of targets) { const targetName = target.name; if (!(targetName === "mas" || targetName === "mas-dev")) { continue; } const masBuildOptions = (0, (_deepAssign || _load_deepAssign()).deepAssign)({}, _this2.platformSpecificBuildOptions, _this2.config.mas); if (targetName === "mas-dev") { (0, (_deepAssign || _load_deepAssign()).deepAssign)(masBuildOptions, _this2.config[targetName], { type: "development" }); } const targetOutDir = _path.join(outDir, targetName); if (prepackaged == null) { yield _this2.doPack(outDir, targetOutDir, "mas", arch, masBuildOptions, [target]); yield _this2.sign(_path.join(targetOutDir, `${_this2.appInfo.productFilename}.app`), targetOutDir, masBuildOptions); } else { yield _this2.sign(prepackaged, targetOutDir, masBuildOptions); } } if (nonMasPromise != null) { yield nonMasPromise; } })(); } sign(appPath, outDir, masOptions) { var _this3 = this; return (0, (_bluebirdLst || _load_bluebirdLst()).coroutine)(function* () { if (!(0, (_codeSign || _load_codeSign()).isSignAllowed)()) { return; } const isMas = masOptions != null; const macOptions = _this3.platformSpecificBuildOptions; const qualifier = (isMas ? masOptions.identity : null) || macOptions.identity; if (!isMas && qualifier === null) { if (_this3.forceCodeSigning) { throw new Error("identity explicitly is set to null, but forceCodeSigning is set to true"); } (0, (_builderUtil || _load_builderUtil()).log)("identity explicitly is set to null, skipping macOS application code signing."); return; } const keychainName = (yield _this3.codeSigningInfo).keychainName; const explicitType = isMas ? masOptions.type : macOptions.type; const type = explicitType || "distribution"; const isDevelopment = type === "development"; const certificateType = getCertificateType(isMas, isDevelopment); let identity = yield (0, (_codeSign || _load_codeSign()).findIdentity)(certificateType, qualifier, keychainName); if (identity == null) { if (!isMas && !isDevelopment && explicitType !== "distribution") { identity = yield (0, (_codeSign || _load_codeSign()).findIdentity)("Mac Developer", qualifier, keychainName); if (identity != null) { (0, (_builderUtil || _load_builderUtil()).warn)("Mac Developer is used to sign app — it is only for development and testing, not for production"); } } if (identity == null) { yield (0, (_codeSign || _load_codeSign()).reportError)(isMas, certificateType, qualifier, keychainName, _this3.forceCodeSigning); return; } } const signOptions = { "identity-validation": false, // https://github.com/electron-userland/electron-builder/issues/1699 // kext are signed by the chipset manufacturers. You need a special certificate (only available on request) from Apple to be able to sign kext. ignore: function (file) { return file.endsWith(".kext") || file.startsWith("/Contents/PlugIns", appPath.length) || // https://github.com/electron-userland/electron-builder/issues/2010 file.includes("/node_modules/puppeteer/.local-chromium"); }, identity: identity, type, platform: isMas ? "mas" : "darwin", version: _this3.config.electronVersion, app: appPath, keychain: keychainName || undefined, binaries: (isMas && masOptions != null ? masOptions.binaries : macOptions.binaries) || undefined, requirements: isMas || macOptions.requirements == null ? undefined : yield _this3.getResource(macOptions.requirements), "gatekeeper-assess": (_codeSign || _load_codeSign()).appleCertificatePrefixes.find(function (it) { return identity.name.startsWith(it); }) != null }; yield _this3.adjustSignOptions(signOptions, masOptions); yield (0, (_builderUtil || _load_builderUtil()).task)(`Signing app (identity: ${identity.hash} ${identity.name})`, _this3.doSign(signOptions)); // https://github.com/electron-userland/electron-builder/issues/1196#issuecomment-312310209 if (masOptions != null && !isDevelopment) { const certType = isDevelopment ? "Mac Developer" : "3rd Party Mac Developer Installer"; const masInstallerIdentity = yield (0, (_codeSign || _load_codeSign()).findIdentity)(certType, masOptions.identity, keychainName); if (masInstallerIdentity == null) { throw new Error(`Cannot find valid "${certType}" identity to sign MAS installer, please see https://electron.build/code-signing`); } const artifactName = _this3.expandArtifactNamePattern(masOptions, "pkg"); const artifactPath = _path.join(outDir, artifactName); yield _this3.doFlat(appPath, artifactPath, masInstallerIdentity, keychainName); _this3.dispatchArtifactCreated(artifactPath, null, (_builderUtil || _load_builderUtil()).Arch.x64, _this3.computeSafeArtifactName(artifactName, "pkg")); } })(); } adjustSignOptions(signOptions, masOptions) { var _this4 = this; return (0, (_bluebirdLst || _load_bluebirdLst()).coroutine)(function* () { const resourceList = yield _this4.resourceList; if (resourceList.includes(`entitlements.osx.plist`)) { throw new Error("entitlements.osx.plist is deprecated name, please use entitlements.mac.plist"); } if (resourceList.includes(`entitlements.osx.inherit.plist`)) { throw new Error("entitlements.osx.inherit.plist is deprecated name, please use entitlements.mac.inherit.plist"); } const customSignOptions = masOptions || _this4.platformSpecificBuildOptions; const entitlementsSuffix = masOptions == null ? "mac" : "mas"; if (customSignOptions.entitlements == null) { const p = `entitlements.${entitlementsSuffix}.plist`; if (resourceList.includes(p)) { signOptions.entitlements = _path.join(_this4.buildResourcesDir, p); } } else { signOptions.entitlements = customSignOptions.entitlements; } if (customSignOptions.entitlementsInherit == null) { const p = `entitlements.${entitlementsSuffix}.inherit.plist`; if (resourceList.includes(p)) { signOptions["entitlements-inherit"] = _path.join(_this4.buildResourcesDir, p); } } else { signOptions["entitlements-inherit"] = customSignOptions.entitlementsInherit; } })(); } //noinspection JSMethodCanBeStatic doSign(opts) { return (0, (_bluebirdLst || _load_bluebirdLst()).coroutine)(function* () { return (0, (_electronOsxSign || _load_electronOsxSign()).signAsync)(opts); })(); } //noinspection JSMethodCanBeStatic doFlat(appPath, outFile, identity, keychain) { return (0, (_bluebirdLst || _load_bluebirdLst()).coroutine)(function* () { // productbuild doesn't created directory for out file yield (0, (_fsExtraP || _load_fsExtraP()).ensureDir)(_path.dirname(outFile)); const args = (0, (_pkg || _load_pkg()).prepareProductBuildArgs)(identity, keychain); args.push("--component", appPath, "/Applications"); args.push(outFile); return yield (0, (_builderUtil || _load_builderUtil()).exec)("productbuild", args); })(); } getElectronSrcDir(dist) { return _path.resolve(this.projectDir, dist, this.electronDistMacOsAppName); } getElectronDestinationDir(appOutDir) { return _path.join(appOutDir, this.electronDistMacOsAppName); } } exports.default = MacPackager; function getCertificateType(isMas, isDevelopment) { if (isDevelopment) { return "Mac Developer"; } return isMas ? "3rd Party Mac Developer Application" : "Developer ID Application"; } //# sourceMappingURL=macPackager.js.map
/*! * Copyright (c) 2015-2020 Cisco Systems, Inc. See LICENSE file. */ import {EventEmitter} from 'events'; import SCR from 'node-scr'; import {proxyEvents, transferEvents} from '@webex/common'; import {WebexPlugin} from '@webex/webex-core'; import {filter, map, pick, some} from 'lodash'; import {detectFileType, processImage} from '@webex/helper-image'; import sha256 from 'crypto-js/sha256'; export const EMITTER_SYMBOL = Symbol('EMITTER_SYMBOL'); export const FILE_SYMBOL = Symbol('FILE_SYMBOL'); const PROMISE_SYMBOL = Symbol('PROMISE_SYMBOL'); /** * @class */ const ShareActivity = WebexPlugin.extend({ getSymbols() { return { file: FILE_SYMBOL, emitter: EMITTER_SYMBOL }; }, namespace: 'Conversation', derived: { target: { deps: ['conversation'], fn() { return this.conversation; } } }, session: { conversation: { required: true, type: 'object' }, content: 'string', clientTempId: 'string', displayName: 'string', enableThumbnails: { default: true, type: 'boolean' }, hiddenSpaceUrl: 'object', mentions: 'object', spaceUrl: 'object', uploads: { type: 'object', default() { return new Map(); } } }, initialize(attrs, options) { Reflect.apply(WebexPlugin.prototype.initialize, this, [attrs, options]); if (attrs && attrs.conversation) { this.spaceUrl = Promise.resolve(attrs.conversation._spaceUrl || this._retrieveSpaceUrl(`${attrs.conversation.url}/space`) .then((url) => { attrs.conversation._spaceUrl = url; return url; })); this.hiddenSpaceUrl = Promise.resolve(attrs.conversation._hiddenSpaceUrl || this._retrieveSpaceUrl(`${attrs.conversation.url}/space/hidden`) .then((url) => { attrs.conversation._hiddenSpaceUrl = url; return url; })); } }, /** * Adds an additional GIF to the share activity * Different from regular add to skip uploading to webex files service * @param {File} gif * @param {File} gif.image // thumbnail * @param {Object} options * @param {Object} options.actions * @returns {Promise} */ addGif(gif, options) { let gifToAdd = this.uploads.get(gif); // If the gif already exists, then don't do anything if (gifToAdd) { return Promise.resolve(); } gifToAdd = Object.assign({ displayName: gif.name, fileSize: gif.size || gif.byteLength || gif.length, mimeType: gif.type, url: 'https://giphy.com', objectType: 'file', height: gif.height, width: gif.width, image: { height: gif.image.height, width: gif.image.width, url: 'https://giphy.com' }, [FILE_SYMBOL]: gif }, pick(options, 'actions')); this.uploads.set(gif, gifToAdd); /* Instead of encryptBinary, which produces a encrypted version of * the file for upload and a SCR (contains info needed to encrypt the * SCR itself and the displayName), we directly create an SCR. * Because we are skipping uploading, the encrypted file is not needed. */ return SCR.create() .then((scr) => { scr.loc = gif.url; gifToAdd.scr = scr; return SCR.create(); }) .then((thumbnailScr) => { thumbnailScr.loc = gif.image.url; gifToAdd.image.scr = thumbnailScr; }); }, /** * Adds an additional file to the share and begins submitting it to webex * files * @param {File} file * @param {Object} options * @param {Object} options.actions * @returns {EventEmittingPromise} */ add(file, options) { options = options || {}; let upload = this.uploads.get(file); if (upload) { return upload[PROMISE_SYMBOL]; } const emitter = new EventEmitter(); upload = Object.assign({ displayName: file.name, fileSize: file.size || file.byteLength || file.length, mimeType: file.type, objectType: 'file', [EMITTER_SYMBOL]: emitter, [FILE_SYMBOL]: file }, pick(options, 'actions')); this.uploads.set(file, upload); const promise = detectFileType(file, this.logger) .then((type) => { upload.mimeType = type; return processImage({ file, type, thumbnailMaxWidth: this.config.thumbnailMaxWidth, thumbnailMaxHeight: this.config.thumbnailMaxHeight, enableThumbnails: this.enableThumbnails, logger: this.logger }); }) .then((imageData) => { const main = this.webex.internal.encryption.encryptBinary(file) .then(({scr, cdata}) => { upload.scr = scr; return Promise.all([cdata, this.spaceUrl]); }) .then(([cdata, spaceUrl]) => { const uploadPromise = this._upload(cdata, `${spaceUrl}/upload_sessions`); transferEvents('progress', uploadPromise, emitter); return uploadPromise; }) .then((metadata) => { upload.url = upload.scr.loc = metadata.downloadUrl; }); let thumb; if (imageData) { const [thumbnail, fileDimensions, thumbnailDimensions] = imageData; Object.assign(upload, fileDimensions); if (thumbnail && thumbnailDimensions) { upload.image = thumbnailDimensions; thumb = this.webex.internal.encryption.encryptBinary(thumbnail) .then(({scr, cdata}) => { upload.image.scr = scr; return Promise.all([cdata, this.hiddenSpaceUrl]); }) .then(([cdata, spaceUrl]) => this._upload(cdata, `${spaceUrl}/upload_sessions`)) .then((metadata) => { upload.image.url = upload.image.scr.loc = metadata.downloadUrl; }); } } return Promise.all([main, thumb]); }); upload[PROMISE_SYMBOL] = promise; proxyEvents(emitter, promise); return promise; }, /** * Fetches the files from the share * @returns {Array} */ getFiles() { const files = []; for (const [key] of this.uploads) { files.push(this.uploads.get(key)[FILE_SYMBOL]); } return files; }, /** * @param {File} file * @param {string} uri * @private * @returns {Promise} */ _upload(file, uri) { const fileSize = file.length || file.size || file.byteLength; const fileHash = sha256(file).toString(); return this.webex.upload({ uri, file, qs: { transcode: true }, phases: { initialize: {fileSize}, upload: { $url(session) { return session.uploadUrl; } }, finalize: { $uri(session) { return session.finishUploadUrl; }, body: {fileSize, fileHash} } } }); }, /** * Removes the specified file from the share (Does not currently delete the * uploaded file) * @param {File} file * @returns {Promise} */ remove(file) { this.uploads.delete(file); // Returns a promise for future-proofiness. return Promise.resolve(); }, /** * @private * @returns {Promise<Object>} */ prepare() { if (!this.uploads.size) { throw new Error('Cannot submit a share activity without atleast one file'); } const activity = { verb: 'share', object: { objectType: 'content', displayName: this.object && this.object.displayName ? this.object.displayName : undefined, content: this.object && this.object.content ? this.object.content : undefined, mentions: this.object && this.object.mentions ? this.object.mentions : undefined, files: { items: [] } }, clientTempId: this.clientTempId }; const promises = []; this.uploads.forEach((item) => { activity.object.files.items.push(item); promises.push(item[PROMISE_SYMBOL]); }); activity.object.contentCategory = this._determineContentCategory(activity.object.files.items); return Promise.all(promises) .then(() => activity); }, /** * @param {Array} items * @param {string} mimeType * @private * @returns {boolean} */ _itemContainsActionWithMimeType(items, mimeType) { return some(items.map((item) => some(item.actions, {mimeType}))); }, /** * @param {Array} items * @private * @returns {string} */ _determineContentCategory(items) { // determine if the items contain an image if (this._itemContainsActionWithMimeType(items, 'application/x-cisco-webex-whiteboard')) { return 'documents'; } const mimeTypes = filter(map(items, 'mimeType')); if (mimeTypes.length !== items.length) { return 'documents'; } const contentCategory = mimeTypes[0].split('/').shift(); if (contentCategory !== 'video' && contentCategory !== 'image') { return 'documents'; } for (const mimeType of mimeTypes) { if (mimeType.split('/').shift() !== contentCategory) { return 'documents'; } } return `${contentCategory}s`; }, /** * @param {string} uri * @returns {Promise} */ _retrieveSpaceUrl(uri) { return this.webex.request({ method: 'PUT', uri }) .then((res) => res.body.spaceUrl); } }); /** * Instantiates a ShareActivity * @param {Object} conversation * @param {ShareActivity|Object|array} object * @param {ProxyWebex} webex * @returns {ShareActivity} */ ShareActivity.create = function create(conversation, object, webex) { if (object instanceof ShareActivity) { return object; } let files; if (object && object.object && object.object.files) { files = object.object.files; Reflect.deleteProperty(object.object, 'files'); } const share = new ShareActivity(Object.assign({ conversation }, object), { parent: webex }); files = files && files.items || files; if (files) { files.forEach((file) => share.add(file)); } return share; }; export default ShareActivity;
var pronto = require('../pronto'); var BufferedReader = require('../streams/bufferedreader'); /** * Buffer the input stream of a request. * * This allows the incomming HTTP body to be buffered until it is later * needed.This is very useful in cases where other longish transactions * (like database queries) must happen before input is used. * * This puts a streams.BufferedReader into the context. * * IMPORTANT: The returned stream will be paused. Use BufferedReader.open() * or BufferedReader.resume() to start emitting data from the stream. * * IMPORTANT: Large uploads plus long delays will result in larger consumption * of system resources (e.g. memory). * * Params * * - stream: The stream to buffer. If not supplied, the request is * buffered. (OPTIONAL) */ function BufferRequest(){} pronto.inheritsCommand(BufferRequest); module.exports = BufferRequest; BufferRequest.prototype.execute = function(cxt, params) { var source = params.stream || cxt.getDatasource('request'); var dest = new BufferedReader(source); this.done(dest); }
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var ClickCounter = exports.ClickCounter = function () { function ClickCounter() { _classCallCheck(this, ClickCounter); this.count = 0; } ClickCounter.prototype.increment = function increment() { this.count++; }; return ClickCounter; }();
"use strict"; module.exports = require("@jsdevtools/eslint-config-modular/browser");
'use babel' export default ` div(class="section-container user-support-helper") div.container div.row span(class="text-right close-icon", href="#") div(class="row content") `
//Configuration var express = require('express'); var app = express(); var mongo = require('mongodb').MongoClient; var url = 'mongodb://localhost:27017/tutorial'; var passport = require("passport"); app.use(express.static(__dirname + "/public")); var path = require('path'); var multer = require('multer') //Router var router = express.Router(); //Schemas var User = require('../../app/models/user'); var Portfolio = require('../../app/models/portoflio'); var Work = require('../../app/models/work'); //Controllers var registerController = require('./controllers/registerController'); var portfolioController = require('./controllers/portfolioController'); var userController = require('./controllers/userController'); var workController = require('./controllers/workController'); // multer Storage Configuration const storage = multer.diskStorage({ destination: function(req, file, cb) { cb(null, 'public/uploads/'); }, filename: function(req, file, cb) { cb(null, Date.now() + path.extname(file.originalname)); } }); //Multer Upload Configuraton const upload = multer({ storage: storage, fileFilter: function(req, file, callback) { var ext = path.extname(file.originalname); if (ext !== '.png' && ext !== '.jpg' && ext !== '.gif' && ext !== '.jpeg') { return callback(new Error('Only images are allowed')) } callback(null, true) } }); //Main Router module.exports = function(router) { function ensureAuthenticated(req, res, next) { if (req.isAuthenticated()) { next(); } else { req.flash("info", "You must be logged in to see this page."); res.redirect("/login"); } }; router.use(function(req, res, next) { res.locals.currentUser = req.user; res.locals.errors = req.flash("error"); res.locals.infos = req.flash("info"); //console.log(req.user); next(); }); //Portfolio Requests router.get( '/viewall',portfolioController.viewPortfolios); router.post('/addportfolio', upload.single('pp'), portfolioController.addPortfolio); router.get('/addportfolio', ensureAuthenticated, portfolioController.makePortfolio); //Work Requests router.get('/delete/:_id',workController.deleteWork); router.post('/update', workController.updateWork); router.post('/ppupdate', upload.single('pp'), workController.updateProfilePicture); router.post('/ppdelete',workController.deleteProfilePicture); router.post('/addwork', upload.single("image"), ensureAuthenticated, workController.addWork); //Register Requests router.get('/register', registerController.getRegister); router.post('/register', registerController.Register); //User Requests router.get('/', userController.home); router.get('/viewyw', ensureAuthenticated, userController.viewYourWork); router.get('/addwork', ensureAuthenticated, userController.addWork); router.get('/about',userController.about); router.get('/viewwork/:username', userController.viewOnesWork); router.get('/login', userController.login); router.get('/logout',userController.logout); router.post("/login",userController.passportAuth); //Any Other routes router.get("*",userController.home); //Returning Router return router; }
function incrementCounter(id, step) { return { type: 'INCREMENT_COUNTER', id, step } } function decrementCounter(id, step) { return { type: 'DECREMENT_COUNTER', id, step } } function addCounter(id, label, step) { return { type: 'ADD_COUNTER', label, step, id } } function removeCounter(id) { return { type: 'REMOVE_COUNTER', id } } function updateCounter(id, label, step, value) { return { type: 'UPDATE_COUNTER', id, label, step, value } } export { incrementCounter, decrementCounter, addCounter, removeCounter, updateCounter };
import React from 'react' import { Checkbox } from 'material-ui'; export default class MultipleCheckboxes extends React.Component { constructor(props) { super(props); this.shouldComponentUpdate = this.shouldComponentUpdate.bind(this); } shouldComponentUpdate(nextProps) { if(nextProps.values.length !== this.props.values.length) { return true; } else { return nextProps.values.length && nextProps.values.every((v,i)=> v !== this.props.values[i]); } } render = () => { return ( <div>{this.props.specialNeeds.map((sn, index) => { return ( <div key={index} class="col-md-6"> <Checkbox label={sn.name} defaultChecked={this.props.values.indexOf(sn.name) > -1} onCheck={() => {this.props.handleCheckboxGroup(sn.name)}} /> </div> )})} </div>); } }
/* eslint-disable import/prefer-default-export */ export const sum = (data, columns) => { const defaultValue = 0; return data.reduce((previous, current) => { return columns .map(c => ({ [c]: (previous[c] || defaultValue) + (current[c] || defaultValue) })) .reduce((a, b) => Object.assign({}, a, b), {}); }, {}); };
//= link_directory ../javascripts/redirectr .js //= link_directory ../stylesheets/redirectr .css
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ // THIS CODE IS GENERATED - DO NOT MODIFY // See angular/tools/gulp-tasks/cldr/extract.js (function(global) { global.ng = global.ng || {}; global.ng.common = global.ng.common || {}; global.ng.common.locales = global.ng.common.locales || {}; var u = undefined; function plural(n) { if (n === 1) return 1; return 5; } global.ng.common.locales['nyn'] = [ 'nyn', [['AM', 'PM'], u, u], u, [ ['S', 'K', 'R', 'S', 'N', 'T', 'M'], ['SAN', 'ORK', 'OKB', 'OKS', 'OKN', 'OKT', 'OMK'], [ 'Sande', 'Orwokubanza', 'Orwakabiri', 'Orwakashatu', 'Orwakana', 'Orwakataano', 'Orwamukaaga' ], ['SAN', 'ORK', 'OKB', 'OKS', 'OKN', 'OKT', 'OMK'] ], u, [ ['J', 'F', 'M', 'A', 'M', 'J', 'J', 'A', 'S', 'O', 'N', 'D'], ['KBZ', 'KBR', 'KST', 'KKN', 'KTN', 'KMK', 'KMS', 'KMN', 'KMW', 'KKM', 'KNK', 'KNB'], [ 'Okwokubanza', 'Okwakabiri', 'Okwakashatu', 'Okwakana', 'Okwakataana', 'Okwamukaaga', 'Okwamushanju', 'Okwamunaana', 'Okwamwenda', 'Okwaikumi', 'Okwaikumi na kumwe', 'Okwaikumi na ibiri' ] ], u, [['BC', 'AD'], u, ['Kurisito Atakaijire', 'Kurisito Yaijire']], 1, [0, 0], ['dd/MM/y', 'd MMM y', 'd MMMM y', 'EEEE, d MMMM y'], ['HH:mm', 'HH:mm:ss', 'HH:mm:ss z', 'HH:mm:ss zzzz'], ['{1} {0}', u, u, u], ['.', ',', ';', '%', '+', '-', 'E', '×', '‰', '∞', 'NaN', ':'], ['#,##0.###', '#,##0%', '¤#,##0.00', '#E0'], 'UGX', 'USh', 'Eshiringi ya Uganda', {'JPY': ['JP¥', '¥'], 'UGX': ['USh'], 'USD': ['US$', '$']}, 'ltr', plural, [] ]; })(typeof globalThis !== 'undefined' && globalThis || typeof global !== 'undefined' && global || typeof window !== 'undefined' && window);
var util = require('util'), Store = require('../base'), _ = require('lodash'), debug = require('debug')('saga:mongodb'), ConcurrencyError = require('../../errors/concurrencyError'), mongo = Store.use('mongodb'), mongoVersion = Store.use('mongodb/package.json').version, isNew = mongoVersion.indexOf('1.') !== 0, isNew = mongoVersion.indexOf('1.') !== 0, ObjectID = isNew ? mongo.ObjectID : mongo.BSONPure.ObjectID; function Mongo(options) { Store.call(this, options); var defaults = { host: 'localhost', port: 27017, dbName: 'domain', collectionName: 'saga'//, // heartbeat: 60 * 1000 }; _.defaults(options, defaults); var defaultOpt = { ssl: false }; options.options = options.options || {}; if (isNew) { defaultOpt.autoReconnect = false; defaultOpt.useNewUrlParser = true; defaultOpt.useUnifiedTopology = true; _.defaults(options.options, defaultOpt); } else { defaultOpt.auto_reconnect = false; _.defaults(options.options, defaultOpt); } this.options = options; } util.inherits(Mongo, Store); _.extend(Mongo.prototype, { connect: function (callback) { var self = this; var options = this.options; var connectionUrl; if (options.url) { connectionUrl = options.url; } else { var members = options.servers ? options.servers : [{host: options.host, port: options.port}]; var memberString = _(members).map(function(m) { return m.host + ':' + m.port; }); var authString = options.username && options.password ? options.username + ':' + options.password + '@' : ''; var optionsString = options.authSource ? '?authSource=' + options.authSource : ''; connectionUrl = 'mongodb://' + authString + memberString + '/' + options.dbName + optionsString; } var client; if (mongo.MongoClient.length === 2) { client = new mongo.MongoClient(connectionUrl, options.options); client.connect(function(err, cl) { if (err) { debug(err); if (callback) callback(err); return; } self.db = cl.db(cl.s.options.dbName); if (!self.db.close) { self.db.close = cl.close.bind(cl); } initDb(); }); } else { client = new mongo.MongoClient(); client.connect(connectionUrl, options.options, function(err, db) { if (err) { debug(err); if (callback) callback(err); return; } self.db = db; initDb(); }); } function initDb() { self.db.on('close', function() { self.emit('disconnect'); self.stopHeartbeat(); }); var finish = function (err) { self.store = self.db.collection(options.collectionName); self.store.createIndex({ '_commands.id': 1}, function() {}); self.store.createIndex({ '_timeoutAt': 1}, function() {}); self.store.createIndex({ '_commitStamp': 1}, function() {}); if (!err) { self.emit('connect'); if (self.options.heartbeat) { self.startHeartbeat(); } } if (callback) callback(err, self); }; finish(); } }, stopHeartbeat: function () { if (this.heartbeatInterval) { clearInterval(this.heartbeatInterval); delete this.heartbeatInterval; } }, startHeartbeat: function () { var self = this; var gracePeriod = Math.round(this.options.heartbeat / 2); this.heartbeatInterval = setInterval(function () { var graceTimer = setTimeout(function () { if (self.heartbeatInterval) { console.error((new Error ('Heartbeat timeouted after ' + gracePeriod + 'ms (mongodb)')).stack); self.disconnect(); } }, gracePeriod); self.db.command({ ping: 1 }, function (err) { if (graceTimer) clearTimeout(graceTimer); if (err) { console.error(err.stack || err); self.disconnect(); } }); }, this.options.heartbeat); }, disconnect: function (callback) { this.stopHeartbeat(); if (!this.db) { if (callback) callback(null); return; } this.db.close(callback || function () {}); }, getNewId: function(callback) { callback(null, new ObjectID().toString()); }, save: function (saga, cmds, callback) { if (!saga || !_.isObject(saga) || !_.isString(saga.id) || !_.isDate(saga._commitStamp)) { var err = new Error('Please pass a valid saga!'); debug(err); return callback(err); } if (!cmds || !_.isArray(cmds)) { var err = new Error('Please pass a valid saga!'); debug(err); return callback(err); } if (cmds.length > 0) { for (var c in cmds) { var cmd = cmds[c]; if (!cmd.id || !_.isString(cmd.id) || !cmd.payload) { var err = new Error('Please pass a valid commands array!'); debug(err); return callback(err); } } } saga._id = saga.id; saga._commands = cmds; if (!saga._hash) { saga._hash = new ObjectID().toString(); this.store.insertOne(saga, { safe: true, w: 1 }, function (err) { if (err && err.message && err.message.indexOf('duplicate key') >= 0) { return callback(new ConcurrencyError()); } if (callback) { callback(err); } }); } else { var currentHash = saga._hash; saga._hash = new ObjectID().toString(); this.store.updateOne({ _id: saga._id, _hash: currentHash }, { $set: saga }, { safe: true }, function(err, modifiedCount) { if (isNew) { if (modifiedCount && modifiedCount.result && modifiedCount.result.n === 0) { return callback(new ConcurrencyError()); } } else { if (modifiedCount === 0) { return callback(new ConcurrencyError()); } } if (callback) { callback(err); } }); } }, get: function (id, callback) { if (!id || !_.isString(id)) { var err = new Error('Please pass a valid id!'); debug(err); return callback(err); } this.store.findOne({ _id: id }, function (err, saga) { if (err) { return callback(err); } if (!saga) { return callback(null, null); } if (saga._commands) { delete saga._commands; } callback(null, saga); }); }, remove: function (id, callback) { if (!id || !_.isString(id)) { var err = new Error('Please pass a valid id!'); debug(err); return callback(err); } this.store.deleteOne({ _id: id }, { safe: true, w: 1 }, function (err) { if (callback) callback(err); }); }, getTimeoutedSagas: function (options, callback) { if (!callback) { callback = options; options = {}; } options = options || {}; // options.limit = options.limit || -1; // options.skip = options.skip || 0; options.sort = [['_timeoutAt', 'asc']]; this.store.find({ _timeoutAt: { '$lte': new Date() } }, options).toArray(function (err, sagas) { if (err) { return callback(err); } sagas.forEach(function (s) { if (s._commands) { delete s._commands; } }); callback(null, sagas); }); }, getOlderSagas: function (date, callback) { if (!date || !_.isDate(date)) { var err = new Error('Please pass a valid date object!'); debug(err); return callback(err); } this.store.find({ _commitStamp: { '$lte': date } }).toArray(function (err, sagas) { if (err) { return callback(err); } sagas.forEach(function (s) { if (s._commands) { delete s._commands; } }); callback(null, sagas); }); }, getUndispatchedCommands: function (options, callback) { if (!callback) { callback = options; options = {}; } options = options || {}; // options.limit = options.limit || -1; // options.skip = options.skip || 0; options.sort = [['_commitStamp', 'asc']]; var res = []; this.store.find({ '_commands.0': {$exists: true} }, options).toArray(function (err, sagas) { if (err) { return callback(err); } sagas.forEach(function (s) { if (s._commands && s._commands.length > 0) { s._commands.forEach(function (c) { res.push({ sagaId: s._id, commandId: c.id, command: c.payload, commitStamp: s._commitStamp }); }); } }); callback(null, res); }); }, setCommandToDispatched: function (cmdId, sagaId, callback) { if (!cmdId || !_.isString(cmdId)) { var err = new Error('Please pass a valid command id!'); debug(err); return callback(err); } if (!sagaId || !_.isString(sagaId)) { var err = new Error('Please pass a valid saga id!'); debug(err); return callback(err); } this.store.updateOne({ _id: sagaId, '_commands.id': cmdId }, { $pull: { '_commands': { id: cmdId } } }, { safe: true }, function (err) { if (callback) callback(err); }); }, clear: function (callback) { this.store.deleteMany({}, { safe: true }, callback); } }); module.exports = Mongo;
version https://git-lfs.github.com/spec/v1 oid sha256:839b318c8e34c567859b2d96a43b8729872fbbaf0bd0e5c50c1431777bfe16eb size 882
// // * Input-File for TJ-K axisymmetric solovev equilibrium * // Iconst without X-point, elong AUG, Te_10eV,B0_0.07T,deuterium,Cref_1e-5 // ----------------------------------------------------------- { "A" : 0, "R_0" : 91.884233908188605, "alpha" : 0.02, "c" : [ 0.58136855188608583, 9.2360756664978574, -9.1888338426687337, -4.1872227595243885, 6.544638217090343, -5.7648048417281998, -0.23576721602133818, 1.3692553155542757, 6.3214049719456709, -3.9167432232703687, -0.97303855303064757, 0.10615175705576452 ], "elongation" : 1.7, "equilibrium" : "solovev", "inverseaspectratio" : 0.16666666666666669, "psip_max" : 0, "psip_max_cut" : 10000000000, "psip_max_lim" : 10000000000, "psip_min" : -6, "qampl" : 1, "rk4eps" : 0.0001, "triangularity" : 0.33000000000000002 }
"use babel"; import gitCmd from "../git-cmd"; import Notifications from "../Notifications"; import { command as pull } from "./pull"; import { command as push } from "./push"; export default { label: "Sync", description: "Pull then push from upstream", confirm: { message: "Are you sure you want to sync with upstream?" }, async command(filePaths, statusBar, git = gitCmd, notifications = Notifications, title = "Sync") { await pull(filePaths, statusBar, git, notifications); await push(filePaths, statusBar, git, notifications); return { title, message: "Synced", }; }, };
const fs = require('fs'); module.exports = function (result) { const stat = fs.statSync(result.name); if (stat.isFile()) { // TODO must also close the file, otherwise the file will be closed during garbage collection, which we do not want // TODO #241 get rid of the open file descriptor fs.unlinkSync(result.name); } else { fs.rmdirSync(result.name); } this.out(result.name); };
var searchData= [ ['inend',['InEnd',['../namespace_politechnikon_1_1game__logic.html#aa4499f0ebdf2f28e13e5b9e811fe00b4ae51bbf445c6eac27c2d5e106b3680ff4',1,'Politechnikon::game_logic']]], ['ingame',['InGame',['../namespace_politechnikon_1_1game__logic.html#aa4499f0ebdf2f28e13e5b9e811fe00b4a7f3d370e94c8b1fea09838572013d8ec',1,'Politechnikon::game_logic']]], ['inhighscore',['InHighScore',['../namespace_politechnikon_1_1game__logic.html#aa4499f0ebdf2f28e13e5b9e811fe00b4a2223ad10744ae2620d561ce5ae3db324',1,'Politechnikon::game_logic']]], ['inload',['InLoad',['../namespace_politechnikon_1_1game__logic.html#aa4499f0ebdf2f28e13e5b9e811fe00b4a877071ae821fb64531dc6889de1b65c5',1,'Politechnikon::game_logic']]], ['inmenu',['InMenu',['../namespace_politechnikon_1_1game__logic.html#aa4499f0ebdf2f28e13e5b9e811fe00b4aed2dc8c66bc8fbf1126273f63f522abc',1,'Politechnikon::game_logic']]], ['innewgame',['InNewGame',['../namespace_politechnikon_1_1game__logic.html#aa4499f0ebdf2f28e13e5b9e811fe00b4ad31dd43b9cc6e55def022a5fedb739b7',1,'Politechnikon::game_logic']]], ['insave',['InSave',['../namespace_politechnikon_1_1game__logic.html#aa4499f0ebdf2f28e13e5b9e811fe00b4aea53f4f7aaeacd8ab3c746f58cb86f5c',1,'Politechnikon::game_logic']]], ['instant',['Instant',['../namespace_politechnikon_1_1engine.html#aecee13d8f9ccbd026b65aa07def91875a54828f327f31abd59f2f459c0247756d',1,'Politechnikon::engine']]], ['interfaceobjects',['InterfaceObjects',['../namespace_politechnikon_1_1game__logic.html#aeedaa2e4120b08694bd26251749c5435a17ec5e54d3eb16f1c9ed88eed089f864',1,'Politechnikon::game_logic']]] ];
import { flip, concat, propEq } from 'ramda' // // Action creators // const suffix = flip(concat) export const requestTypeFor = suffix('_REQUEST') export const receiveTypeFor = suffix('_RECEIVE') export const errorTypeFor = suffix('_ERROR') export const ApiCallType = { REQUEST: 'REQUEST', RECEIVE: 'RECEIVE', ERROR: 'ERROR' } const actionCreator = (callType, typeFn) => action => ({ originType: action.type, type: typeFn(action.type), apiCallType: callType, path: action.dataApiCall.path }) export const onRequestActionCreator = actionCreator(ApiCallType.REQUEST, requestTypeFor) export const onReceiveActionCreator = action => data => ({ ...actionCreator(ApiCallType.RECEIVE, receiveTypeFor)(action), data }) export const onErrorActionCreator = action => error => ({ ...actionCreator(ApiCallType.ERROR, errorTypeFor)(action), error }) /** Gets the "call" object from an action, populating the token if necesary */ export const callFromAction = (store, action) => { // TODO: this should be an optional "middleware" const call = action.dataApiCall if (call.requiresAuthentication) { call.token = getAuthToken(store.getState()) } return call } // HARDCODED: coupled with our app. This is the only point to become // apiCalls an external library const getAuthToken = state => (state.login ? state.login.token : undefined) export const simulateDataReceive = (action, data) => onReceiveActionCreator(action)(data) // // Checking // export const isApiCall = action => action.dataApiCall export const isDerivedActionFor = (action, apiActionType) => action.originType === apiActionType const isApiCallOfType = propEq('apiCallType') export const isRequest = isApiCallOfType(ApiCallType.REQUEST) export const isReceive = isApiCallOfType(ApiCallType.RECEIVE) export const isError = isApiCallOfType(ApiCallType.ERROR)
// // Lansite Client RequestBox // By Tanner Krewson // BoxNames.push('RequestBox'); RequestBox.prototype = Object.create(Box.prototype); function RequestBox(data) { Box.call(this, data.id, data.unique); this.updateData(data); } //@Override RequestBox.prototype.updateData = function(data) { this.text = data.text; } //@Override RequestBox.prototype.show = function() { //Runs the parent show function Box.prototype.show.call(this); //Place any custom code here var thisBox = $('#' + this.unique); //change the text thisBox.find('.requesttext').text(this.text); var acceptButton = thisBox.find('.requestaccept'); var denyButton = thisBox.find('.requestdeny'); var self = this; //when the button is clicked acceptButton.on('click', function(event) { self.handleRequest(true); }); denyButton.on('click', function(event) { self.handleRequest(false); }); } RequestBox.prototype.handleRequest = function(wasAccepted) { SendToServer.eventFromIndBox(this.unique, 'handle', { 'unique': this.unique, 'wasAccepted': wasAccepted }); } //@Override RequestBox.prototype.update = function() { //Runs the parent update function Box.prototype.update.call(this); //Place any custom code here } RequestBox.addButtons = function(sidebar) { //sidebar.addButton(new Button('RequestBox', 'Do Something')); } /* You may send information to the server using the SendToServer object, like so: SendToServer.eventFromIndBox(boxUnique, eventName, data); SendToServer.request(requestName, data); */
/* * Test case runner. Supports both ECMAScript tests and Duktape API * C tests. Duktape API C tests are compiled on-the-fly against a * dynamic or static library. * * Error handling is currently not correct throughout. */ var fs = require('fs'), path = require('path'), tmp = require('tmp'), child_process = require('child_process'), async = require('async'), xml2js = require('xml2js'), md5 = require('MD5'), yaml = require('yamljs'); var TIMEOUT_SLOW_VALGRIND = 4 * 3600 * 1000; var TIMEOUT_SLOW = 3600 * 1000; var TIMEOUT_NORMAL_VALGRIND = 3600 * 1000; var TIMEOUT_NORMAL = 600 * 1000; // Global options from command line var optPythonCommand; var optPrepTestPath; var optMinifyClosure; var optMinifyUglifyJS; var optMinifyUglifyJS2; var optUtilIncludePath; var optEmdukTrailingLineHack; var knownIssues; /* * Utils. */ // Generate temporary filename, file will be autodeleted on exit unless // deleted explicitly. See: https://www.npmjs.com/package/tmp function mkTempName(ext) { var fn = tmp.tmpNameSync({ keep: false, prefix: 'tmp-runtests-', postfix: (typeof ext === 'undefined' ? '' : '' + ext) }); //console.log('mkTempName -> ' + fn); return fn; } function safeUnlinkSync(filePath) { try { if (filePath) { fs.unlinkSync(filePath); } } catch (e) { console.log('Failed to unlink ' + filePath + ' (ignoring): ' + e); } } function safeReadFileSync(filePath, encoding) { try { if (!filePath) { return; } return fs.readFileSync(filePath, encoding); } catch (e) { console.log('Failed to read ' + filePath + ' (ignoring): ' + e); } } function diffText(text1, text2, callback) { var tmp1 = mkTempName(); var tmp2 = mkTempName(); var cmd; fs.writeFileSync(tmp1, text1); fs.writeFileSync(tmp2, text2); cmd = [ 'diff', '-u', tmp1, tmp2 ]; child = child_process.exec(cmd.join(' '), function diffDone(error, stdout, stderr) { safeUnlinkSync(tmp1); safeUnlinkSync(tmp2); callback(null, stdout); }); } /* * Parse a testcase file. */ function parseTestCaseSync(filePath) { var text = fs.readFileSync(filePath, 'utf-8'); var pos, i1, i2; var meta = {}; var tmp; var expect = ''; i1 = text.indexOf('/*---'); i2 = text.indexOf('---*/'); if (i1 >= 0 && i2 >= 0 && i2 >= i1) { meta = JSON.parse(text.substring(i1 + 5, i2)); } pos = 0; for (;;) { i1 = text.indexOf('/*===', pos); i2 = text.indexOf('===*/', pos); if (i1 >= 0 && i2 >= 0 && i2 >= i1) { pos = i2 + 5; tmp = text.substring(i1 + 5, i2).split('\n').slice(1, -1); // ignore first and last line expect += tmp.map(function (x) { return x + '\n'; }).join(''); } else { break; } } return { filePath: filePath, name: path.basename(filePath, '.js'), fileName: path.basename(filePath), meta: meta, expect: expect, expect_md5: md5(expect) }; } function addKnownIssueMetadata(testcase) { if (!knownIssues) { return; } knownIssues.forEach(function (v) { if (v.test !== testcase.fileName) { return; } testcase.meta = testcase.meta || {}; if (v.knownissue) { testcase.meta.knownissue = v.knownissue; // XXX: merge multiple } if (v.specialoptions) { testcase.meta.specialoptions = v.specialoptions; // XXX: merge multiple } }); } /* * Execute a testcase with a certain engine, with optional valgrinding. */ function executeTest(options, callback) { var child; var cmd, cmdline; var execopts; var tempPrologue, tempInput, tempVgxml, tempVgout; var tempSource, tempExe; var timeout; // testcase execution done function execDone(error, stdout, stderr) { var res; // Emduk outputs an extra '\x20\0a' to end of stdout, strip it if (optEmdukTrailingLineHack && typeof stdout === 'string' && stdout.length >= 2 && stdout.substring(stdout.length - 2) === ' \n') { stdout = stdout.substring(0, stdout.length - 2); } res = { testcase: options.testcase, engine: options.engine, error: error, stdout: stdout || '', stderr: stderr || '', cmdline: cmdline, execopts: execopts }; res.valgrind_xml = safeReadFileSync(tempVgxml, 'utf-8'); res.valgrind_out = safeReadFileSync(tempVgout, 'utf-8'); safeUnlinkSync(tempPrologue); safeUnlinkSync(tempInput); safeUnlinkSync(tempVgxml); safeUnlinkSync(tempVgout); safeUnlinkSync(tempSource); safeUnlinkSync(tempExe); if (res.valgrind_xml && res.valgrind_xml.substring(0, 5) === '<?xml' && res.valgrind_xml.indexOf('</valgrindoutput>') > 0) { /* FIXME: Xml2js seems to not throw an error nor call the callback * in some cases (e.g. when a child is killed and xml output is * incomplete). So, use a simple pre-check to guard against parsing * trivially broken XML. */ try { xml2js.parseString(res.valgrind_xml, function (err, result) { if (err) { console.log(err); } else { res.valgrind_root = result; res.valgring_json = JSON.stringify(result); } callback(null, res); }); } catch (e) { console.log('xml2js parsing failed, should not happen: ' + e); callback(null, res); } } else { callback(null, res); } } // testcase compilation done (only relevant for API tests), ready to execute function compileDone(error, stdout, stderr) { /* FIXME: use child_process.spawn(); we don't currently escape command * line parameters which is risky. */ if (error) { console.log(error); execDone(error); return; } cmd = []; if (options.valgrind) { tempVgxml = mkTempName(); tempVgout = mkTempName(); cmd = cmd.concat([ 'valgrind', '--tool=memcheck', '--xml=yes', '--xml-file=' + tempVgxml, '--log-file=' + tempVgout, '--child-silent-after-fork=yes', '-q' ]); } if (tempExe) { cmd.push(tempExe); } else { cmd.push(options.engine.fullPath); if (!options.valgrind && options.engine.name === 'duk') { // cmd.push('--restrict-memory'); // restricted memory } // cmd.push('--alloc-logging'); // cmd.push('--alloc-torture'); // cmd.push('--alloc-hybrid'); cmd.push(tempInput || options.testPath); } cmdline = cmd.join(' '); if (options.notimeout) { timeout = undefined; } else if (options.testcase.meta.slow) { timeout = options.valgrind ? TIMEOUT_SLOW_VALGRIND : TIMEOUT_SLOW; } else { timeout = options.valgrind ? TIMEOUT_NORMAL_VALGRIND : TIMEOUT_NORMAL; } execopts = { maxBuffer: 128 * 1024 * 1024, timeout: timeout, stdio: 'pipe', killSignal: 'SIGKILL' }; //console.log(cmdline); child = child_process.exec(cmdline, execopts, execDone); } function compileApiTest() { tempSource = mkTempName('.c'); try { fs.writeFileSync(tempSource, options.engine.cPrefix + fs.readFileSync(options.testPath)); } catch (e) { console.log(e); callback(e); return; } tempExe = mkTempName(); // FIXME: listing specific options here is awkward, must match Makefile cmd = [ 'gcc', '-o', tempExe, '-Lbuild', '-Iprep/nondebug', // this particularly is awkward '-Wl,-rpath,.', '-pedantic', '-ansi', '-std=c99', '-Wall', '-Wdeclaration-after-statement', '-fstrict-aliasing', '-D_POSIX_C_SOURCE=200809L', '-D_GNU_SOURCE', '-D_XOPEN_SOURCE', '-Os', '-fomit-frame-pointer', '-g', '-ggdb', //'-Werror', // Would be nice but GCC differences break tests too easily //'-m32', 'runtests/api_testcase_main.c', tempSource, '-lduktape', //'-lduktaped', '-lm' ]; if (options.testcase.meta.pthread) { cmd.push('-lpthread'); } cmdline = cmd.join(' '); execopts = { maxBuffer: 128 * 1024 * 1024, timeout: timeout, stdio: 'pipe', killSignal: 'SIGKILL' }; console.log(options.testPath, cmdline); child = child_process.exec(cmdline, execopts, compileDone); } function prepareEcmaTest() { tempPrologue = mkTempName(); tempInput = mkTempName(); try { // The prefix is written to a temp file each time in case it needs // to be dynamic later (e.g. include test case or execution context info). fs.writeFileSync(tempPrologue, options.engine.jsPrefix || '/* no prefix */'); } catch (e) { console.log(e); callback(e); return; } var args = []; args.push(optPrepTestPath) if (optMinifyClosure) { args.push('--minify-closure', optMinifyClosure); } if (optMinifyUglifyJS) { args.push('--minify-uglifyjs', optMinifyUglifyJS); } if (optMinifyUglifyJS2) { args.push('--minify-uglifyjs2', optMinifyUglifyJS2) } args.push('--util-include-path', optUtilIncludePath) args.push('--input', options.testPath) args.push('--output', tempInput) args.push('--prologue', tempPrologue) child_process.execFile(optPythonCommand, args, {}, compileDone) } if (options.engine.name === 'api') { compileApiTest(); } else { prepareEcmaTest(); } } /* * Main */ /* The engine specific headers should not have a newline, to avoid * affecting line numbers in errors / tracebacks. */ var DUK_HEADER = "this.__engine__ = 'duk'; "; // Note: Array.prototype.map() is required to support 'this' binding // other than an array (arguments object here). var NODEJS_HEADER = "this.__engine__ = 'v8'; " + "function print() {" + " var tmp = Array.prototype.map.call(arguments, function (x) { return String(x); });" + " var msg = tmp.join(' ') + '\\n';" + " process.stdout.write(msg);" + " } "; var RHINO_HEADER = "this.__engine__ = 'rhino'; "; var SMJS_HEADER = "this.__engine__ = 'smjs'; "; var API_TEST_HEADER = "#include <stdio.h>\n" + "#include <stdlib.h>\n" + "#include <string.h>\n" + "#include <math.h>\n" + "#include <limits.h> /* INT_MIN, INT_MAX */\n" + "#include \"duktape.h\"\n" + "\n" + "#define TEST_SAFE_CALL(func) do { \\\n" + "\t\tduk_ret_t _rc; \\\n" + "\t\tprintf(\"*** %s (duk_safe_call)\\n\", #func); \\\n" + "\t\tfflush(stdout); \\\n" + "\t\t_rc = duk_safe_call(ctx, (func), NULL, 0 /*nargs*/, 1 /*nrets*/); \\\n" + "\t\tprintf(\"==> rc=%d, result='%s'\\n\", (int) _rc, duk_safe_to_string(ctx, -1)); \\\n" + "\t\tfflush(stdout); \\\n" + "\t\tduk_pop(ctx); \\\n" + "\t} while (0)\n" + "\n" + "#define TEST_PCALL(func) do { \\\n" + "\t\tduk_ret_t _rc; \\\n" + "\t\tprintf(\"*** %s (duk_pcall)\\n\", #func); \\\n" + "\t\tfflush(stdout); \\\n" + "\t\tduk_push_c_function(ctx, (func), 0); \\\n" + "\t\t_rc = duk_pcall(ctx, 0); \\\n" + "\t\tprintf(\"==> rc=%d, result='%s'\\n\", (int) _rc, duk_safe_to_string(ctx, -1)); \\\n" + "\t\tfflush(stdout); \\\n" + "\t\tduk_pop(ctx); \\\n" + "\t} while (0)\n" + "\n" + "#line 1\n"; function findTestCasesSync(argList) { var found = {}; var pat = /^([a-zA-Z0-9_-]+).(js|c)$/; var testcases = []; argList.forEach(function checkArg(arg) { var st = fs.statSync(arg); var m; if (st.isFile()) { m = pat.exec(path.basename(arg)); if (!m) { return; } if (found[m[1]]) { return; } if (m[1].substring(0, 5) === 'util-') { return; } // skip utils found[m[1]] = true; testcases.push(arg); } else if (st.isDirectory()) { fs.readdirSync(arg) .forEach(function check(fn) { var m = pat.exec(fn); if (!m) { return; } if (found[m[1]]) { return; } found[m[1]] = true; testcases.push(path.join(arg, fn)); }); } else { throw new Exception('invalid argument: ' + arg); } }); return testcases; } function adornString(x) { var stars = '********************************************************************************'; return stars.substring(0, x.length + 8) + '\n' + '*** ' + x + ' ***' + '\n' + stars.substring(0, x.length + 8); } function prettyJson(x) { return JSON.stringify(x, null, 2); } function prettySnippet(x, label) { x = (x != null ? x : ''); if (x.length > 0 && x[x.length - 1] != '\n') { x += '\n'; } return '=== begin: ' + label + ' ===\n' + x + '=== end: ' + label + ' ==='; } function getValgrindErrorSummary(root) { var res; var errors; if (!root || !root.valgrindoutput || !root.valgrindoutput.error) { return; } root.valgrindoutput.error.forEach(function vgError(e) { var k = e.kind[0]; if (!res) { res = {}; } if (!res[k]) { res[k] = 1; } else { res[k]++; } }); return res; } function testRunnerMain() { var argv = require('optimist') .usage('Execute one or multiple test cases; dirname to execute all tests in a directory.') .default('num-threads', 4) .default('test-sleep', 0) .default('python-command', 'python2') .boolean('run-duk') .boolean('run-nodejs') .boolean('run-rhino') .boolean('run-smjs') .boolean('verbose') .boolean('report-diff-to-other') .boolean('valgrind') .boolean('emduk-trailing-line-hack') .describe('num-threads', 'number of threads to use for testcase execution') .describe('test-sleep', 'sleep time (milliseconds) between testcases, avoid overheating :)') .describe('python-command', 'python2 executable to use') .describe('run-duk', 'run testcase with Duktape') .describe('cmd-duk', 'path for "duk" command') .describe('run-nodejs', 'run testcase with Node.js (V8)') .describe('cmd-nodejs', 'path for Node.js command') .describe('run-rhino', 'run testcase with Rhino') .describe('cmd-rhino', 'path for Rhino command') .describe('run-smjs', 'run testcase with smjs') .describe('cmd-smjs', 'path for Spidermonkey executable') .describe('verbose', 'verbose test output') .describe('report-diff-to-other', 'report diff to other engines') .describe('valgrind', 'run duktape testcase with valgrind (no effect on other engines)') .describe('prep-test-path', 'path for test_prep.py') .describe('util-include-path', 'path for util-*.js files (tests/ecmascript usually)') .describe('minify-closure', 'path for closure compiler.jar') .describe('minify-uglifyjs', 'path for UglifyJS executable') .describe('minify-uglifyjs2', 'path for UglifyJS2 executable') .describe('known-issues', 'known issues yaml file') .describe('emduk-trailing-line-hack', 'strip bogus newline from end of emduk stdout') .demand('prep-test-path') .demand('util-include-path') .demand(1) // at least 1 non-arg .argv; var testcases; var engines; var queue1, queue2; var results = {}; // testcase -> engine -> result var execStartTime, execStartQueue; function iterateResults(callback, filter_engname) { var testname, engname; for (testname in results) { for (engname in results[testname]) { if (filter_engname && engname !== filter_engname) { continue; } res = results[testname][engname]; callback(testname, engname, results[testname][engname]); } } } function queueExecTasks() { var tasks = []; testcases.forEach(function test(fullPath) { var filename = path.basename(fullPath); var testcase = parseTestCaseSync(fullPath); if (testcase.meta.skip) { // console.log('skip testcase: ' + testcase.name); return; } addKnownIssueMetadata(testcase); results[testcase.name] = {}; // create in test case order if (path.extname(fullPath) === '.c') { tasks.push({ engine: engine_api, filename: filename, testPath: fullPath, testcase: testcase, valgrind: argv.valgrind, notimeout: argv['no-timeout'] }); } else { engines.forEach(function testWithEngine(engine) { tasks.push({ engine: engine, filename: filename, testPath: fullPath, testcase: testcase, valgrind: argv.valgrind && (engine.name === 'duk'), notimeout: argv['no-timeout'] }); }); } }); if (tasks.length === 0) { console.log('No tasks to execute'); process.exit(1); } console.log('Executing ' + testcases.length + ' testcase(s) with ' + engines.length + ' engine(s) using ' + argv['num-threads'] + ' thread(s)' + ', total ' + tasks.length + ' task(s)' + (argv.valgrind ? ', valgrind enabled (for duk)' : '')); queue1.push(tasks); } function queueDiffTasks() { var tn, en, res; console.log('Testcase execution done, running diffs'); iterateResults(function queueDiff(tn, en, res) { if (res.stdout !== res.testcase.expect) { queue2.push({ src: res.testcase.expect, dst: res.stdout, resultObject: res, resultKey: 'diff_expect' }); } if (en !== 'duk' || en === 'api') { return; } // duk-specific diffs engines.forEach(function diffToEngine(other) { if (other.name === 'duk') { return; } if (results[tn][other.name].stdout === res.stdout) { return; } if (!res.diff_other) { res.diff_other = {} } queue2.push({ src: results[tn][other.name].stdout, dst: res.stdout, resultObject: res.diff_other, resultKey: other.name }); }); }, null); } function analyzeResults() { var summary = { exitCode: 0 }; iterateResults(function analyze(tn, en, res) { res.stdout_md5 = md5(res.stdout); res.stderr_md5 = md5(res.stderr); if (res.testcase.meta.skip) { res.status = 'skip'; } else if (res.diff_expect) { if (!res.testcase.meta.knownissue && !res.testcase.meta.specialoptions) { summary.exitCode = 1; } res.status = 'fail'; } else { res.status = 'pass'; } }); return summary; } function printSummary() { var countPass = 0, countFail = 0, countSkip = 0; var lines = []; iterateResults(function summary(tn, en, res) { var parts = []; var diffs; var vgerrors; var need = false; if (en !== 'duk' && en !== 'api') { return; } vgerrors = getValgrindErrorSummary(res.valgrind_root); parts.push(res.testcase.name); parts.push(res.status); if (res.status === 'skip') { countSkip++; } else if (res.status === 'fail') { countFail++; parts.push(res.diff_expect.split('\n').length + ' diff lines'); if (res.testcase.meta.knownissue) { if (typeof res.testcase.meta.knownissue === 'string') { parts.push('known issue: ' + res.testcase.meta.knownissue); } else { parts.push('known issue'); } } if (res.testcase.meta.specialoptions) { if (typeof res.testcase.meta.specialoptions === 'string') { parts.push('requires special feature options: ' + res.testcase.meta.specialoptions); } else { parts.push('requires special feature options'); } } if (res.testcase.meta.comment) { parts.push('comment: ' + res.testcase.meta.comment); } need = true; } else { countPass++; diffs = []; engines.forEach(function checkDiffToOther(other) { if (other.name === 'duk' || !res.diff_other || !res.diff_other[other.name]) { return; } parts.push(other.name + ' diff ' + res.diff_other[other.name].split('\n').length + ' lines'); if (argv['report-diff-to-other']) { need = true; } }); } if (vgerrors) { parts.push('valgrind ' + JSON.stringify(vgerrors)); need = true; } if (need) { lines.push(parts); } }, null); lines.forEach(function printLine(line) { var tmp = (' ' + line[0]); tmp = tmp.substring(tmp.length - 50); console.log(tmp + ': ' + line.slice(1).join('; ')); }); console.log(''); console.log('SUMMARY: ' + countPass + ' pass, ' + countFail + ' fail'); // countSkip is no longer correct } function createLogFile(logFile) { var lines = []; iterateResults(function logResult(tn, en, res) { var desc = tn + '/' + en; lines.push(adornString(tn + ' ' + en)); lines.push(''); lines.push(prettyJson(res)); lines.push(''); lines.push(prettySnippet(res.stdout, 'stdout of ' + desc)); lines.push(''); lines.push(prettySnippet(res.stderr, 'stderr of ' + desc)); lines.push(''); lines.push(prettySnippet(res.testcase.expect, 'expect of ' + desc)); lines.push(''); if (res.diff_expect) { lines.push(prettySnippet(res.diff_expect, 'diff_expect of ' + desc)); lines.push(''); } if (res.diff_other) { for (other_name in res.diff_other) { lines.push(prettySnippet(res.diff_other[other_name], 'diff_other ' + other_name + ' of ' + desc)); lines.push(''); } } }); fs.writeFileSync(logFile, lines.join('\n') + '\n'); } optPythonCommand = argv['python-command']; if (argv['prep-test-path']) { optPrepTestPath = argv['prep-test-path']; } else { throw new Error('missing --prep-test-path'); } if (argv['minify-closure']) { optMinifyClosure = argv['minify-closure']; } if (argv['minify-uglifyjs']) { optMinifyUglifyJS = argv['minify-uglifyjs']; } if (argv['minify-uglifyjs2']) { optMinifyUglifyJS2 = argv['minify-uglifyjs2']; } // Don't require a minifier here because we may be executing API testcases if (argv['util-include-path']) { optUtilIncludePath = argv['util-include-path']; } else { throw new Error('missing --util-include-path'); } if (argv['known-issues']) { knownIssues = yaml.load(argv['known-issues']); } if (argv['emduk-trailing-line-hack']) { optEmdukTrailingLineHack = true; } engines = []; if (argv['run-duk']) { engines.push({ name: 'duk', fullPath: argv['cmd-duk'] || 'duk' , jsPrefix: DUK_HEADER }); } if (argv['run-nodejs']) { engines.push({ name: 'nodejs', fullPath: argv['cmd-nodejs'] || 'node', jsPrefix: NODEJS_HEADER }); } if (argv['run-rhino']) { engines.push({ name: 'rhino', fullPath: argv['cmd-rhino'] || 'rhino', jsPrefix: RHINO_HEADER }); } if (argv['run-smjs']) { engines.push({ name: 'smjs', fullPath: argv['cmd-smjs'] || 'smjs', jsPrefix: SMJS_HEADER }); } engine_api = { name: 'api', cPrefix: API_TEST_HEADER }; testcases = findTestCasesSync(argv._); testcases.sort(); //console.log(testcases); queue1 = async.queue(function (task, callback) { executeTest(task, function testDone(err, val) { var tmp; results[task.testcase.name][task.engine.name] = val; if (argv.verbose) { tmp = ' ' + task.engine.name + (task.valgrind ? '/vg' : ''); console.log(tmp.substring(tmp.length - 8) + ': ' + task.testcase.name); } if (argv['test-sleep'] > 0) { setTimeout(callback, Number(argv['test-sleep'])); } else { callback(); } }); }, argv['num-threads']); queue2 = async.queue(function (task, callback) { if (task.dummy) { callback(); return; } diffText(task.src, task.dst, function (err, val) { task.resultObject[task.resultKey] = val; callback(); }); }, argv['num-threads']); queue1.drain = function() { // Second parallel step: run diffs queue2.push({ dummy: true }); // ensure queue is not empty queueDiffTasks(); }; queue2.drain = function() { // summary and exit var summary = analyzeResults(); console.log('\n----------------------------------------------------------------------------\n'); printSummary(); console.log('\n----------------------------------------------------------------------------\n'); if (argv['log-file']) { console.log('Writing test output to: ' + argv['log-file']); createLogFile(argv['log-file']); } console.log('All done.'); process.exit(summary.exitCode); }; // First parallel step: run testcases with selected engines queueExecTasks(); // Periodic indication of how much to go execStartTime = new Date().getTime(); execStartQueue = queue1.length(); var timer = setInterval(function () { // not exact; not in queued != finished var now = new Date().getTime(); var rate = (execStartQueue - queue1.length()) / ((now - execStartTime) / 1000); var eta = Math.ceil(queue1.length() / rate); console.log('Still running, testcase task queue length: ' + queue1.length() + ', eta ' + eta + ' second(s)'); }, 10000); } testRunnerMain();
var validate = function(regexString, truthy, falsy) { var regex = new RegExp(regexString); var error = function(value, expected) { return 'Expected ' + value + ' to be ' + String(expected) + ' instead of ' + String(!expected) + '!'; }; for (var i = 0; i < truthy.length; i++) { if (regex.test(truthy[i]) === false) { return error(truthy[i], true); } } for (var i = 0; i < falsy.length; i++) { if (regex.test(falsy[i]) === true) { return error(falsy[i], false); } } return 'Success! All test cases passed!'; }; module.exports = validate;
describe('KeyCoder', function() { it('all keys returns the correct number of keys', function() { expect(Keycoder.allKeys().length).to.equal(100); }); it('creates all named keys', function() { Keycoder.allKeys().forEach(function(key) { key.names.forEach(function(name) { expect(Keycoder.key[name]).not.to.be.undefined; expect(Keycoder.key[name].keyCode.ie).to.equal(key.keyCode.ie); }); }); }); describe('protects source key data from changes to', function() { var changedAKey, changedBackspaceKey; beforeEach(function() { changedAKey = Keycoder.fromCharacter('a'); changedBackspaceKey = Keycoder.fromKeyCode(8); }); describe('name', function() { it('values', function() { changedBackspaceKey.names[0] = 'DIFFERENT'; expect(Keycoder.fromKeyCode(8).names[0]).not.to.equal('DIFFERENT'); }); it('arrays', function() { changedBackspaceKey.names = ['DIFFERENT']; expect(Keycoder.fromKeyCode(8).names[0]).not.to.equal('DIFFERENT'); }); }); it('characters', function() { changedAKey.character = '-'; expect(Keycoder.fromCharacter('a').character).not.to.equal('-'); }); it('shift characters', function() { changedAKey.shift.character = '-'; expect(Keycoder.fromCharacter('a').shift.character).not.to.equal('-'); }); it('Mozilla key codes', function() { changedAKey.keyCode.mozilla = -1; expect(Keycoder.fromCharacter('a').keyCode.mozilla).not.to.equal(-1); }); it('IE key codes', function() { changedAKey.keyCode.ie = -1; expect(Keycoder.fromCharacter('a').keyCode.ie).not.to.equal(-1); }); it('character codes', function() { changedAKey.charCode = -1; expect(Keycoder.fromCharCode(97).charCode).not.to.equal(-1); }); it('shift character codes', function() { changedAKey.charCode = -1; expect(Keycoder.fromCharCode(65).charCode).not.to.equal(-1); }); }); describe('compares', function() { var deleteKey, otherDeleteKey, backspaceKey; beforeEach(function() { backspaceKey = Keycoder.fromKeyCode(8); deleteKey = Keycoder.fromKeyCode(46); otherDeleteKey = Keycoder.fromKeyCode(46); }); describe('key objects to key objects and', function() { it('returns true when they are equal', function() { expect(deleteKey.equals(otherDeleteKey)).to.equal(true); }); it('returns false when they are not equal', function() { expect(backspaceKey.equals(deleteKey)).to.equal(false); }); }); describe('IE key codes to key objects and', function() { it('returns true when they are equal', function() { expect(deleteKey.equals(otherDeleteKey.keyCode.ie)).to.equal(true); }); it('returns false when they are not equal', function() { expect(backspaceKey.equals(deleteKey.keyCode.ie)).to.equal(false); }); }); describe('Mozilla key codes to key objects and', function() { it('returns true when they are equal', function() { expect(deleteKey.equals(otherDeleteKey.keyCode.mozilla)).to.equal(true); }); it('returns false when they are not equal', function() { expect(backspaceKey.equals(deleteKey.keyCode.mozilla)).to.equal(false); }); }); describe('named keys to key objects and', function() { it('returns true when they are equal', function() { expect(deleteKey.equals(Keycoder.key.DELETE)).to.equal(true); }); it('returns false when they are not equal', function() { expect(deleteKey.equals(Keycoder.key.INSERT)).to.equal(false); }); }); }); describe('key objects know if they', function() { it('have distinct shift characters', function() { var aKey = Keycoder.fromCharacter('1'); expect(aKey.hasDistinctShiftCharacter()).to.equal(true); }); it('do not have distinct shift characters', function() { var spaceKey = Keycoder.fromCharacter(' '); expect(spaceKey.hasDistinctShiftCharacter()).to.equal(false); }); it('are printable characters', function() { var aKey = Keycoder.fromCharacter('a'); expect(aKey.isPrintableCharacter()).to.equal(true); }); it('are not printable characters', function() { var backSpaceKey = Keycoder.fromKeyCode(8); expect(backSpaceKey.isPrintableCharacter()).to.equal(false); }); it('have character codes', function() { var aKey = Keycoder.fromCharacter('a'); expect(aKey.hasCharCode()).to.equal(true); }); it('do not have character codes', function() { expect(Keycoder.key.BACKSPACE.hasCharCode()).to.equal(false); }); }); describe('maps', function() { describe('event objects with type', function() { var event; describe('keypress', function() { beforeEach(function() { event = { type: 'keypress', shiftKey: false } }); it('to a printable character', function() { event.charCode = 97; expect(Keycoder.eventToCharacter(event)).to.equal('a'); }); it('to a shift key printable characters ', function() { event.charCode = 65; event.shiftKey = true; expect(Keycoder.eventToCharacter(event)).to.equal('A'); }); it('to null if no matching key is found', function() { it('to a shift key printable characters ', function() { event.charCode = -1; expect(Keycoder.eventToCharacter(event)).to.equal(null); }); }); }); describe('keyup', function() { beforeEach(function() { event = { type: 'keyup', keyCode: 65, shiftKey: false } }); it('to a printable character', function() { expect(Keycoder.eventToCharacter(event)).to.equal('a'); }); it('to a shift key printable characters ', function() { event.shiftKey = true; expect(Keycoder.eventToCharacter(event)).to.equal('A'); }); it('to null if no matching key is found', function() { it('to a shift key printable characters ', function() { event.keyCode = -1; expect(Keycoder.eventToCharacter(event)).to.equal(null); }); }); }); describe('keydown', function() { beforeEach(function() { event = { type: 'keydown', keyCode: 65, shiftKey: false } }); it('to a printable character', function() { expect(Keycoder.eventToCharacter(event)).to.equal('a'); }); it('to a shift key printable characters ', function() { event.shiftKey = true; expect(Keycoder.eventToCharacter(event)).to.equal('A'); }); it('to null if no matching key is found', function() { it('to a shift key printable characters ', function() { event.keyCode = -1; expect(Keycoder.eventToCharacter(event)).to.equal(null); }); }); }); }); describe('printable character', function() { var characters = ' 0123456789abcdefghijklmnopqrstuvwxyz`-=[]\\;\',./'.split(''); characters.forEach(function(character) { it(character + ' to a key', function() { var key = Keycoder.fromCharacter(character); expect(key.character).to.equal(character); }); }); var shiftCharacters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ~!@#$%^&*()_+{}|:"<>?'.split(''); shiftCharacters.forEach(function(character) { it(character + ' to a key', function() { var key = Keycoder.fromCharacter(character); expect(key.shift.character).to.equal(character); }); }); }); Keycoder.allKeys().forEach(function(key) { if(key.character !== null) { it('IE keycode '+ key.keyCode.ie + ' to ' + key.character, function() { var ieCharacter = Keycoder.toCharacter(key.keyCode.ie); expect(ieCharacter).to.equal(key.character); }); it('Mozilla keycode '+ key.keyCode.mozilla + ' to ' + key.character, function() { var mozillaCharacter = Keycoder.toCharacter(key.keyCode.mozilla); expect(mozillaCharacter).to.equal(key.character); }); } it('Mozilla key code ' + key.keyCode.mozilla + ' to a key', function() { var mappedKey = Keycoder.fromKeyCode(key.keyCode.mozilla); expect(mappedKey.keyCode.mozilla).to.equal(key.keyCode.mozilla); }); it('IE key code ' + key.keyCode.ie + ' to a key', function() { var mappedKey = Keycoder.fromKeyCode(key.keyCode.ie); expect(mappedKey.keyCode.ie).to.equal(key.keyCode.ie); }); //Skip the numpad keys since their char codes match those of the other number keys //they won't map back to the same value if(key.charCode !== null && (key.charCode < 42 || key.charCode > 57)) { it('ASCII char code ' + key.charCode + ' to a key', function() { var mappedKey = Keycoder.fromCharCode(key.charCode); expect(mappedKey.charCode).to.equal(key.charCode); }); } //Skip the numpad keys since their char codes match those of the other number keys //they won't map back to the same value if(key.shift.charCode !== null && (key.shift.charCode < 42 || key.shift.charCode > 57)) { it('ASCII shift char code ' + key.shift.charCode + ' to a key', function() { var mappedKey = Keycoder.fromCharCode(key.shift.charCode); expect(mappedKey.shift.charCode).to.equal(key.shift.charCode); }); } if(key.charCode !== null && key.character != null) { it('ASCII char code ' + key.charCode + ' to ' + key.character, function() { var mappedCharacter = Keycoder.charCodeToCharacter(key.charCode); expect(mappedCharacter).to.equal(key.character); }); } if(key.shift.charCode !== null && key.shift.character != null) { it('char code ' + key.charCode + ' to ' + key.shift.character, function() { var mappedCharacter = Keycoder.charCodeToCharacter(key.shift.charCode); expect(mappedCharacter).to.equal(key.shift.character); }); } }); }); });
define(['jquery','DoughBaseComponent','chosen'], function ($, DoughBaseComponent, chosen) { 'use strict'; var AutoCompleteProto, defaultConfig = {}; function AutoComplete($el, config) { AutoComplete.baseConstructor.call(this, $el, config, defaultConfig); } DoughBaseComponent.extend(AutoComplete); AutoComplete.componentName = 'AutoComplete'; AutoCompleteProto = AutoComplete.prototype; AutoCompleteProto.init = function(initialised) { var placeholderText = this.$el.attr('data-dough-placeholder-text'); this.$el.chosen({ placeholder_text_multiple: !!placeholderText? placeholderText : ' ', width: "100%", single_backstroke_delete: false, inherit_select_classes: true }).change(function() { $(this).closest('form').trigger('input'); }); this._initialisedSuccess(initialised); return this; }; return AutoComplete; });
import React from "react"; import PropTypes from "prop-types"; import moment from "moment"; import Immutable from "immutable"; import LightComponent from "ui-lib/light_component"; import { Row, Column, Header, Section, Loading } from "ui-components/layout"; import { CardList, JobSpecCard, JobCard } from "ui-components/data_card"; import JobListObservable from "ui-observables/paged_job_list"; import { ListPager } from "ui-components/type_admin"; import { States as ObservableDataStates } from "ui-lib/observable_data"; class JobSpecView extends LightComponent { constructor(props) { super(props); this.jobs = new JobListObservable({ limit: 10, query: { "jobSpec.id": props.item._id } }); this.state = { jobs: this.jobs.value.getValue(), jobsState: this.jobs.state.getValue() }; } componentDidMount() { this.addDisposable(this.jobs.start()); this.addDisposable(this.jobs.value.subscribe((jobs) => this.setState({ jobs }))); this.addDisposable(this.jobs.value.subscribe((jobsState) => this.setState({ jobsState }))); } componentWillReceiveProps(nextProps) { this.jobs.setOpts({ query: { "jobSpec.id": nextProps.item._id } }); } render() { this.log("render", this.props, this.state); const jobs = this.state.jobs.map((item) => Immutable.fromJS({ id: item.get("_id"), time: moment(item.get("created")).unix(), item: item.toJS(), Card: JobCard, props: { clickable: true } })); return ( <Row> <Column xs={12} md={6}> <Section> <Header label="Properties" /> <JobSpecCard item={this.props.item} expanded={true} expandable={false} /> </Section> </Column> <Column xs={12} md={6}> <Header label="Jobs" /> <Loading show={this.state.jobsState === ObservableDataStates.LOADING}/> <CardList list={Immutable.fromJS(jobs)} /> <ListPager pagedList={this.jobs} pagingInfo={this.jobs.pagingInfo.getValue()} /> </Column> </Row> ); } } JobSpecView.propTypes = { theme: PropTypes.object, item: PropTypes.object }; export default JobSpecView;
"use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; var _createSvgIcon = _interopRequireDefault(require("./utils/createSvgIcon")); var _jsxRuntime = require("react/jsx-runtime"); var _default = (0, _createSvgIcon.default)( /*#__PURE__*/(0, _jsxRuntime.jsx)("path", { d: "M18 12.22V9l-5-2.5V5h2V3h-2V1h-2v2H9v2h2v1.5L6 9v3.22L2 14v8h8v-3c0-1.1.9-2 2-2s2 .9 2 2v3h8v-8l-4-1.78zm-6 1.28c-.83 0-1.5-.67-1.5-1.5s.67-1.5 1.5-1.5 1.5.67 1.5 1.5-.67 1.5-1.5 1.5z" }), 'Church'); exports.default = _default;
var angular = require('angular'); require('angular-bootstrap'); var settings = angular.module('prex.settings', ['ui.bootstrap']); var RootFolderModalCtrl = function ($scope, $modalInstance) { $scope.paths = [{}]; $scope.ok = function () { $modalInstance.close($scope.paths); }; $scope.remove = function (path) { var idx = $scope.paths.indexOf(path); $scope.paths.splice(idx, 1); }; $scope.cancel = function () { $modalInstance.dismiss('cancel'); }; }; settings.directive('menu', function () { return { restrict: 'EA', transclude: true, templateUrl: 'settings/menu.html', controller: function ($scope, $element, $attrs) { $scope.isVisible = false; function onMouseMove(evt) { if (evt.y < 100 && !$scope.isVisible) { $scope.isVisible = true; $scope.$apply(); } else if (evt.y >= 100 && $scope.isVisible) { $scope.isVisible = false; $scope.$apply(); } } window.addEventListener('mousemove', onMouseMove, false); $scope.$on('$destroy', function (){ document.removeEventListener('mousemove', onMouseMove); }); } }; }) .directive('addRootFolderButton', function ($modal) { return { restrict: 'EA', replace: true, template: '<li ng-click="open()"> <a href="">Add root folder</a></li>', require: '^menu', link: function (scope, element, attrs) { scope.open = function () { var instance = $modal.open({ templateUrl: 'settings/root-folder-modal.html', controller: RootFolderModalCtrl }); instance.result.then(function (paths) { }); }; } } });
var events = require('events'); var util = require('util'); var Worker = function(){ events.EventEmitter.call(this); var self = this; process.on('message', function(msg){ self.dispatcher(msg); }); }; util.inherits(Worker, events.EventEmitter); Worker.prototype.dispatcher = function(msg){ msg.param._seq = msg._seq; this.emit(msg.type, msg.param); } Worker.prototype.send = function(type, param){ process.send({ _seq : param._seq, type : type, param : param }); } var worker = module.exports = new Worker();
export { default } from './switcher-mpref';
var colors = require('colors') var prefix = '[CKStyle] '.cyan function out(msg) { console.log(msg) } function log(msg) { console.log(prefix + msg) } function warn(msg) { console.log(prefix + msg.yellow) } function error(msg) { console.log(prefix + msg.red) } function ok(msg) { console.log(prefix + msg.green) } exports.log = log exports.warn = warn exports.error = error exports.ok = ok exports.out = out
(function () { 'use strict'; angular .module('app.meerp.services') .service('errorService', errorService); function errorService() { return { handleError: handleError, }; function handleError(error) { } } })();
jQuery(document).ready(function() { jQuery('#filterKommuner').fastLiveFilter('#kommuner ul', {callback: function(numShown) { if( jQuery('#filterKommuner').val().length == 0 ) { jQuery(document).trigger('monstring_not_searching'); } else if(numShown == 0) { jQuery(document).trigger('monstring_none_found'); } else { jQuery(document).trigger('monstring_some_found'); } } }); jQuery('#filterKommuner').change(); //jQuery('.monstringSok').hide(); }); jQuery(document).on('monstring_none_found', function() { //jQuery('#plStartSearch').hide(); jQuery('#plNoneFound').show(); }); jQuery(document).on('monstring_some_found', function() { //jQuery('#plStartSearch').hide(); jQuery('#plNoneFound').hide(); jQuery('#kommuner button').each(function() { if(jQuery(this).find('button:visible').length == 0) { jQuery(this).closest('h3').hide(); } else { jQuery(this).closest('h3').show(); } }) }); jQuery(document).on('monstring_not_searching', function() { //jQuery('.monstringSok').hide(); //jQuery('#plStartSearch').show(); jQuery('#plNoneFound').hide(); });
import React from 'react'; import styled from 'styled-components'; import Icon from '../Icon/Icon'; import Tooltip from '../Overlay/Tooltip'; import { FileButton, SelectInput, TextareaInput, TextInput } from './FieldBox'; import { field as propTypes } from '../../helpers/propTypes'; const Status = styled.div` bottom: 0; display: block; position: absolute; white-space: nowrap; ${props => props.theme.isRTL ? 'left' : 'right'}: 0; `; const TipIcon = styled(Icon)` cursor: default; display: inline-block; font-size: 0.8em; color: #999; margin-${props => props.theme.isRTL ? 'right' : 'left'}: 5px; text-align: center; vertical-align: middle; width: 16px; &:before { display: inline-block; font-size: 10px !important; vertical-align: middle; width: 14px; } `; const Label = styled.label` display: inline-block; font-weight: ${props => props.theme.field.labelFontWeight}; vertical-align: middle; `; const Required = styled.span` color: ${props => props.theme.colors.error}; `; const HeadFeedback = styled.div` animation: 0.3s ${props => props.theme.keyframes.fadeInDown} ease; border-radius: ${props => props.theme.common.radius}px; bottom: 20px; font-size: 13px; ${props => props.theme.isRTL ? 'right' : 'left'}: 0; line-height: 18px; max-width: 300px; padding: 2px 6px; position: absolute; &:after { border: 4px solid transparent; border-bottom: none; content: ''; display: block; ${props => props.theme.isRTL ? 'right' : 'left'}: 10px; position: absolute; top: 100%; } `; const HeadError = HeadFeedback.extend` background-color: ${props => props.theme.colors.error}; color: white; &:after { border-top-color: ${props => props.theme.colors.error}; } `; const HeadWarning = HeadFeedback.extend` background-color: ${props => props.theme.colors.warning}; color: white; &:after { border-top-color: ${props => props.theme.colors.warning}; } `; const HeadRaw = (props) => { const { className, errorMessage, feedbackIn, hasError, hasWarning, label, required, status, tip, warningMessage } = props; const labelMarkup = label ? ( <Label> {label} {required ? <Required>⁕</Required> : null} </Label> ) : null; let errorMarkup; let warningMarkup; if (feedbackIn === 'head') { if (hasError) { errorMarkup = (<HeadError>{errorMessage}</HeadError>); } if (!hasError && hasWarning) { warningMarkup = (<HeadWarning>{warningMessage}</HeadWarning>); } } const tipMarkup = tip ? ( <Tooltip gutter="xs" content={tip}> <TipIcon nameDefault="info" /> </Tooltip> ) : null; const statusMarkup = status ? (<Status>{status}</Status>) : null; if (labelMarkup || errorMarkup || warningMarkup || tipMarkup || statusMarkup) { return ( <div className={className}> {labelMarkup} {tipMarkup} {errorMarkup} {warningMarkup} {statusMarkup} </div> ); } return null; }; const Head = styled(HeadRaw)` margin-bottom: 5px; ${props => props.status && !props.theme.isRTL ? 'padding-right: 50px;' : undefined} ${props => props.status && props.theme.isRTL ? 'padding-left: 50px;' : undefined} position: relative; `; const Help = styled.div` color: ${props => props.theme.colors.grayB}; `; const FootFeedback = styled.div` font-size: 12px; line-height: 14px; `; const FootError = FootFeedback.extend` color: ${props => props.theme.colors.error}; `; const FootWarning = FootFeedback.extend` color: ${props => props.theme.colors.warning}; `; const FootRaw = ({ className, errorMessage, feedbackIn, hasError, hasWarning, help, warningMessage }) => { const helpMarkup = help ? (<Help>{help}</Help>) : null; let errorMarkup; let warningMarkup; if (feedbackIn === 'foot') { if (hasError) { errorMarkup = (<FootError>{errorMessage}</FootError>); } if (!hasError && hasWarning) { warningMarkup = (<FootWarning>{warningMessage}</FootWarning>); } } if (helpMarkup || errorMarkup || warningMarkup) { return ( <div className={className}> {errorMarkup} {warningMarkup} {helpMarkup} </div> ); } return null; }; const Foot = styled(FootRaw)` font-size: 12px; margin-${props => props.theme.isRTL ? 'right' : 'left'}: 5px; margin-top: 5px; `; const AddOnContent = styled.div``; const AddOn = styled.div` align-items: center; border-radius: ${props => props.theme.button.size[props.size].radius}px; display: flex; white-space: nowrap; ${AddOnContent} { > * { flex-grow: 1; ${props => props.placement === 'after' ? `border-top-${props.theme.isRTL ? 'right' : 'left'}-radius: 0;` : undefined} ${props => props.placement === 'after' ? `border-bottom-${props.theme.isRTL ? 'right' : 'left'}-radius: 0;` : undefined} ${props => props.placement === 'before' ? `border-top-${props.theme.isRTL ? 'left' : 'right'}-radius: 0;` : undefined} ${props => props.placement === 'before' ? `border-bottom-${props.theme.isRTL ? 'left' : 'right'}-radius: 0;` : undefined} } } `; const BodyMain = styled.div``; const BodyRaw = ({ className, fieldIsBox, addOnBefore, addOnAfter, ...props }) => ( <div className={className}> { fieldIsBox && addOnBefore ? <AddOn placement="before" size={props.size}> <AddOnContent>{addOnBefore}</AddOnContent> </AddOn> : null } <BodyMain {...props} hasAddOn={!!(fieldIsBox && (addOnBefore || addOnAfter))} /> { fieldIsBox && addOnAfter ? <AddOn placement="after" size={props.size}> <AddOnContent>{addOnAfter}</AddOnContent> </AddOn> : null } </div> ); const Body = styled(BodyRaw)` display: flex; flex-direction: row; ${BodyMain} { flex-grow: 1; overflow-x: hidden; overflow-y: auto; } ${SelectInput}, ${TextInput}, ${TextareaInput}, ${FileButton} { ${props => props.addOnBefore ? `border-top-${props.theme.isRTL ? 'right' : 'left'}-radius: 0;` : undefined} ${props => props.addOnBefore ? `border-bottom-${props.theme.isRTL ? 'right' : 'left'}-radius: 0;` : undefined} ${props => props.addOnAfter ? `border-top-${props.theme.isRTL ? 'left' : 'right'}-radius: 0;` : undefined} ${props => props.addOnAfter ? `border-bottom-${props.theme.isRTL ? 'left' : 'right'}-radius: 0;` : undefined} } `; const FieldRaw = ({ className, ...props }) => { let body = ( <Body {...props} /> ); if (!props.label && props.tip) { body = ( <Tooltip align="right" gutter="sm" content={props.tip}> {body} </Tooltip> ); } return ( <div className={className}> <Head {...props} /> {body} <Foot {...props} /> </div> ); }; const Field = styled(FieldRaw)` font-size: ${props => props.theme.button.size[props.size].fontSize}px; line-height: ${props => props.theme.button.size[props.size].lineHeight}; position: relative; `; Field.propTypes = propTypes; Field.defaultProps = { size: 'md' }; // Build shortcuts for custom styling purposes! AddOn.Content = AddOnContent; Head.Status = Status; Head.Label = Label; Head.Tip = TipIcon; Head.Required = Required; Head.Error = HeadError; Head.Warning = HeadWarning; Foot.Help = Help; Foot.Error = FootError; Foot.Warning = FootWarning; Body.AddOn = AddOn; Body.Main = BodyMain; Field.Head = Head; Field.Foot = Foot; Field.Body = Body; export default Field;
import React from 'react'; import { makeStyles } from '@material-ui/core/styles'; import Grid from '@material-ui/core/Grid'; import FormLabel from '@material-ui/core/FormLabel'; import FormControlLabel from '@material-ui/core/FormControlLabel'; import RadioGroup from '@material-ui/core/RadioGroup'; import Radio from '@material-ui/core/Radio'; import Paper from '@material-ui/core/Paper'; const useStyles = makeStyles((theme) => ({ root: { flexGrow: 1, }, paper: { height: 140, width: 100, }, control: { padding: theme.spacing(2), }, })); export default function SpacingGrid() { const [spacing, setSpacing] = React.useState(2); const classes = useStyles(); const handleChange = (event) => { setSpacing(Number(event.target.value)); }; return ( <Grid container className={classes.root} spacing={2}> <Grid item xs={12}> <Grid container justify="center" spacing={spacing}> {[0, 1, 2].map((value) => ( <Grid key={value} item> <Paper className={classes.paper} /> </Grid> ))} </Grid> </Grid> <Grid item xs={12}> <Paper className={classes.control}> <Grid container> <Grid item> <FormLabel>spacing</FormLabel> <RadioGroup name="spacing" aria-label="spacing" value={spacing.toString()} onChange={handleChange} row > {[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10].map((value) => ( <FormControlLabel key={value} value={value.toString()} control={<Radio />} label={value.toString()} /> ))} </RadioGroup> </Grid> </Grid> </Paper> </Grid> </Grid> ); }
!function(e,n){if("function"==typeof define&&define.amd)define(["exports"],n);else if("undefined"!=typeof exports)n(exports);else{var t={exports:{}};n(t.exports),e.temperature=t.exports}}(this,function(e){"use strict";function n(e){return 9*e/5+32}function t(e){return e+273.15}function i(e){return 5*(e-32)/9}function r(e){return 5*(e-32)/9+273.15}function o(e){return e-273.15}function u(e){return 9*(e-273.15)/5+32}Object.defineProperty(e,"__esModule",{value:!0}),e.celsiusToFahrenheit=n,e.celsiusToKelvin=t,e.fahrenheitToCelsius=i,e.fahrenheitToKelvin=r,e.kelvinToCelsius=o,e.kelvinToFahrenheit=u});
// flow-typed signature: 1466e36b1ef82dc9829709c974e5b4a4 // flow-typed version: <<STUB>>/webpack_v2.1.0-beta.25/flow_v0.33.0 /** * This is an autogenerated libdef stub for: * * 'webpack' * * Fill this stub out by replacing all the `any` types. * * Once filled out, we encourage you to share your work with the * community by sending a pull request to: * https://github.com/flowtype/flow-typed */ declare module 'webpack' { declare module.exports: any; } /** * We include stubs for each file inside this npm package in case you need to * require those files directly. Feel free to delete any files that aren't * needed. */ declare module 'webpack/bin/config-optimist' { declare module.exports: any; } declare module 'webpack/bin/config-yargs' { declare module.exports: any; } declare module 'webpack/bin/convert-argv' { declare module.exports: any; } declare module 'webpack/bin/webpack' { declare module.exports: any; } declare module 'webpack/buildin/amd-define' { declare module.exports: any; } declare module 'webpack/buildin/amd-options' { declare module.exports: any; } declare module 'webpack/buildin/global' { declare module.exports: any; } declare module 'webpack/buildin/module' { declare module.exports: any; } declare module 'webpack/buildin/return-require' { declare module.exports: any; } declare module 'webpack/hot/dev-server' { declare module.exports: any; } declare module 'webpack/hot/emitter' { declare module.exports: any; } declare module 'webpack/hot/log-apply-result' { declare module.exports: any; } declare module 'webpack/hot/only-dev-server' { declare module.exports: any; } declare module 'webpack/hot/poll' { declare module.exports: any; } declare module 'webpack/hot/signal' { declare module.exports: any; } declare module 'webpack/lib/AbstractPlugin' { declare module.exports: any; } declare module 'webpack/lib/AmdMainTemplatePlugin' { declare module.exports: any; } declare module 'webpack/lib/APIPlugin' { declare module.exports: any; } declare module 'webpack/lib/ArrayMap' { declare module.exports: any; } declare module 'webpack/lib/AsyncDependenciesBlock' { declare module.exports: any; } declare module 'webpack/lib/AutomaticPrefetchPlugin' { declare module.exports: any; } declare module 'webpack/lib/BannerPlugin' { declare module.exports: any; } declare module 'webpack/lib/BasicEvaluatedExpression' { declare module.exports: any; } declare module 'webpack/lib/CachePlugin' { declare module.exports: any; } declare module 'webpack/lib/CaseSensitiveModulesWarning' { declare module.exports: any; } declare module 'webpack/lib/Chunk' { declare module.exports: any; } declare module 'webpack/lib/ChunkRenderError' { declare module.exports: any; } declare module 'webpack/lib/ChunkTemplate' { declare module.exports: any; } declare module 'webpack/lib/CommonJsHarmonyMainTemplatePlugin' { declare module.exports: any; } declare module 'webpack/lib/compareLocations' { declare module.exports: any; } declare module 'webpack/lib/CompatibilityPlugin' { declare module.exports: any; } declare module 'webpack/lib/Compilation' { declare module.exports: any; } declare module 'webpack/lib/Compiler' { declare module.exports: any; } declare module 'webpack/lib/ConstPlugin' { declare module.exports: any; } declare module 'webpack/lib/ContextModule' { declare module.exports: any; } declare module 'webpack/lib/ContextModuleFactory' { declare module.exports: any; } declare module 'webpack/lib/ContextReplacementPlugin' { declare module.exports: any; } declare module 'webpack/lib/DefinePlugin' { declare module.exports: any; } declare module 'webpack/lib/DelegatedModule' { declare module.exports: any; } declare module 'webpack/lib/DelegatedModuleFactoryPlugin' { declare module.exports: any; } declare module 'webpack/lib/DelegatedPlugin' { declare module.exports: any; } declare module 'webpack/lib/dependencies/AMDDefineDependency' { declare module.exports: any; } declare module 'webpack/lib/dependencies/AMDDefineDependencyParserPlugin' { declare module.exports: any; } declare module 'webpack/lib/dependencies/AMDPlugin' { declare module.exports: any; } declare module 'webpack/lib/dependencies/AMDRequireArrayDependency' { declare module.exports: any; } declare module 'webpack/lib/dependencies/AMDRequireContextDependency' { declare module.exports: any; } declare module 'webpack/lib/dependencies/AMDRequireDependenciesBlock' { declare module.exports: any; } declare module 'webpack/lib/dependencies/AMDRequireDependenciesBlockParserPlugin' { declare module.exports: any; } declare module 'webpack/lib/dependencies/AMDRequireDependency' { declare module.exports: any; } declare module 'webpack/lib/dependencies/AMDRequireItemDependency' { declare module.exports: any; } declare module 'webpack/lib/dependencies/CommonJsPlugin' { declare module.exports: any; } declare module 'webpack/lib/dependencies/CommonJsRequireContextDependency' { declare module.exports: any; } declare module 'webpack/lib/dependencies/CommonJsRequireDependency' { declare module.exports: any; } declare module 'webpack/lib/dependencies/CommonJsRequireDependencyParserPlugin' { declare module.exports: any; } declare module 'webpack/lib/dependencies/ConstDependency' { declare module.exports: any; } declare module 'webpack/lib/dependencies/ContextDependency' { declare module.exports: any; } declare module 'webpack/lib/dependencies/ContextDependencyHelpers' { declare module.exports: any; } declare module 'webpack/lib/dependencies/ContextDependencyTemplateAsId' { declare module.exports: any; } declare module 'webpack/lib/dependencies/ContextDependencyTemplateAsRequireCall' { declare module.exports: any; } declare module 'webpack/lib/dependencies/ContextElementDependency' { declare module.exports: any; } declare module 'webpack/lib/dependencies/CriticalDependencyWarning' { declare module.exports: any; } declare module 'webpack/lib/dependencies/DelegatedSourceDependency' { declare module.exports: any; } declare module 'webpack/lib/dependencies/DepBlockHelpers' { declare module.exports: any; } declare module 'webpack/lib/dependencies/DllEntryDependency' { declare module.exports: any; } declare module 'webpack/lib/dependencies/getFunctionExpression' { declare module.exports: any; } declare module 'webpack/lib/dependencies/HarmonyAcceptDependency' { declare module.exports: any; } declare module 'webpack/lib/dependencies/HarmonyAcceptImportDependency' { declare module.exports: any; } declare module 'webpack/lib/dependencies/HarmonyExportDependencyParserPlugin' { declare module.exports: any; } declare module 'webpack/lib/dependencies/HarmonyExportExpressionDependency' { declare module.exports: any; } declare module 'webpack/lib/dependencies/HarmonyExportHeaderDependency' { declare module.exports: any; } declare module 'webpack/lib/dependencies/HarmonyExportImportedSpecifierDependency' { declare module.exports: any; } declare module 'webpack/lib/dependencies/HarmonyExportSpecifierDependency' { declare module.exports: any; } declare module 'webpack/lib/dependencies/HarmonyImportDependency' { declare module.exports: any; } declare module 'webpack/lib/dependencies/HarmonyImportDependencyParserPlugin' { declare module.exports: any; } declare module 'webpack/lib/dependencies/HarmonyImportSpecifierDependency' { declare module.exports: any; } declare module 'webpack/lib/dependencies/HarmonyModulesHelpers' { declare module.exports: any; } declare module 'webpack/lib/dependencies/HarmonyModulesPlugin' { declare module.exports: any; } declare module 'webpack/lib/dependencies/LoaderDependency' { declare module.exports: any; } declare module 'webpack/lib/dependencies/LoaderPlugin' { declare module.exports: any; } declare module 'webpack/lib/dependencies/LocalModule' { declare module.exports: any; } declare module 'webpack/lib/dependencies/LocalModuleDependency' { declare module.exports: any; } declare module 'webpack/lib/dependencies/LocalModulesHelpers' { declare module.exports: any; } declare module 'webpack/lib/dependencies/ModuleDependency' { declare module.exports: any; } declare module 'webpack/lib/dependencies/ModuleDependencyTemplateAsId' { declare module.exports: any; } declare module 'webpack/lib/dependencies/ModuleDependencyTemplateAsRequireId' { declare module.exports: any; } declare module 'webpack/lib/dependencies/ModuleHotAcceptDependency' { declare module.exports: any; } declare module 'webpack/lib/dependencies/ModuleHotDeclineDependency' { declare module.exports: any; } declare module 'webpack/lib/dependencies/MultiEntryDependency' { declare module.exports: any; } declare module 'webpack/lib/dependencies/NullDependency' { declare module.exports: any; } declare module 'webpack/lib/dependencies/NullDependencyTemplate' { declare module.exports: any; } declare module 'webpack/lib/dependencies/PrefetchDependency' { declare module.exports: any; } declare module 'webpack/lib/dependencies/RequireContextDependency' { declare module.exports: any; } declare module 'webpack/lib/dependencies/RequireContextDependencyParserPlugin' { declare module.exports: any; } declare module 'webpack/lib/dependencies/RequireContextPlugin' { declare module.exports: any; } declare module 'webpack/lib/dependencies/RequireEnsureDependenciesBlock' { declare module.exports: any; } declare module 'webpack/lib/dependencies/RequireEnsureDependenciesBlockParserPlugin' { declare module.exports: any; } declare module 'webpack/lib/dependencies/RequireEnsureDependency' { declare module.exports: any; } declare module 'webpack/lib/dependencies/RequireEnsureItemDependency' { declare module.exports: any; } declare module 'webpack/lib/dependencies/RequireEnsurePlugin' { declare module.exports: any; } declare module 'webpack/lib/dependencies/RequireHeaderDependency' { declare module.exports: any; } declare module 'webpack/lib/dependencies/RequireIncludeDependency' { declare module.exports: any; } declare module 'webpack/lib/dependencies/RequireIncludeDependencyParserPlugin' { declare module.exports: any; } declare module 'webpack/lib/dependencies/RequireIncludePlugin' { declare module.exports: any; } declare module 'webpack/lib/dependencies/RequireResolveContextDependency' { declare module.exports: any; } declare module 'webpack/lib/dependencies/RequireResolveDependency' { declare module.exports: any; } declare module 'webpack/lib/dependencies/RequireResolveDependencyParserPlugin' { declare module.exports: any; } declare module 'webpack/lib/dependencies/RequireResolveHeaderDependency' { declare module.exports: any; } declare module 'webpack/lib/dependencies/SingleEntryDependency' { declare module.exports: any; } declare module 'webpack/lib/dependencies/SystemImportContextDependency' { declare module.exports: any; } declare module 'webpack/lib/dependencies/SystemImportDependenciesBlock' { declare module.exports: any; } declare module 'webpack/lib/dependencies/SystemImportDependency' { declare module.exports: any; } declare module 'webpack/lib/dependencies/SystemImportParserPlugin' { declare module.exports: any; } declare module 'webpack/lib/dependencies/SystemPlugin' { declare module.exports: any; } declare module 'webpack/lib/dependencies/TemplateArgumentDependency' { declare module.exports: any; } declare module 'webpack/lib/dependencies/UnsupportedDependency' { declare module.exports: any; } declare module 'webpack/lib/dependencies/WebpackMissingModule' { declare module.exports: any; } declare module 'webpack/lib/DependenciesBlock' { declare module.exports: any; } declare module 'webpack/lib/DependenciesBlockVariable' { declare module.exports: any; } declare module 'webpack/lib/Dependency' { declare module.exports: any; } declare module 'webpack/lib/DllEntryPlugin' { declare module.exports: any; } declare module 'webpack/lib/DllModule' { declare module.exports: any; } declare module 'webpack/lib/DllModuleFactory' { declare module.exports: any; } declare module 'webpack/lib/DllPlugin' { declare module.exports: any; } declare module 'webpack/lib/DllReferencePlugin' { declare module.exports: any; } declare module 'webpack/lib/EntryModuleNotFoundError' { declare module.exports: any; } declare module 'webpack/lib/EntryOptionPlugin' { declare module.exports: any; } declare module 'webpack/lib/Entrypoint' { declare module.exports: any; } declare module 'webpack/lib/EnvironmentPlugin' { declare module.exports: any; } declare module 'webpack/lib/EvalDevToolModulePlugin' { declare module.exports: any; } declare module 'webpack/lib/EvalDevToolModuleTemplatePlugin' { declare module.exports: any; } declare module 'webpack/lib/EvalSourceMapDevToolModuleTemplatePlugin' { declare module.exports: any; } declare module 'webpack/lib/EvalSourceMapDevToolPlugin' { declare module.exports: any; } declare module 'webpack/lib/ExtendedAPIPlugin' { declare module.exports: any; } declare module 'webpack/lib/ExternalModule' { declare module.exports: any; } declare module 'webpack/lib/ExternalModuleFactoryPlugin' { declare module.exports: any; } declare module 'webpack/lib/ExternalsPlugin' { declare module.exports: any; } declare module 'webpack/lib/FlagDependencyExportsPlugin' { declare module.exports: any; } declare module 'webpack/lib/FlagDependencyUsagePlugin' { declare module.exports: any; } declare module 'webpack/lib/FlagInitialModulesAsUsedPlugin' { declare module.exports: any; } declare module 'webpack/lib/FunctionModulePlugin' { declare module.exports: any; } declare module 'webpack/lib/FunctionModuleTemplatePlugin' { declare module.exports: any; } declare module 'webpack/lib/HashedModuleIdsPlugin' { declare module.exports: any; } declare module 'webpack/lib/HotModuleReplacement.runtime' { declare module.exports: any; } declare module 'webpack/lib/HotModuleReplacementPlugin' { declare module.exports: any; } declare module 'webpack/lib/HotUpdateChunkTemplate' { declare module.exports: any; } declare module 'webpack/lib/IgnorePlugin' { declare module.exports: any; } declare module 'webpack/lib/JsonpChunkTemplatePlugin' { declare module.exports: any; } declare module 'webpack/lib/JsonpExportMainTemplatePlugin' { declare module.exports: any; } declare module 'webpack/lib/JsonpHotUpdateChunkTemplatePlugin' { declare module.exports: any; } declare module 'webpack/lib/JsonpMainTemplate.runtime' { declare module.exports: any; } declare module 'webpack/lib/JsonpMainTemplatePlugin' { declare module.exports: any; } declare module 'webpack/lib/JsonpTemplatePlugin' { declare module.exports: any; } declare module 'webpack/lib/LibManifestPlugin' { declare module.exports: any; } declare module 'webpack/lib/LibraryTemplatePlugin' { declare module.exports: any; } declare module 'webpack/lib/LoaderOptionsPlugin' { declare module.exports: any; } declare module 'webpack/lib/LoaderTargetPlugin' { declare module.exports: any; } declare module 'webpack/lib/MainTemplate' { declare module.exports: any; } declare module 'webpack/lib/MemoryOutputFileSystem' { declare module.exports: any; } declare module 'webpack/lib/Module' { declare module.exports: any; } declare module 'webpack/lib/ModuleBuildError' { declare module.exports: any; } declare module 'webpack/lib/ModuleDependencyWarning' { declare module.exports: any; } declare module 'webpack/lib/ModuleError' { declare module.exports: any; } declare module 'webpack/lib/ModuleFilenameHelpers' { declare module.exports: any; } declare module 'webpack/lib/ModuleNotFoundError' { declare module.exports: any; } declare module 'webpack/lib/ModuleParseError' { declare module.exports: any; } declare module 'webpack/lib/ModuleParserHelpers' { declare module.exports: any; } declare module 'webpack/lib/ModuleReason' { declare module.exports: any; } declare module 'webpack/lib/ModuleTemplate' { declare module.exports: any; } declare module 'webpack/lib/ModuleWarning' { declare module.exports: any; } declare module 'webpack/lib/MovedToPluginWarningPlugin' { declare module.exports: any; } declare module 'webpack/lib/MultiCompiler' { declare module.exports: any; } declare module 'webpack/lib/MultiEntryPlugin' { declare module.exports: any; } declare module 'webpack/lib/MultiModule' { declare module.exports: any; } declare module 'webpack/lib/MultiModuleFactory' { declare module.exports: any; } declare module 'webpack/lib/NamedModulesPlugin' { declare module.exports: any; } declare module 'webpack/lib/NewWatchingPlugin' { declare module.exports: any; } declare module 'webpack/lib/node/NodeChunkTemplatePlugin' { declare module.exports: any; } declare module 'webpack/lib/node/NodeEnvironmentPlugin' { declare module.exports: any; } declare module 'webpack/lib/node/NodeHotUpdateChunkTemplatePlugin' { declare module.exports: any; } declare module 'webpack/lib/node/NodeMainTemplate.runtime' { declare module.exports: any; } declare module 'webpack/lib/node/NodeMainTemplateAsync.runtime' { declare module.exports: any; } declare module 'webpack/lib/node/NodeMainTemplatePlugin' { declare module.exports: any; } declare module 'webpack/lib/node/NodeOutputFileSystem' { declare module.exports: any; } declare module 'webpack/lib/node/NodeSourcePlugin' { declare module.exports: any; } declare module 'webpack/lib/node/NodeTargetPlugin' { declare module.exports: any; } declare module 'webpack/lib/node/NodeTemplatePlugin' { declare module.exports: any; } declare module 'webpack/lib/node/NodeWatchFileSystem' { declare module.exports: any; } declare module 'webpack/lib/NodeStuffPlugin' { declare module.exports: any; } declare module 'webpack/lib/NoErrorsPlugin' { declare module.exports: any; } declare module 'webpack/lib/NormalModule' { declare module.exports: any; } declare module 'webpack/lib/NormalModuleFactory' { declare module.exports: any; } declare module 'webpack/lib/NormalModuleReplacementPlugin' { declare module.exports: any; } declare module 'webpack/lib/NullFactory' { declare module.exports: any; } declare module 'webpack/lib/optimize/AggressiveMergingPlugin' { declare module.exports: any; } declare module 'webpack/lib/optimize/AggressiveSplittingPlugin' { declare module.exports: any; } declare module 'webpack/lib/optimize/ChunkModuleIdRangePlugin' { declare module.exports: any; } declare module 'webpack/lib/optimize/CommonsChunkPlugin' { declare module.exports: any; } declare module 'webpack/lib/optimize/DedupePlugin' { declare module.exports: any; } declare module 'webpack/lib/optimize/EnsureChunkConditionsPlugin' { declare module.exports: any; } declare module 'webpack/lib/optimize/FlagIncludedChunksPlugin' { declare module.exports: any; } declare module 'webpack/lib/optimize/LimitChunkCountPlugin' { declare module.exports: any; } declare module 'webpack/lib/optimize/MergeDuplicateChunksPlugin' { declare module.exports: any; } declare module 'webpack/lib/optimize/MinChunkSizePlugin' { declare module.exports: any; } declare module 'webpack/lib/optimize/OccurrenceOrderPlugin' { declare module.exports: any; } declare module 'webpack/lib/optimize/RemoveEmptyChunksPlugin' { declare module.exports: any; } declare module 'webpack/lib/optimize/RemoveParentModulesPlugin' { declare module.exports: any; } declare module 'webpack/lib/optimize/UglifyJsPlugin' { declare module.exports: any; } declare module 'webpack/lib/OptionsApply' { declare module.exports: any; } declare module 'webpack/lib/OptionsDefaulter' { declare module.exports: any; } declare module 'webpack/lib/Parser' { declare module.exports: any; } declare module 'webpack/lib/PrefetchPlugin' { declare module.exports: any; } declare module 'webpack/lib/ProgressPlugin' { declare module.exports: any; } declare module 'webpack/lib/ProvidePlugin' { declare module.exports: any; } declare module 'webpack/lib/RawModule' { declare module.exports: any; } declare module 'webpack/lib/RecordIdsPlugin' { declare module.exports: any; } declare module 'webpack/lib/removeAndDo' { declare module.exports: any; } declare module 'webpack/lib/RequestShortener' { declare module.exports: any; } declare module 'webpack/lib/RequireJsStuffPlugin' { declare module.exports: any; } declare module 'webpack/lib/RuleSet' { declare module.exports: any; } declare module 'webpack/lib/SetVarMainTemplatePlugin' { declare module.exports: any; } declare module 'webpack/lib/SingleEntryPlugin' { declare module.exports: any; } declare module 'webpack/lib/SourceMapDevToolModuleOptionsPlugin' { declare module.exports: any; } declare module 'webpack/lib/SourceMapDevToolPlugin' { declare module.exports: any; } declare module 'webpack/lib/Stats' { declare module.exports: any; } declare module 'webpack/lib/Template' { declare module.exports: any; } declare module 'webpack/lib/TemplatedPathPlugin' { declare module.exports: any; } declare module 'webpack/lib/UmdMainTemplatePlugin' { declare module.exports: any; } declare module 'webpack/lib/UnsupportedFeatureWarning' { declare module.exports: any; } declare module 'webpack/lib/UseStrictPlugin' { declare module.exports: any; } declare module 'webpack/lib/validateWebpackOptions' { declare module.exports: any; } declare module 'webpack/lib/WarnCaseSensitiveModulesPlugin' { declare module.exports: any; } declare module 'webpack/lib/WatchIgnorePlugin' { declare module.exports: any; } declare module 'webpack/lib/web/WebEnvironmentPlugin' { declare module.exports: any; } declare module 'webpack/lib/webpack' { declare module.exports: any; } declare module 'webpack/lib/webpack.web' { declare module.exports: any; } declare module 'webpack/lib/WebpackOptionsApply' { declare module.exports: any; } declare module 'webpack/lib/WebpackOptionsDefaulter' { declare module.exports: any; } declare module 'webpack/lib/WebpackOptionsValidationError' { declare module.exports: any; } declare module 'webpack/lib/webworker/WebWorkerChunkTemplatePlugin' { declare module.exports: any; } declare module 'webpack/lib/webworker/WebWorkerHotUpdateChunkTemplatePlugin' { declare module.exports: any; } declare module 'webpack/lib/webworker/WebWorkerMainTemplate.runtime' { declare module.exports: any; } declare module 'webpack/lib/webworker/WebWorkerMainTemplatePlugin' { declare module.exports: any; } declare module 'webpack/lib/webworker/WebWorkerTemplatePlugin' { declare module.exports: any; } declare module 'webpack/web_modules/node-libs-browser' { declare module.exports: any; } // Filename aliases declare module 'webpack/bin/config-optimist.js' { declare module.exports: $Exports<'webpack/bin/config-optimist'>; } declare module 'webpack/bin/config-yargs.js' { declare module.exports: $Exports<'webpack/bin/config-yargs'>; } declare module 'webpack/bin/convert-argv.js' { declare module.exports: $Exports<'webpack/bin/convert-argv'>; } declare module 'webpack/bin/webpack.js' { declare module.exports: $Exports<'webpack/bin/webpack'>; } declare module 'webpack/buildin/amd-define.js' { declare module.exports: $Exports<'webpack/buildin/amd-define'>; } declare module 'webpack/buildin/amd-options.js' { declare module.exports: $Exports<'webpack/buildin/amd-options'>; } declare module 'webpack/buildin/global.js' { declare module.exports: $Exports<'webpack/buildin/global'>; } declare module 'webpack/buildin/module.js' { declare module.exports: $Exports<'webpack/buildin/module'>; } declare module 'webpack/buildin/return-require.js' { declare module.exports: $Exports<'webpack/buildin/return-require'>; } declare module 'webpack/hot/dev-server.js' { declare module.exports: $Exports<'webpack/hot/dev-server'>; } declare module 'webpack/hot/emitter.js' { declare module.exports: $Exports<'webpack/hot/emitter'>; } declare module 'webpack/hot/log-apply-result.js' { declare module.exports: $Exports<'webpack/hot/log-apply-result'>; } declare module 'webpack/hot/only-dev-server.js' { declare module.exports: $Exports<'webpack/hot/only-dev-server'>; } declare module 'webpack/hot/poll.js' { declare module.exports: $Exports<'webpack/hot/poll'>; } declare module 'webpack/hot/signal.js' { declare module.exports: $Exports<'webpack/hot/signal'>; } declare module 'webpack/lib/AbstractPlugin.js' { declare module.exports: $Exports<'webpack/lib/AbstractPlugin'>; } declare module 'webpack/lib/AmdMainTemplatePlugin.js' { declare module.exports: $Exports<'webpack/lib/AmdMainTemplatePlugin'>; } declare module 'webpack/lib/APIPlugin.js' { declare module.exports: $Exports<'webpack/lib/APIPlugin'>; } declare module 'webpack/lib/ArrayMap.js' { declare module.exports: $Exports<'webpack/lib/ArrayMap'>; } declare module 'webpack/lib/AsyncDependenciesBlock.js' { declare module.exports: $Exports<'webpack/lib/AsyncDependenciesBlock'>; } declare module 'webpack/lib/AutomaticPrefetchPlugin.js' { declare module.exports: $Exports<'webpack/lib/AutomaticPrefetchPlugin'>; } declare module 'webpack/lib/BannerPlugin.js' { declare module.exports: $Exports<'webpack/lib/BannerPlugin'>; } declare module 'webpack/lib/BasicEvaluatedExpression.js' { declare module.exports: $Exports<'webpack/lib/BasicEvaluatedExpression'>; } declare module 'webpack/lib/CachePlugin.js' { declare module.exports: $Exports<'webpack/lib/CachePlugin'>; } declare module 'webpack/lib/CaseSensitiveModulesWarning.js' { declare module.exports: $Exports<'webpack/lib/CaseSensitiveModulesWarning'>; } declare module 'webpack/lib/Chunk.js' { declare module.exports: $Exports<'webpack/lib/Chunk'>; } declare module 'webpack/lib/ChunkRenderError.js' { declare module.exports: $Exports<'webpack/lib/ChunkRenderError'>; } declare module 'webpack/lib/ChunkTemplate.js' { declare module.exports: $Exports<'webpack/lib/ChunkTemplate'>; } declare module 'webpack/lib/CommonJsHarmonyMainTemplatePlugin.js' { declare module.exports: $Exports<'webpack/lib/CommonJsHarmonyMainTemplatePlugin'>; } declare module 'webpack/lib/compareLocations.js' { declare module.exports: $Exports<'webpack/lib/compareLocations'>; } declare module 'webpack/lib/CompatibilityPlugin.js' { declare module.exports: $Exports<'webpack/lib/CompatibilityPlugin'>; } declare module 'webpack/lib/Compilation.js' { declare module.exports: $Exports<'webpack/lib/Compilation'>; } declare module 'webpack/lib/Compiler.js' { declare module.exports: $Exports<'webpack/lib/Compiler'>; } declare module 'webpack/lib/ConstPlugin.js' { declare module.exports: $Exports<'webpack/lib/ConstPlugin'>; } declare module 'webpack/lib/ContextModule.js' { declare module.exports: $Exports<'webpack/lib/ContextModule'>; } declare module 'webpack/lib/ContextModuleFactory.js' { declare module.exports: $Exports<'webpack/lib/ContextModuleFactory'>; } declare module 'webpack/lib/ContextReplacementPlugin.js' { declare module.exports: $Exports<'webpack/lib/ContextReplacementPlugin'>; } declare module 'webpack/lib/DefinePlugin.js' { declare module.exports: $Exports<'webpack/lib/DefinePlugin'>; } declare module 'webpack/lib/DelegatedModule.js' { declare module.exports: $Exports<'webpack/lib/DelegatedModule'>; } declare module 'webpack/lib/DelegatedModuleFactoryPlugin.js' { declare module.exports: $Exports<'webpack/lib/DelegatedModuleFactoryPlugin'>; } declare module 'webpack/lib/DelegatedPlugin.js' { declare module.exports: $Exports<'webpack/lib/DelegatedPlugin'>; } declare module 'webpack/lib/dependencies/AMDDefineDependency.js' { declare module.exports: $Exports<'webpack/lib/dependencies/AMDDefineDependency'>; } declare module 'webpack/lib/dependencies/AMDDefineDependencyParserPlugin.js' { declare module.exports: $Exports<'webpack/lib/dependencies/AMDDefineDependencyParserPlugin'>; } declare module 'webpack/lib/dependencies/AMDPlugin.js' { declare module.exports: $Exports<'webpack/lib/dependencies/AMDPlugin'>; } declare module 'webpack/lib/dependencies/AMDRequireArrayDependency.js' { declare module.exports: $Exports<'webpack/lib/dependencies/AMDRequireArrayDependency'>; } declare module 'webpack/lib/dependencies/AMDRequireContextDependency.js' { declare module.exports: $Exports<'webpack/lib/dependencies/AMDRequireContextDependency'>; } declare module 'webpack/lib/dependencies/AMDRequireDependenciesBlock.js' { declare module.exports: $Exports<'webpack/lib/dependencies/AMDRequireDependenciesBlock'>; } declare module 'webpack/lib/dependencies/AMDRequireDependenciesBlockParserPlugin.js' { declare module.exports: $Exports<'webpack/lib/dependencies/AMDRequireDependenciesBlockParserPlugin'>; } declare module 'webpack/lib/dependencies/AMDRequireDependency.js' { declare module.exports: $Exports<'webpack/lib/dependencies/AMDRequireDependency'>; } declare module 'webpack/lib/dependencies/AMDRequireItemDependency.js' { declare module.exports: $Exports<'webpack/lib/dependencies/AMDRequireItemDependency'>; } declare module 'webpack/lib/dependencies/CommonJsPlugin.js' { declare module.exports: $Exports<'webpack/lib/dependencies/CommonJsPlugin'>; } declare module 'webpack/lib/dependencies/CommonJsRequireContextDependency.js' { declare module.exports: $Exports<'webpack/lib/dependencies/CommonJsRequireContextDependency'>; } declare module 'webpack/lib/dependencies/CommonJsRequireDependency.js' { declare module.exports: $Exports<'webpack/lib/dependencies/CommonJsRequireDependency'>; } declare module 'webpack/lib/dependencies/CommonJsRequireDependencyParserPlugin.js' { declare module.exports: $Exports<'webpack/lib/dependencies/CommonJsRequireDependencyParserPlugin'>; } declare module 'webpack/lib/dependencies/ConstDependency.js' { declare module.exports: $Exports<'webpack/lib/dependencies/ConstDependency'>; } declare module 'webpack/lib/dependencies/ContextDependency.js' { declare module.exports: $Exports<'webpack/lib/dependencies/ContextDependency'>; } declare module 'webpack/lib/dependencies/ContextDependencyHelpers.js' { declare module.exports: $Exports<'webpack/lib/dependencies/ContextDependencyHelpers'>; } declare module 'webpack/lib/dependencies/ContextDependencyTemplateAsId.js' { declare module.exports: $Exports<'webpack/lib/dependencies/ContextDependencyTemplateAsId'>; } declare module 'webpack/lib/dependencies/ContextDependencyTemplateAsRequireCall.js' { declare module.exports: $Exports<'webpack/lib/dependencies/ContextDependencyTemplateAsRequireCall'>; } declare module 'webpack/lib/dependencies/ContextElementDependency.js' { declare module.exports: $Exports<'webpack/lib/dependencies/ContextElementDependency'>; } declare module 'webpack/lib/dependencies/CriticalDependencyWarning.js' { declare module.exports: $Exports<'webpack/lib/dependencies/CriticalDependencyWarning'>; } declare module 'webpack/lib/dependencies/DelegatedSourceDependency.js' { declare module.exports: $Exports<'webpack/lib/dependencies/DelegatedSourceDependency'>; } declare module 'webpack/lib/dependencies/DepBlockHelpers.js' { declare module.exports: $Exports<'webpack/lib/dependencies/DepBlockHelpers'>; } declare module 'webpack/lib/dependencies/DllEntryDependency.js' { declare module.exports: $Exports<'webpack/lib/dependencies/DllEntryDependency'>; } declare module 'webpack/lib/dependencies/getFunctionExpression.js' { declare module.exports: $Exports<'webpack/lib/dependencies/getFunctionExpression'>; } declare module 'webpack/lib/dependencies/HarmonyAcceptDependency.js' { declare module.exports: $Exports<'webpack/lib/dependencies/HarmonyAcceptDependency'>; } declare module 'webpack/lib/dependencies/HarmonyAcceptImportDependency.js' { declare module.exports: $Exports<'webpack/lib/dependencies/HarmonyAcceptImportDependency'>; } declare module 'webpack/lib/dependencies/HarmonyExportDependencyParserPlugin.js' { declare module.exports: $Exports<'webpack/lib/dependencies/HarmonyExportDependencyParserPlugin'>; } declare module 'webpack/lib/dependencies/HarmonyExportExpressionDependency.js' { declare module.exports: $Exports<'webpack/lib/dependencies/HarmonyExportExpressionDependency'>; } declare module 'webpack/lib/dependencies/HarmonyExportHeaderDependency.js' { declare module.exports: $Exports<'webpack/lib/dependencies/HarmonyExportHeaderDependency'>; } declare module 'webpack/lib/dependencies/HarmonyExportImportedSpecifierDependency.js' { declare module.exports: $Exports<'webpack/lib/dependencies/HarmonyExportImportedSpecifierDependency'>; } declare module 'webpack/lib/dependencies/HarmonyExportSpecifierDependency.js' { declare module.exports: $Exports<'webpack/lib/dependencies/HarmonyExportSpecifierDependency'>; } declare module 'webpack/lib/dependencies/HarmonyImportDependency.js' { declare module.exports: $Exports<'webpack/lib/dependencies/HarmonyImportDependency'>; } declare module 'webpack/lib/dependencies/HarmonyImportDependencyParserPlugin.js' { declare module.exports: $Exports<'webpack/lib/dependencies/HarmonyImportDependencyParserPlugin'>; } declare module 'webpack/lib/dependencies/HarmonyImportSpecifierDependency.js' { declare module.exports: $Exports<'webpack/lib/dependencies/HarmonyImportSpecifierDependency'>; } declare module 'webpack/lib/dependencies/HarmonyModulesHelpers.js' { declare module.exports: $Exports<'webpack/lib/dependencies/HarmonyModulesHelpers'>; } declare module 'webpack/lib/dependencies/HarmonyModulesPlugin.js' { declare module.exports: $Exports<'webpack/lib/dependencies/HarmonyModulesPlugin'>; } declare module 'webpack/lib/dependencies/LoaderDependency.js' { declare module.exports: $Exports<'webpack/lib/dependencies/LoaderDependency'>; } declare module 'webpack/lib/dependencies/LoaderPlugin.js' { declare module.exports: $Exports<'webpack/lib/dependencies/LoaderPlugin'>; } declare module 'webpack/lib/dependencies/LocalModule.js' { declare module.exports: $Exports<'webpack/lib/dependencies/LocalModule'>; } declare module 'webpack/lib/dependencies/LocalModuleDependency.js' { declare module.exports: $Exports<'webpack/lib/dependencies/LocalModuleDependency'>; } declare module 'webpack/lib/dependencies/LocalModulesHelpers.js' { declare module.exports: $Exports<'webpack/lib/dependencies/LocalModulesHelpers'>; } declare module 'webpack/lib/dependencies/ModuleDependency.js' { declare module.exports: $Exports<'webpack/lib/dependencies/ModuleDependency'>; } declare module 'webpack/lib/dependencies/ModuleDependencyTemplateAsId.js' { declare module.exports: $Exports<'webpack/lib/dependencies/ModuleDependencyTemplateAsId'>; } declare module 'webpack/lib/dependencies/ModuleDependencyTemplateAsRequireId.js' { declare module.exports: $Exports<'webpack/lib/dependencies/ModuleDependencyTemplateAsRequireId'>; } declare module 'webpack/lib/dependencies/ModuleHotAcceptDependency.js' { declare module.exports: $Exports<'webpack/lib/dependencies/ModuleHotAcceptDependency'>; } declare module 'webpack/lib/dependencies/ModuleHotDeclineDependency.js' { declare module.exports: $Exports<'webpack/lib/dependencies/ModuleHotDeclineDependency'>; } declare module 'webpack/lib/dependencies/MultiEntryDependency.js' { declare module.exports: $Exports<'webpack/lib/dependencies/MultiEntryDependency'>; } declare module 'webpack/lib/dependencies/NullDependency.js' { declare module.exports: $Exports<'webpack/lib/dependencies/NullDependency'>; } declare module 'webpack/lib/dependencies/NullDependencyTemplate.js' { declare module.exports: $Exports<'webpack/lib/dependencies/NullDependencyTemplate'>; } declare module 'webpack/lib/dependencies/PrefetchDependency.js' { declare module.exports: $Exports<'webpack/lib/dependencies/PrefetchDependency'>; } declare module 'webpack/lib/dependencies/RequireContextDependency.js' { declare module.exports: $Exports<'webpack/lib/dependencies/RequireContextDependency'>; } declare module 'webpack/lib/dependencies/RequireContextDependencyParserPlugin.js' { declare module.exports: $Exports<'webpack/lib/dependencies/RequireContextDependencyParserPlugin'>; } declare module 'webpack/lib/dependencies/RequireContextPlugin.js' { declare module.exports: $Exports<'webpack/lib/dependencies/RequireContextPlugin'>; } declare module 'webpack/lib/dependencies/RequireEnsureDependenciesBlock.js' { declare module.exports: $Exports<'webpack/lib/dependencies/RequireEnsureDependenciesBlock'>; } declare module 'webpack/lib/dependencies/RequireEnsureDependenciesBlockParserPlugin.js' { declare module.exports: $Exports<'webpack/lib/dependencies/RequireEnsureDependenciesBlockParserPlugin'>; } declare module 'webpack/lib/dependencies/RequireEnsureDependency.js' { declare module.exports: $Exports<'webpack/lib/dependencies/RequireEnsureDependency'>; } declare module 'webpack/lib/dependencies/RequireEnsureItemDependency.js' { declare module.exports: $Exports<'webpack/lib/dependencies/RequireEnsureItemDependency'>; } declare module 'webpack/lib/dependencies/RequireEnsurePlugin.js' { declare module.exports: $Exports<'webpack/lib/dependencies/RequireEnsurePlugin'>; } declare module 'webpack/lib/dependencies/RequireHeaderDependency.js' { declare module.exports: $Exports<'webpack/lib/dependencies/RequireHeaderDependency'>; } declare module 'webpack/lib/dependencies/RequireIncludeDependency.js' { declare module.exports: $Exports<'webpack/lib/dependencies/RequireIncludeDependency'>; } declare module 'webpack/lib/dependencies/RequireIncludeDependencyParserPlugin.js' { declare module.exports: $Exports<'webpack/lib/dependencies/RequireIncludeDependencyParserPlugin'>; } declare module 'webpack/lib/dependencies/RequireIncludePlugin.js' { declare module.exports: $Exports<'webpack/lib/dependencies/RequireIncludePlugin'>; } declare module 'webpack/lib/dependencies/RequireResolveContextDependency.js' { declare module.exports: $Exports<'webpack/lib/dependencies/RequireResolveContextDependency'>; } declare module 'webpack/lib/dependencies/RequireResolveDependency.js' { declare module.exports: $Exports<'webpack/lib/dependencies/RequireResolveDependency'>; } declare module 'webpack/lib/dependencies/RequireResolveDependencyParserPlugin.js' { declare module.exports: $Exports<'webpack/lib/dependencies/RequireResolveDependencyParserPlugin'>; } declare module 'webpack/lib/dependencies/RequireResolveHeaderDependency.js' { declare module.exports: $Exports<'webpack/lib/dependencies/RequireResolveHeaderDependency'>; } declare module 'webpack/lib/dependencies/SingleEntryDependency.js' { declare module.exports: $Exports<'webpack/lib/dependencies/SingleEntryDependency'>; } declare module 'webpack/lib/dependencies/SystemImportContextDependency.js' { declare module.exports: $Exports<'webpack/lib/dependencies/SystemImportContextDependency'>; } declare module 'webpack/lib/dependencies/SystemImportDependenciesBlock.js' { declare module.exports: $Exports<'webpack/lib/dependencies/SystemImportDependenciesBlock'>; } declare module 'webpack/lib/dependencies/SystemImportDependency.js' { declare module.exports: $Exports<'webpack/lib/dependencies/SystemImportDependency'>; } declare module 'webpack/lib/dependencies/SystemImportParserPlugin.js' { declare module.exports: $Exports<'webpack/lib/dependencies/SystemImportParserPlugin'>; } declare module 'webpack/lib/dependencies/SystemPlugin.js' { declare module.exports: $Exports<'webpack/lib/dependencies/SystemPlugin'>; } declare module 'webpack/lib/dependencies/TemplateArgumentDependency.js' { declare module.exports: $Exports<'webpack/lib/dependencies/TemplateArgumentDependency'>; } declare module 'webpack/lib/dependencies/UnsupportedDependency.js' { declare module.exports: $Exports<'webpack/lib/dependencies/UnsupportedDependency'>; } declare module 'webpack/lib/dependencies/WebpackMissingModule.js' { declare module.exports: $Exports<'webpack/lib/dependencies/WebpackMissingModule'>; } declare module 'webpack/lib/DependenciesBlock.js' { declare module.exports: $Exports<'webpack/lib/DependenciesBlock'>; } declare module 'webpack/lib/DependenciesBlockVariable.js' { declare module.exports: $Exports<'webpack/lib/DependenciesBlockVariable'>; } declare module 'webpack/lib/Dependency.js' { declare module.exports: $Exports<'webpack/lib/Dependency'>; } declare module 'webpack/lib/DllEntryPlugin.js' { declare module.exports: $Exports<'webpack/lib/DllEntryPlugin'>; } declare module 'webpack/lib/DllModule.js' { declare module.exports: $Exports<'webpack/lib/DllModule'>; } declare module 'webpack/lib/DllModuleFactory.js' { declare module.exports: $Exports<'webpack/lib/DllModuleFactory'>; } declare module 'webpack/lib/DllPlugin.js' { declare module.exports: $Exports<'webpack/lib/DllPlugin'>; } declare module 'webpack/lib/DllReferencePlugin.js' { declare module.exports: $Exports<'webpack/lib/DllReferencePlugin'>; } declare module 'webpack/lib/EntryModuleNotFoundError.js' { declare module.exports: $Exports<'webpack/lib/EntryModuleNotFoundError'>; } declare module 'webpack/lib/EntryOptionPlugin.js' { declare module.exports: $Exports<'webpack/lib/EntryOptionPlugin'>; } declare module 'webpack/lib/Entrypoint.js' { declare module.exports: $Exports<'webpack/lib/Entrypoint'>; } declare module 'webpack/lib/EnvironmentPlugin.js' { declare module.exports: $Exports<'webpack/lib/EnvironmentPlugin'>; } declare module 'webpack/lib/EvalDevToolModulePlugin.js' { declare module.exports: $Exports<'webpack/lib/EvalDevToolModulePlugin'>; } declare module 'webpack/lib/EvalDevToolModuleTemplatePlugin.js' { declare module.exports: $Exports<'webpack/lib/EvalDevToolModuleTemplatePlugin'>; } declare module 'webpack/lib/EvalSourceMapDevToolModuleTemplatePlugin.js' { declare module.exports: $Exports<'webpack/lib/EvalSourceMapDevToolModuleTemplatePlugin'>; } declare module 'webpack/lib/EvalSourceMapDevToolPlugin.js' { declare module.exports: $Exports<'webpack/lib/EvalSourceMapDevToolPlugin'>; } declare module 'webpack/lib/ExtendedAPIPlugin.js' { declare module.exports: $Exports<'webpack/lib/ExtendedAPIPlugin'>; } declare module 'webpack/lib/ExternalModule.js' { declare module.exports: $Exports<'webpack/lib/ExternalModule'>; } declare module 'webpack/lib/ExternalModuleFactoryPlugin.js' { declare module.exports: $Exports<'webpack/lib/ExternalModuleFactoryPlugin'>; } declare module 'webpack/lib/ExternalsPlugin.js' { declare module.exports: $Exports<'webpack/lib/ExternalsPlugin'>; } declare module 'webpack/lib/FlagDependencyExportsPlugin.js' { declare module.exports: $Exports<'webpack/lib/FlagDependencyExportsPlugin'>; } declare module 'webpack/lib/FlagDependencyUsagePlugin.js' { declare module.exports: $Exports<'webpack/lib/FlagDependencyUsagePlugin'>; } declare module 'webpack/lib/FlagInitialModulesAsUsedPlugin.js' { declare module.exports: $Exports<'webpack/lib/FlagInitialModulesAsUsedPlugin'>; } declare module 'webpack/lib/FunctionModulePlugin.js' { declare module.exports: $Exports<'webpack/lib/FunctionModulePlugin'>; } declare module 'webpack/lib/FunctionModuleTemplatePlugin.js' { declare module.exports: $Exports<'webpack/lib/FunctionModuleTemplatePlugin'>; } declare module 'webpack/lib/HashedModuleIdsPlugin.js' { declare module.exports: $Exports<'webpack/lib/HashedModuleIdsPlugin'>; } declare module 'webpack/lib/HotModuleReplacement.runtime.js' { declare module.exports: $Exports<'webpack/lib/HotModuleReplacement.runtime'>; } declare module 'webpack/lib/HotModuleReplacementPlugin.js' { declare module.exports: $Exports<'webpack/lib/HotModuleReplacementPlugin'>; } declare module 'webpack/lib/HotUpdateChunkTemplate.js' { declare module.exports: $Exports<'webpack/lib/HotUpdateChunkTemplate'>; } declare module 'webpack/lib/IgnorePlugin.js' { declare module.exports: $Exports<'webpack/lib/IgnorePlugin'>; } declare module 'webpack/lib/JsonpChunkTemplatePlugin.js' { declare module.exports: $Exports<'webpack/lib/JsonpChunkTemplatePlugin'>; } declare module 'webpack/lib/JsonpExportMainTemplatePlugin.js' { declare module.exports: $Exports<'webpack/lib/JsonpExportMainTemplatePlugin'>; } declare module 'webpack/lib/JsonpHotUpdateChunkTemplatePlugin.js' { declare module.exports: $Exports<'webpack/lib/JsonpHotUpdateChunkTemplatePlugin'>; } declare module 'webpack/lib/JsonpMainTemplate.runtime.js' { declare module.exports: $Exports<'webpack/lib/JsonpMainTemplate.runtime'>; } declare module 'webpack/lib/JsonpMainTemplatePlugin.js' { declare module.exports: $Exports<'webpack/lib/JsonpMainTemplatePlugin'>; } declare module 'webpack/lib/JsonpTemplatePlugin.js' { declare module.exports: $Exports<'webpack/lib/JsonpTemplatePlugin'>; } declare module 'webpack/lib/LibManifestPlugin.js' { declare module.exports: $Exports<'webpack/lib/LibManifestPlugin'>; } declare module 'webpack/lib/LibraryTemplatePlugin.js' { declare module.exports: $Exports<'webpack/lib/LibraryTemplatePlugin'>; } declare module 'webpack/lib/LoaderOptionsPlugin.js' { declare module.exports: $Exports<'webpack/lib/LoaderOptionsPlugin'>; } declare module 'webpack/lib/LoaderTargetPlugin.js' { declare module.exports: $Exports<'webpack/lib/LoaderTargetPlugin'>; } declare module 'webpack/lib/MainTemplate.js' { declare module.exports: $Exports<'webpack/lib/MainTemplate'>; } declare module 'webpack/lib/MemoryOutputFileSystem.js' { declare module.exports: $Exports<'webpack/lib/MemoryOutputFileSystem'>; } declare module 'webpack/lib/Module.js' { declare module.exports: $Exports<'webpack/lib/Module'>; } declare module 'webpack/lib/ModuleBuildError.js' { declare module.exports: $Exports<'webpack/lib/ModuleBuildError'>; } declare module 'webpack/lib/ModuleDependencyWarning.js' { declare module.exports: $Exports<'webpack/lib/ModuleDependencyWarning'>; } declare module 'webpack/lib/ModuleError.js' { declare module.exports: $Exports<'webpack/lib/ModuleError'>; } declare module 'webpack/lib/ModuleFilenameHelpers.js' { declare module.exports: $Exports<'webpack/lib/ModuleFilenameHelpers'>; } declare module 'webpack/lib/ModuleNotFoundError.js' { declare module.exports: $Exports<'webpack/lib/ModuleNotFoundError'>; } declare module 'webpack/lib/ModuleParseError.js' { declare module.exports: $Exports<'webpack/lib/ModuleParseError'>; } declare module 'webpack/lib/ModuleParserHelpers.js' { declare module.exports: $Exports<'webpack/lib/ModuleParserHelpers'>; } declare module 'webpack/lib/ModuleReason.js' { declare module.exports: $Exports<'webpack/lib/ModuleReason'>; } declare module 'webpack/lib/ModuleTemplate.js' { declare module.exports: $Exports<'webpack/lib/ModuleTemplate'>; } declare module 'webpack/lib/ModuleWarning.js' { declare module.exports: $Exports<'webpack/lib/ModuleWarning'>; } declare module 'webpack/lib/MovedToPluginWarningPlugin.js' { declare module.exports: $Exports<'webpack/lib/MovedToPluginWarningPlugin'>; } declare module 'webpack/lib/MultiCompiler.js' { declare module.exports: $Exports<'webpack/lib/MultiCompiler'>; } declare module 'webpack/lib/MultiEntryPlugin.js' { declare module.exports: $Exports<'webpack/lib/MultiEntryPlugin'>; } declare module 'webpack/lib/MultiModule.js' { declare module.exports: $Exports<'webpack/lib/MultiModule'>; } declare module 'webpack/lib/MultiModuleFactory.js' { declare module.exports: $Exports<'webpack/lib/MultiModuleFactory'>; } declare module 'webpack/lib/NamedModulesPlugin.js' { declare module.exports: $Exports<'webpack/lib/NamedModulesPlugin'>; } declare module 'webpack/lib/NewWatchingPlugin.js' { declare module.exports: $Exports<'webpack/lib/NewWatchingPlugin'>; } declare module 'webpack/lib/node/NodeChunkTemplatePlugin.js' { declare module.exports: $Exports<'webpack/lib/node/NodeChunkTemplatePlugin'>; } declare module 'webpack/lib/node/NodeEnvironmentPlugin.js' { declare module.exports: $Exports<'webpack/lib/node/NodeEnvironmentPlugin'>; } declare module 'webpack/lib/node/NodeHotUpdateChunkTemplatePlugin.js' { declare module.exports: $Exports<'webpack/lib/node/NodeHotUpdateChunkTemplatePlugin'>; } declare module 'webpack/lib/node/NodeMainTemplate.runtime.js' { declare module.exports: $Exports<'webpack/lib/node/NodeMainTemplate.runtime'>; } declare module 'webpack/lib/node/NodeMainTemplateAsync.runtime.js' { declare module.exports: $Exports<'webpack/lib/node/NodeMainTemplateAsync.runtime'>; } declare module 'webpack/lib/node/NodeMainTemplatePlugin.js' { declare module.exports: $Exports<'webpack/lib/node/NodeMainTemplatePlugin'>; } declare module 'webpack/lib/node/NodeOutputFileSystem.js' { declare module.exports: $Exports<'webpack/lib/node/NodeOutputFileSystem'>; } declare module 'webpack/lib/node/NodeSourcePlugin.js' { declare module.exports: $Exports<'webpack/lib/node/NodeSourcePlugin'>; } declare module 'webpack/lib/node/NodeTargetPlugin.js' { declare module.exports: $Exports<'webpack/lib/node/NodeTargetPlugin'>; } declare module 'webpack/lib/node/NodeTemplatePlugin.js' { declare module.exports: $Exports<'webpack/lib/node/NodeTemplatePlugin'>; } declare module 'webpack/lib/node/NodeWatchFileSystem.js' { declare module.exports: $Exports<'webpack/lib/node/NodeWatchFileSystem'>; } declare module 'webpack/lib/NodeStuffPlugin.js' { declare module.exports: $Exports<'webpack/lib/NodeStuffPlugin'>; } declare module 'webpack/lib/NoErrorsPlugin.js' { declare module.exports: $Exports<'webpack/lib/NoErrorsPlugin'>; } declare module 'webpack/lib/NormalModule.js' { declare module.exports: $Exports<'webpack/lib/NormalModule'>; } declare module 'webpack/lib/NormalModuleFactory.js' { declare module.exports: $Exports<'webpack/lib/NormalModuleFactory'>; } declare module 'webpack/lib/NormalModuleReplacementPlugin.js' { declare module.exports: $Exports<'webpack/lib/NormalModuleReplacementPlugin'>; } declare module 'webpack/lib/NullFactory.js' { declare module.exports: $Exports<'webpack/lib/NullFactory'>; } declare module 'webpack/lib/optimize/AggressiveMergingPlugin.js' { declare module.exports: $Exports<'webpack/lib/optimize/AggressiveMergingPlugin'>; } declare module 'webpack/lib/optimize/AggressiveSplittingPlugin.js' { declare module.exports: $Exports<'webpack/lib/optimize/AggressiveSplittingPlugin'>; } declare module 'webpack/lib/optimize/ChunkModuleIdRangePlugin.js' { declare module.exports: $Exports<'webpack/lib/optimize/ChunkModuleIdRangePlugin'>; } declare module 'webpack/lib/optimize/CommonsChunkPlugin.js' { declare module.exports: $Exports<'webpack/lib/optimize/CommonsChunkPlugin'>; } declare module 'webpack/lib/optimize/DedupePlugin.js' { declare module.exports: $Exports<'webpack/lib/optimize/DedupePlugin'>; } declare module 'webpack/lib/optimize/EnsureChunkConditionsPlugin.js' { declare module.exports: $Exports<'webpack/lib/optimize/EnsureChunkConditionsPlugin'>; } declare module 'webpack/lib/optimize/FlagIncludedChunksPlugin.js' { declare module.exports: $Exports<'webpack/lib/optimize/FlagIncludedChunksPlugin'>; } declare module 'webpack/lib/optimize/LimitChunkCountPlugin.js' { declare module.exports: $Exports<'webpack/lib/optimize/LimitChunkCountPlugin'>; } declare module 'webpack/lib/optimize/MergeDuplicateChunksPlugin.js' { declare module.exports: $Exports<'webpack/lib/optimize/MergeDuplicateChunksPlugin'>; } declare module 'webpack/lib/optimize/MinChunkSizePlugin.js' { declare module.exports: $Exports<'webpack/lib/optimize/MinChunkSizePlugin'>; } declare module 'webpack/lib/optimize/OccurrenceOrderPlugin.js' { declare module.exports: $Exports<'webpack/lib/optimize/OccurrenceOrderPlugin'>; } declare module 'webpack/lib/optimize/RemoveEmptyChunksPlugin.js' { declare module.exports: $Exports<'webpack/lib/optimize/RemoveEmptyChunksPlugin'>; } declare module 'webpack/lib/optimize/RemoveParentModulesPlugin.js' { declare module.exports: $Exports<'webpack/lib/optimize/RemoveParentModulesPlugin'>; } declare module 'webpack/lib/optimize/UglifyJsPlugin.js' { declare module.exports: $Exports<'webpack/lib/optimize/UglifyJsPlugin'>; } declare module 'webpack/lib/OptionsApply.js' { declare module.exports: $Exports<'webpack/lib/OptionsApply'>; } declare module 'webpack/lib/OptionsDefaulter.js' { declare module.exports: $Exports<'webpack/lib/OptionsDefaulter'>; } declare module 'webpack/lib/Parser.js' { declare module.exports: $Exports<'webpack/lib/Parser'>; } declare module 'webpack/lib/PrefetchPlugin.js' { declare module.exports: $Exports<'webpack/lib/PrefetchPlugin'>; } declare module 'webpack/lib/ProgressPlugin.js' { declare module.exports: $Exports<'webpack/lib/ProgressPlugin'>; } declare module 'webpack/lib/ProvidePlugin.js' { declare module.exports: $Exports<'webpack/lib/ProvidePlugin'>; } declare module 'webpack/lib/RawModule.js' { declare module.exports: $Exports<'webpack/lib/RawModule'>; } declare module 'webpack/lib/RecordIdsPlugin.js' { declare module.exports: $Exports<'webpack/lib/RecordIdsPlugin'>; } declare module 'webpack/lib/removeAndDo.js' { declare module.exports: $Exports<'webpack/lib/removeAndDo'>; } declare module 'webpack/lib/RequestShortener.js' { declare module.exports: $Exports<'webpack/lib/RequestShortener'>; } declare module 'webpack/lib/RequireJsStuffPlugin.js' { declare module.exports: $Exports<'webpack/lib/RequireJsStuffPlugin'>; } declare module 'webpack/lib/RuleSet.js' { declare module.exports: $Exports<'webpack/lib/RuleSet'>; } declare module 'webpack/lib/SetVarMainTemplatePlugin.js' { declare module.exports: $Exports<'webpack/lib/SetVarMainTemplatePlugin'>; } declare module 'webpack/lib/SingleEntryPlugin.js' { declare module.exports: $Exports<'webpack/lib/SingleEntryPlugin'>; } declare module 'webpack/lib/SourceMapDevToolModuleOptionsPlugin.js' { declare module.exports: $Exports<'webpack/lib/SourceMapDevToolModuleOptionsPlugin'>; } declare module 'webpack/lib/SourceMapDevToolPlugin.js' { declare module.exports: $Exports<'webpack/lib/SourceMapDevToolPlugin'>; } declare module 'webpack/lib/Stats.js' { declare module.exports: $Exports<'webpack/lib/Stats'>; } declare module 'webpack/lib/Template.js' { declare module.exports: $Exports<'webpack/lib/Template'>; } declare module 'webpack/lib/TemplatedPathPlugin.js' { declare module.exports: $Exports<'webpack/lib/TemplatedPathPlugin'>; } declare module 'webpack/lib/UmdMainTemplatePlugin.js' { declare module.exports: $Exports<'webpack/lib/UmdMainTemplatePlugin'>; } declare module 'webpack/lib/UnsupportedFeatureWarning.js' { declare module.exports: $Exports<'webpack/lib/UnsupportedFeatureWarning'>; } declare module 'webpack/lib/UseStrictPlugin.js' { declare module.exports: $Exports<'webpack/lib/UseStrictPlugin'>; } declare module 'webpack/lib/validateWebpackOptions.js' { declare module.exports: $Exports<'webpack/lib/validateWebpackOptions'>; } declare module 'webpack/lib/WarnCaseSensitiveModulesPlugin.js' { declare module.exports: $Exports<'webpack/lib/WarnCaseSensitiveModulesPlugin'>; } declare module 'webpack/lib/WatchIgnorePlugin.js' { declare module.exports: $Exports<'webpack/lib/WatchIgnorePlugin'>; } declare module 'webpack/lib/web/WebEnvironmentPlugin.js' { declare module.exports: $Exports<'webpack/lib/web/WebEnvironmentPlugin'>; } declare module 'webpack/lib/webpack.js' { declare module.exports: $Exports<'webpack/lib/webpack'>; } declare module 'webpack/lib/webpack.web.js' { declare module.exports: $Exports<'webpack/lib/webpack.web'>; } declare module 'webpack/lib/WebpackOptionsApply.js' { declare module.exports: $Exports<'webpack/lib/WebpackOptionsApply'>; } declare module 'webpack/lib/WebpackOptionsDefaulter.js' { declare module.exports: $Exports<'webpack/lib/WebpackOptionsDefaulter'>; } declare module 'webpack/lib/WebpackOptionsValidationError.js' { declare module.exports: $Exports<'webpack/lib/WebpackOptionsValidationError'>; } declare module 'webpack/lib/webworker/WebWorkerChunkTemplatePlugin.js' { declare module.exports: $Exports<'webpack/lib/webworker/WebWorkerChunkTemplatePlugin'>; } declare module 'webpack/lib/webworker/WebWorkerHotUpdateChunkTemplatePlugin.js' { declare module.exports: $Exports<'webpack/lib/webworker/WebWorkerHotUpdateChunkTemplatePlugin'>; } declare module 'webpack/lib/webworker/WebWorkerMainTemplate.runtime.js' { declare module.exports: $Exports<'webpack/lib/webworker/WebWorkerMainTemplate.runtime'>; } declare module 'webpack/lib/webworker/WebWorkerMainTemplatePlugin.js' { declare module.exports: $Exports<'webpack/lib/webworker/WebWorkerMainTemplatePlugin'>; } declare module 'webpack/lib/webworker/WebWorkerTemplatePlugin.js' { declare module.exports: $Exports<'webpack/lib/webworker/WebWorkerTemplatePlugin'>; } declare module 'webpack/web_modules/node-libs-browser.js' { declare module.exports: $Exports<'webpack/web_modules/node-libs-browser'>; }
angular.module('gamilms_directives', []) .directive('gamiUnit', ['$gamiEvent', function($gamiEvent) { return { restrict: 'AE', // scope:{ // $uibModalInstance: '&' // }, link: function($scope, $element, $attr) { //$element.context.textContent = $gamiEvent.gaminum(); $scope.gamiEmit = function() { $gamiEvent.open_modal($gamiEvent.MODEL_CONFIG); }; $scope.badge_info = function(index) { $gamiEvent.CHALLENGE_INFO = { challenge_title: $attr.badgeName, challenge_content: $attr.badgeInfo, challenge_img: $attr.badgeUrl }; $gamiEvent.MODEL_CONFIG.templateUrl = $gamiEvent.project_name + '/template/challenge.html'; $gamiEvent.MODEL_CONFIG.controller = 'ChallengeCtrl'; $gamiEvent.open_modal($gamiEvent.MODEL_CONFIG); }; $scope.gamiEmit_badge = function(_badge) { var temp_badge_info = ''; $gamiEvent.update_badge('first_see_badge', function() {}); $gamiEvent.CHALLENGE_INFO = { challenge_title: _badge.name, challenge_content: '獲得' + _badge.value + '次', challenge_img: _badge.image }; $gamiEvent.MODEL_CONFIG.templateUrl = $gamiEvent.project_name + '/template/challenge.html'; $gamiEvent.MODEL_CONFIG.controller = 'ChallengeCtrl'; $gamiEvent.open_modal($gamiEvent.MODEL_CONFIG); }; $scope.gamiEmit_log = function(_log) { $gamiEvent.update_badge('first_see_loglist', function() {}); $gamiEvent.CHALLENGE_INFO = { challenge_title: _log.event_name, challenge_content: _log.timestamp, challenge_img: _log.image }; $gamiEvent.MODEL_CONFIG.templateUrl = $gamiEvent.project_name + '/template/challenge.html'; $gamiEvent.MODEL_CONFIG.controller = 'ChallengeCtrl'; $gamiEvent.open_modal($gamiEvent.MODEL_CONFIG); }; // console.log($gamiEvent); // console.log('gami-unit'); // console.log($scope); // console.log($element); // console.log($attr); } }; }]);
import React, { Component } from 'react'; import Helmet from 'react-helmet'; import { config } from 'config'; import { Link } from 'react-router'; import { prefixLink } from 'gatsby-helpers'; class Enter extends Component { constructor(props) { super(props); this.state = { visible: true, fade: false }; this._handleClick = this._handleClick.bind(this); } _handleClick(e) { e.preventDefault(); this.setState({ fade: true }); setTimeout(() => { this.setState({ visible: false }) }, 255); } render() { if (this.state.visible) { return ( <div className="page--enter" style={{ backgroundImage: `url("${prefixLink('/images/AC.png')}")`, opacity: this.state.fade ? 0 : 1 }} onClick={this._handleClick} > {} <div className="enter"> - click to enter - <div className="spinnerHolder"> <div className="spinner"></div> <div className="spinner2"></div> </div> </div> </div> ); } return null; } } export default class Home extends Component { render () { return ( <div className="page"> <Helmet title="Ariel Chen" /> <Enter /> <div className="section--1"> <div className="image--circle-side"> <a href="https://github.com/arielmchen" target="_blank"> <img src ={prefixLink('/images/gh.png')}/> </a> </div> <div className="image--circle-side"> <a href="https://www.linkedin.com/in/arielmchen" target="_blank"> <img src ={prefixLink('/images/li.png')}/> </a> </div> <div className="image--circle-main"> <img src ={prefixLink('/images/hopefully.gif')}/> </div> <div className="image--circle-side"> <a href="mailto:arielchen@berkeley.edu"> <img src ={prefixLink('/images/em.png')}/> </a> </div> <div className="image--circle-side"> <a href={prefixLink('ArielChen_Res.pdf')} download="ArielChen_Resume"> <img src ={prefixLink('/images/dl.png')}/> </a> </div> <div className="details"> <div className="about"> Hi! I'm a third year at UC Berkeley studying Cognitive Science with a focus in <a className="notice" href="https://arielmchen.carbonmade.com/" target="_blank">design</a> and Computer Science. My interests include hiking, trying new foods, and going on adventures. </div> </div> </div> </div> ); } }
goog.provide('ol.webgl'); goog.provide('ol.webgl.WebGLContextEventType'); /** * @const * @private * @type {Array.<string>} */ ol.webgl.CONTEXT_IDS_ = [ 'experimental-webgl', 'webgl', 'webkit-3d', 'moz-webgl' ]; /** * @enum {string} */ ol.webgl.WebGLContextEventType = { LOST: 'webglcontextlost', RESTORED: 'webglcontextrestored' }; /** * @param {HTMLCanvasElement} canvas Canvas. * @param {Object=} opt_attributes Attributes. * @return {WebGLRenderingContext} WebGL rendering context. */ ol.webgl.getContext = function(canvas, opt_attributes) { var context, i, ii = ol.webgl.CONTEXT_IDS_.length; for (i = 0; i < ii; ++i) { try { context = canvas.getContext(ol.webgl.CONTEXT_IDS_[i], opt_attributes); if (!goog.isNull(context)) { return /** @type {!WebGLRenderingContext} */ (context); } } catch (e) { } } return null; };
const phrases = require('./../phrases') const smsProcessor = require('./../smsprocessor') const stringProcessor = require('./../stringprocessor') const Q = require('q') const logger = require('winston') const processResponseTextPromise = (data) => { let uncasedMessage = stringProcessor.stringToWords(data.originalTextCased).splice(3).join(' ') let replaceNewLines = uncasedMessage.replace(/@@/g, '\n') console.log(replaceNewLines) data.sendText = replaceNewLines return sendSms(data) .then(result => { data.responseText = phrases.success return data }) } // TODO: refactor this... duplicate code const sendSms = data => { logger.log('debug', '___.textprocessor_sendSms', data) const sendMultipleSmsPromises = data.phoneNumbers.map(phoneNumber => { logger.log('debug', 'loop') return smsProcessor.sendSmsPromise(data, phoneNumber, data.sendText) }) return Q.all(sendMultipleSmsPromises) } module.exports = { processResponseTextPromise }
import Form from './FormContainer'; export default Form;
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.createFraction = void 0; var _factory = require("../../../utils/factory"); var _collection = require("../../../utils/collection"); var name = 'fraction'; var dependencies = ['typed', 'Fraction']; var createFraction = /* #__PURE__ */ (0, _factory.factory)(name, dependencies, function (_ref) { var typed = _ref.typed, Fraction = _ref.Fraction; /** * Create a fraction convert a value to a fraction. * * Syntax: * math.fraction(numerator, denominator) * math.fraction({n: numerator, d: denominator}) * math.fraction(matrix: Array | Matrix) Turn all matrix entries * into fractions * * Examples: * * math.fraction(1, 3) * math.fraction('2/3') * math.fraction({n: 2, d: 3}) * math.fraction([0.2, 0.25, 1.25]) * * See also: * * bignumber, number, string, unit * * @param {number | string | Fraction | BigNumber | Array | Matrix} [args] * Arguments specifying the numerator and denominator of * the fraction * @return {Fraction | Array | Matrix} Returns a fraction */ var fraction = typed('fraction', { number: function number(x) { if (!isFinite(x) || isNaN(x)) { throw new Error(x + ' cannot be represented as a fraction'); } return new Fraction(x); }, string: function string(x) { return new Fraction(x); }, 'number, number': function numberNumber(numerator, denominator) { return new Fraction(numerator, denominator); }, "null": function _null(x) { return new Fraction(0); }, BigNumber: function BigNumber(x) { return new Fraction(x.toString()); }, Fraction: function Fraction(x) { return x; // fractions are immutable }, Object: function Object(x) { return new Fraction(x); }, 'Array | Matrix': function ArrayMatrix(x) { return (0, _collection.deepMap)(x, fraction); } }); return fraction; }); exports.createFraction = createFraction;
'use strict'; require('dotenv').config({path: `${__dirname}/../.env`}); const mongoose = require('mongoose'); mongoose.Promise = global.Promise; mongoose.connect(process.env.MONGODB_URI); const userMocks = require('../test/lib/user-mocks'); const appointmentMocks = require ('../test/lib/appointment-mocks'); function populateStuff(){ userMocks.call(this, (err) => { if (err) return console.log(err); appointmentMocks.call(this, (err)=>{ if (err) return console.log(err); mongoose.disconnect(); }); }); } populateStuff.call({});
/**[@test({ "title": "TruJS.compile._FileObj: string path and data" })]*/ function testFileObj1(arrange, act, assert, module) { var fileObj, path, data, res; arrange(function () { fileObj = module(["TruJS.compile._FileObj", []]); path = "/base/path/file.js"; data = "file data"; }); act(function () { res = fileObj(path, data); }); assert(function (test) { test("res.file should be") .value(res, "file") .equals("file.js"); test("res.name should be") .value(res, "name") .equals("file"); test("res.ext should be") .value(res, "ext") .equals(".js"); test("res.path should be") .value(res, "path") .matches(/[/\\]base[/\\]path[/\\]file[.]js/); test("res.data should be") .value(res, "data") .equals(data); }); } /**[@test({ "title": "TruJS.compile._FileObj: path object w/ file property and data" })]*/ function testFileObj2(arrange, act, assert, module) { var fileObj, path, data, res, nodePath; arrange(function () { nodePath = module(".nodePath"); fileObj = module(["TruJS.compile._FileObj", []]); path = nodePath.parse("/base/path/file.js"); path.file = path.base; delete path.base; data = "file data"; }); act(function () { res = fileObj(path, data); }); assert(function (test) { test("res.file should be") .value(res, "file") .equals("file.js"); test("res.name should be") .value(res, "name") .equals("file"); test("res.ext should be") .value(res, "ext") .equals(".js"); test("res.path should be") .value(res, "path") .matches(/[/\\]base[/\\]path[/\\]file[.]js/); test("res.data should be") .value(res, "data") .equals(data); }); } /**[@test({ "title": "TruJS.compile._FileObj: dir, name, ext empty string" })]*/ function testFileObj2(arrange, act, assert, module) { var fileObj, path, data, res, nodePath; arrange(function () { nodePath = module(".nodePath"); fileObj = module(["TruJS.compile._FileObj", []]); path = nodePath.parse("/base/path/file.js"); path.ext = ""; path.name = ""; path.dir = ""; path.path = "/base/path/file.js"; data = "file data"; }); act(function () { res = fileObj(path, data); }); assert(function (test) { test("res.file should be") .value(res, "file") .equals("file.js"); test("res.name should be") .value(res, "name") .equals("file"); test("res.ext should be") .value(res, "ext") .equals(".js"); test("res.path should be") .value(res, "path") .matches(/[/\\]base[/\\]path[/\\]file[.]js/); test("res.data should be") .value(res, "data") .equals(data); }); }
// Copyright (c) 2012 Ecma International. All rights reserved. // Ecma International makes this code available under the terms and conditions set // forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the // "Use Terms"). Any redistribution of this code must retain the above // copyright and this notice and otherwise comply with the Use Terms. /*--- es5id: 15.2.3.5-4-220 description: > Object.create - 'writable' property of one property in 'Properties' is a Number object (8.10.5 step 6.b) includes: [runTestCase.js] ---*/ function testcase() { var newObj = Object.create({}, { prop: { writable: new Number() } }); var hasProperty = newObj.hasOwnProperty("prop"); newObj.prop = 121; return hasProperty && newObj.prop === 121; } runTestCase(testcase);
/** * Main file * Pokemon Showdown - http://pokemonshowdown.com/ * * This is the main Pokemon Showdown app, and the file you should be * running to start Pokemon Showdown if you're using it normally. * * This file sets up our SockJS server, which handles communication * between users and your server, and also sets up globals. You can * see details in their corresponding files, but here's an overview: * * Users - from users.js * * Most of the communication with users happens in users.js, we just * forward messages between the sockets.js and users.js. * * Rooms - from rooms.js * * Every chat room and battle is a room, and what they do is done in * rooms.js. There's also a global room which every user is in, and * handles miscellaneous things like welcoming the user. * * Tools - from tools.js * * Handles getting data about Pokemon, items, etc. * * * Simulator - from simulator.js * * Used to access the simulator itself. * * CommandParser - from command-parser.js * * Parses text commands like /me * * Sockets - from sockets.js * * Used to abstract out network connections. sockets.js handles * the actual server and connection set-up. * * @license MIT license */ /********************************************************* * Make sure we have everything set up correctly *********************************************************/ // Make sure our dependencies are available, and install them if they // aren't function runNpm(command) { if (require.main !== module) throw new Error("Dependencies unmet"); command = 'npm ' + command + ' && ' + process.execPath + ' app.js'; console.log('Running `' + command + '`...'); require('child_process').spawn('sh', ['-c', command], {stdio: 'inherit', detached: true}); process.exit(0); } var isLegacyEngine = !(''.includes); var fs = require('fs'); var path = require('path'); try { require('sugar'); if (isLegacyEngine) require('es6-shim'); } catch (e) { runNpm('install --production'); } if (isLegacyEngine && !(''.includes)) { runNpm('update --production'); } /********************************************************* * Load configuration *********************************************************/ try { global.Config = require('./config/config.js'); } catch (err) { if (err.code !== 'MODULE_NOT_FOUND') throw err; // Copy it over synchronously from config-example.js since it's needed before we can start the server console.log("config.js doesn't exist - creating one with default settings..."); fs.writeFileSync(path.resolve(__dirname, 'config/config.js'), fs.readFileSync(path.resolve(__dirname, 'config/config-example.js')) ); global.Config = require('./config/config.js'); } if (Config.watchconfig) { fs.watchFile(path.resolve(__dirname, 'config/config.js'), function (curr, prev) { if (curr.mtime <= prev.mtime) return; try { delete require.cache[require.resolve('./config/config.js')]; global.Config = require('./config/config.js'); if (global.Users) Users.cacheGroupData(); console.log('Reloaded config/config.js'); } catch (e) {} }); } // Autoconfigure the app when running in cloud hosting environments: try { var cloudenv = require('cloud-env'); Config.bindaddress = cloudenv.get('IP', Config.bindaddress || ''); Config.port = cloudenv.get('PORT', Config.port); } catch (e) {} if (require.main === module && process.argv[2] && parseInt(process.argv[2])) { Config.port = parseInt(process.argv[2]); Config.ssl = null; } global.ResourceMonitor = { connections: {}, connectionTimes: {}, battles: {}, battleTimes: {}, battlePreps: {}, battlePrepTimes: {}, networkUse: {}, networkCount: {}, cmds: {}, cmdsTimes: {}, cmdsTotal: {lastCleanup: Date.now(), count: 0}, teamValidatorChanged: 0, teamValidatorUnchanged: 0, /** * Counts a connection. Returns true if the connection should be terminated for abuse. */ log: function (text) { console.log(text); if (Rooms.get('staff')) { Rooms.get('staff').add('||' + text).update(); } }, logHTML: function (text) { console.log(text); if (Rooms.get('staff')) { Rooms.get('staff').add('|html|' + text).update(); } }, countConnection: function (ip, name) { var now = Date.now(); var duration = now - this.connectionTimes[ip]; name = (name ? ': ' + name : ''); if (ip in this.connections && duration < 30 * 60 * 1000) { this.connections[ip]++; if (this.connections[ip] < 500 && duration < 5 * 60 * 1000 && this.connections[ip] % 60 === 0) { this.log('[ResourceMonitor] IP ' + ip + ' has connected ' + this.connections[ip] + ' times in the last ' + duration.duration() + name); } else if (this.connections[ip] < 500 && this.connections[ip] % 120 === 0) { this.log('[ResourceMonitor] IP ' + ip + ' has connected ' + this.connections[ip] + ' times in the last ' + duration.duration() + name); } else if (this.connections[ip] === 500) { this.log('[ResourceMonitor] IP ' + ip + ' has been banned for connection flooding (' + this.connections[ip] + ' times in the last ' + duration.duration() + name + ')'); return true; } else if (this.connections[ip] > 500) { if (this.connections[ip] % 500 === 0) { var c = this.connections[ip] / 500; if (c < 5 || c % 2 === 0 && c < 10 || c % 5 === 0) { this.log('[ResourceMonitor] Banned IP ' + ip + ' has connected ' + this.connections[ip] + ' times in the last ' + duration.duration() + name); } } return true; } } else { this.connections[ip] = 1; this.connectionTimes[ip] = now; } }, /** * Counts a battle. Returns true if the connection should be terminated for abuse. */ countBattle: function (ip, name) { var now = Date.now(); var duration = now - this.battleTimes[ip]; name = (name ? ': ' + name : ''); if (ip in this.battles && duration < 30 * 60 * 1000) { this.battles[ip]++; if (duration < 5 * 60 * 1000 && this.battles[ip] % 15 === 0) { this.log('[ResourceMonitor] IP ' + ip + ' has battled ' + this.battles[ip] + ' times in the last ' + duration.duration() + name); } else if (this.battles[ip] % 75 === 0) { this.log('[ResourceMonitor] IP ' + ip + ' has battled ' + this.battles[ip] + ' times in the last ' + duration.duration() + name); } } else { this.battles[ip] = 1; this.battleTimes[ip] = now; } }, /** * Counts battle prep. Returns true if too much */ countPrepBattle: function (ip) { var now = Date.now(); var duration = now - this.battlePrepTimes[ip]; if (ip in this.battlePreps && duration < 3 * 60 * 1000) { this.battlePreps[ip]++; if (this.battlePreps[ip] > 6) { return true; } } else { this.battlePreps[ip] = 1; this.battlePrepTimes[ip] = now; } }, /** * data */ countNetworkUse: function (size) { if (this.activeIp in this.networkUse) { this.networkUse[this.activeIp] += size; this.networkCount[this.activeIp]++; } else { this.networkUse[this.activeIp] = size; this.networkCount[this.activeIp] = 1; } }, writeNetworkUse: function () { var buf = ''; for (var i in this.networkUse) { buf += '' + this.networkUse[i] + '\t' + this.networkCount[i] + '\t' + i + '\n'; } fs.writeFile(path.resolve(__dirname, 'logs/networkuse.tsv'), buf); }, clearNetworkUse: function () { this.networkUse = {}; this.networkCount = {}; }, /** * Counts roughly the size of an object to have an idea of the server load. */ sizeOfObject: function (object) { var objectList = []; var stack = [object]; var bytes = 0; while (stack.length) { var value = stack.pop(); if (typeof value === 'boolean') { bytes += 4; } else if (typeof value === 'string') { bytes += value.length * 2; } else if (typeof value === 'number') { bytes += 8; } else if (typeof value === 'object' && objectList.indexOf(value) < 0) { objectList.push(value); for (var i in value) stack.push(value[i]); } } return bytes; }, /** * Controls the amount of times a cmd command is used */ countCmd: function (ip, name) { var now = Date.now(); var duration = now - this.cmdsTimes[ip]; name = (name ? ': ' + name : ''); if (!this.cmdsTotal) this.cmdsTotal = {lastCleanup: 0, count: 0}; if (now - this.cmdsTotal.lastCleanup > 60 * 1000) { this.cmdsTotal.count = 0; this.cmdsTotal.lastCleanup = now; } this.cmdsTotal.count++; if (ip in this.cmds && duration < 60 * 1000) { this.cmds[ip]++; if (duration < 60 * 1000 && this.cmds[ip] % 5 === 0) { if (this.cmds[ip] >= 3) { if (this.cmds[ip] % 30 === 0) this.log('CMD command from ' + ip + ' blocked for ' + this.cmds[ip] + 'th use in the last ' + duration.duration() + name); return true; } this.log('[ResourceMonitor] IP ' + ip + ' has used CMD command ' + this.cmds[ip] + ' times in the last ' + duration.duration() + name); } else if (this.cmds[ip] % 15 === 0) { this.log('CMD command from ' + ip + ' blocked for ' + this.cmds[ip] + 'th use in the last ' + duration.duration() + name); return true; } } else if (this.cmdsTotal.count > 8000) { // One CMD check per user per minute on average (to-do: make this better) this.log('CMD command for ' + ip + ' blocked because CMD has been used ' + this.cmdsTotal.count + ' times in the last minute.'); return true; } else { this.cmds[ip] = 1; this.cmdsTimes[ip] = now; } } }; /********************************************************* * Set up most of our globals *********************************************************/ /** * Converts anything to an ID. An ID must have only lowercase alphanumeric * characters. * If a string is passed, it will be converted to lowercase and * non-alphanumeric characters will be stripped. * If an object with an ID is passed, its ID will be returned. * Otherwise, an empty string will be returned. */ global.toId = function (text) { if (text && text.id) { text = text.id; } else if (text && text.userid) { text = text.userid; } if (typeof text !== 'string' && typeof text !== 'number') return ''; return ('' + text).toLowerCase().replace(/[^a-z0-9]+/g, ''); }; global.Tools = require('./tools.js').includeFormats(); global.LoginServer = require('./loginserver.js'); global.Users = require('./users.js'); global.Rooms = require('./rooms.js'); // Generate and cache the format list. Rooms.global.formatListText = Rooms.global.getFormatListText(); delete process.send; // in case we're a child process global.Verifier = require('./verifier.js'); global.CommandParser = require('./command-parser.js'); global.Simulator = require('./simulator.js'); global.Tournaments = require('./tournaments'); try { global.Dnsbl = require('./dnsbl.js'); } catch (e) { global.Dnsbl = {query:function () {}}; } global.Cidr = require('./cidr.js'); if (Config.crashguard) { // graceful crash - allow current battles to finish before restarting var lastCrash = 0; process.on('uncaughtException', function (err) { var dateNow = Date.now(); var quietCrash = require('./crashlogger.js')(err, 'The main process'); quietCrash = quietCrash || ((dateNow - lastCrash) <= 1000 * 60 * 5); lastCrash = Date.now(); if (quietCrash) return; var stack = ("" + err.stack).escapeHTML().split("\n").slice(0, 2).join("<br />"); if (Rooms.lobby) { Rooms.lobby.addRaw('<div class="broadcast-red"><b>THE SERVER HAS CRASHED:</b> ' + stack + '<br />Please restart the server.</div>'); Rooms.lobby.addRaw('<div class="broadcast-red">You will not be able to talk in the lobby or start new battles until the server restarts.</div>'); } Config.modchat = 'crash'; Rooms.global.lockdown = true; }); } /********************************************************* * Start networking processes to be connected to *********************************************************/ global.Sockets = require('./sockets.js'); /********************************************************* * Set up our last global *********************************************************/ global.TeamValidator = require('./team-validator.js'); // load ipbans at our leisure fs.readFile(path.resolve(__dirname, 'config/ipbans.txt'), function (err, data) { if (err) return; data = ('' + data).split("\n"); var rangebans = []; for (var i = 0; i < data.length; i++) { data[i] = data[i].split('#')[0].trim(); if (!data[i]) continue; if (data[i].includes('/')) { rangebans.push(data[i]); } else if (!Users.bannedIps[data[i]]) { Users.bannedIps[data[i]] = '#ipban'; } } Users.checkRangeBanned = Cidr.checker(rangebans); }); /********************************************************* * Start up the REPL server *********************************************************/ require('./repl.js').start('app', function (cmd) { return eval(cmd); });
var classKalman__RBPF__BS = [ [ "Kalman_RBPF_BS", "classKalman__RBPF__BS.html#aafe2ff44ff6a1b12f5843d4596e0fa13", null ], [ "~Kalman_RBPF_BS", "classKalman__RBPF__BS.html#addf3730ab56740f7247835aaa62c018c", null ], [ "filter", "classKalman__RBPF__BS.html#a195efd6d06215aa66defda0bb5a958e4", null ], [ "fSamp", "classKalman__RBPF__BS.html#ae18fefa813cfcb43c3c7faae859fb9a9", null ], [ "getLogCondLike", "classKalman__RBPF__BS.html#a1c1e6a397dffee83dca8d98b4f174238", null ], [ "initKalmanMean", "classKalman__RBPF__BS.html#aad62ee3220c93d14fa6983013f0a1524", null ], [ "initKalmanVar", "classKalman__RBPF__BS.html#af7bde76f73af8af1b324d2da8fa7a652", null ], [ "muSamp", "classKalman__RBPF__BS.html#a7bee94069af44372af5f862219a9d9bd", null ], [ "updateKalman", "classKalman__RBPF__BS.html#a5c16d09d4111c6b16f6ddf13df3a43f5", null ] ];
import partial from 'array.partial' const identity = c => c export default (node, childProp = 'children', childSelector = identity) => partial(node[childProp], c => childSelector(c).checked) || node[childProp].some(c => childSelector(c).partial)
/* */ (function(process) { var ImportInliner = require('./imports/inliner'); var rebaseUrls = require('./urls/rebase'); var tokenize = require('./tokenizer/tokenize'); var simpleOptimize = require('./selectors/simple'); var advancedOptimize = require('./selectors/advanced'); var simpleStringify = require('./stringifier/simple'); var sourceMapStringify = require('./stringifier/source-maps'); var CommentsProcessor = require('./text/comments-processor'); var ExpressionsProcessor = require('./text/expressions-processor'); var FreeTextProcessor = require('./text/free-text-processor'); var UrlsProcessor = require('./text/urls-processor'); var Compatibility = require('./utils/compatibility'); var InputSourceMapTracker = require('./utils/input-source-map-tracker'); var SourceTracker = require('./utils/source-tracker'); var SourceReader = require('./utils/source-reader'); var Validator = require('./properties/validator'); var fs = require('fs'); var path = require('path'); var url = require('url'); var override = require('./utils/object').override; var DEFAULT_TIMEOUT = 5000; var CleanCSS = module.exports = function CleanCSS(options) { options = options || {}; this.options = { advanced: undefined === options.advanced ? true : !!options.advanced, aggressiveMerging: undefined === options.aggressiveMerging ? true : !!options.aggressiveMerging, benchmark: options.benchmark, compatibility: new Compatibility(options.compatibility).toOptions(), debug: options.debug, explicitRoot: !!options.root, explicitTarget: !!options.target, inliner: options.inliner || {}, keepBreaks: options.keepBreaks || false, keepSpecialComments: 'keepSpecialComments' in options ? options.keepSpecialComments : '*', mediaMerging: undefined === options.mediaMerging ? true : !!options.mediaMerging, processImport: undefined === options.processImport ? true : !!options.processImport, processImportFrom: importOptionsFrom(options.processImportFrom), rebase: undefined === options.rebase ? true : !!options.rebase, relativeTo: options.relativeTo, restructuring: undefined === options.restructuring ? true : !!options.restructuring, root: options.root || process.cwd(), roundingPrecision: options.roundingPrecision, semanticMerging: undefined === options.semanticMerging ? false : !!options.semanticMerging, shorthandCompacting: undefined === options.shorthandCompacting ? true : !!options.shorthandCompacting, sourceMap: options.sourceMap, sourceMapInlineSources: !!options.sourceMapInlineSources, target: !options.target || missingDirectory(options.target) || presentDirectory(options.target) ? options.target : path.dirname(options.target) }; this.options.inliner.timeout = this.options.inliner.timeout || DEFAULT_TIMEOUT; this.options.inliner.request = override(proxyOptionsFrom(process.env.HTTP_PROXY || process.env.http_proxy), this.options.inliner.request || {}); }; function importOptionsFrom(rules) { return undefined === rules ? ['all'] : rules; } function missingDirectory(filepath) { return !fs.existsSync(filepath) && !/\.css$/.test(filepath); } function presentDirectory(filepath) { return fs.existsSync(filepath) && fs.statSync(filepath).isDirectory(); } function proxyOptionsFrom(httpProxy) { return httpProxy ? { hostname: url.parse(httpProxy).hostname, port: parseInt(url.parse(httpProxy).port) } : {}; } CleanCSS.prototype.minify = function(data, callback) { var context = { stats: {}, errors: [], warnings: [], options: this.options, debug: this.options.debug, localOnly: !callback, sourceTracker: new SourceTracker(), validator: new Validator(this.options.compatibility) }; if (context.options.sourceMap) context.inputSourceMapTracker = new InputSourceMapTracker(context); context.sourceReader = new SourceReader(context, data); data = context.sourceReader.toString(); if (context.options.processImport || data.indexOf('@shallow') > 0) { var runner = callback ? process.nextTick : function(callback) { return callback(); }; return runner(function() { return new ImportInliner(context).process(data, { localOnly: context.localOnly, imports: context.options.processImportFrom, whenDone: runMinifier(callback, context) }); }); } else { return runMinifier(callback, context)(data); } }; function runMinifier(callback, context) { function whenSourceMapReady(data) { data = context.options.debug ? minifyWithDebug(context, data) : minify(context, data); data = withMetadata(context, data); return callback ? callback.call(null, context.errors.length > 0 ? context.errors : null, data) : data; } return function(data) { if (context.options.sourceMap) { return context.inputSourceMapTracker.track(data, function() { if (context.options.sourceMapInlineSources) { return context.inputSourceMapTracker.resolveSources(function() { return whenSourceMapReady(data); }); } else { return whenSourceMapReady(data); } }); } else { return whenSourceMapReady(data); } }; } function withMetadata(context, data) { data.stats = context.stats; data.errors = context.errors; data.warnings = context.warnings; return data; } function minifyWithDebug(context, data) { var startedAt = process.hrtime(); context.stats.originalSize = context.sourceTracker.removeAll(data).length; data = minify(context, data); var elapsed = process.hrtime(startedAt); context.stats.timeSpent = ~~(elapsed[0] * 1e3 + elapsed[1] / 1e6); context.stats.efficiency = 1 - data.styles.length / context.stats.originalSize; context.stats.minifiedSize = data.styles.length; return data; } function benchmark(runner) { return function(processor, action) { var name = processor.constructor.name + '#' + action; var start = process.hrtime(); runner(processor, action); var itTook = process.hrtime(start); console.log('%d ms: ' + name, 1000 * itTook[0] + itTook[1] / 1000000); }; } function minify(context, data) { var options = context.options; var commentsProcessor = new CommentsProcessor(context, options.keepSpecialComments, options.keepBreaks, options.sourceMap); var expressionsProcessor = new ExpressionsProcessor(options.sourceMap); var freeTextProcessor = new FreeTextProcessor(options.sourceMap); var urlsProcessor = new UrlsProcessor(context, options.sourceMap, options.compatibility.properties.urlQuotes); var stringify = options.sourceMap ? sourceMapStringify : simpleStringify; var run = function(processor, action) { data = typeof processor == 'function' ? processor(data) : processor[action](data); }; if (options.benchmark) run = benchmark(run); run(commentsProcessor, 'escape'); run(expressionsProcessor, 'escape'); run(urlsProcessor, 'escape'); run(freeTextProcessor, 'escape'); function restoreEscapes(data, prefixContent) { data = freeTextProcessor.restore(data, prefixContent); data = urlsProcessor.restore(data); data = options.rebase ? rebaseUrls(data, context) : data; data = expressionsProcessor.restore(data); return commentsProcessor.restore(data); } var tokens = tokenize(data, context); simpleOptimize(tokens, options, context); if (options.advanced) advancedOptimize(tokens, options, context, true); return stringify(tokens, options, restoreEscapes, context.inputSourceMapTracker); } })(require('process'));
/*! * Angular Material Design * https://github.com/angular/material * @license MIT * v1.0.0-rc7-master-80a8929 */ !function(t,i,n){"use strict";i.module("material.components.backdrop",["material.core"]).directive("mdBackdrop",["$mdTheming","$animate","$rootElement","$window","$log","$$rAF","$document",function(t,i,n,e,o,r,a){function p(p,c,s){var m=e.getComputedStyle(a[0].body);if("fixed"==m.position){var l=parseInt(m.height,10)+Math.abs(parseInt(m.top,10));c.css({height:l+"px"})}i.pin&&i.pin(c,n),r(function(){var i=c.parent()[0];if(i){"BODY"==i.nodeName&&c.css({position:"fixed"});var n=e.getComputedStyle(i);"static"==n.position&&o.warn(d)}t.inherit(c,c.parent())})}var d="<md-backdrop> may not work properly in a scrolled, static-positioned parent container.";return{restrict:"E",link:p}}])}(window,window.angular);
(function() { 'use strict'; angular.module('ShoppingList', ['ui.router', 'spinner']); })();
'use strict'; /* jshint ignore:start */ /** * This code was generated by * \ / _ _ _| _ _ * | (_)\/(_)(_|\/| |(/_ v1.0.0 * / / */ /* jshint ignore:end */ var _ = require('lodash'); /* jshint ignore:line */ var Holodeck = require('../../../../holodeck'); /* jshint ignore:line */ var Request = require( '../../../../../../lib/http/request'); /* jshint ignore:line */ var Response = require( '../../../../../../lib/http/response'); /* jshint ignore:line */ var RestException = require( '../../../../../../lib/base/RestException'); /* jshint ignore:line */ var Twilio = require('../../../../../../lib'); /* jshint ignore:line */ var client; var holodeck; describe('Usage', function() { beforeEach(function() { holodeck = new Holodeck(); client = new Twilio('ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', 'AUTHTOKEN', { httpClient: holodeck }); }); it('should generate valid fetch request', function() { holodeck.mock(new Response(500, '{}')); var promise = client.preview.wireless.sims('DEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') .usage().fetch(); promise = promise.then(function() { throw new Error('failed'); }, function(error) { expect(error.constructor).toBe(RestException.prototype.constructor); }); promise.done(); var solution = {simSid: 'DEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'}; var url = _.template('https://preview.twilio.com/wireless/Sims/<%= simSid %>/Usage')(solution); holodeck.assertHasRequest(new Request({ method: 'GET', url: url })); } ); it('should generate valid fetch response', function() { var body = JSON.stringify({ 'account_sid': 'ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'commands_costs': {}, 'commands_usage': {}, 'data_costs': {}, 'data_usage': {}, 'sim_unique_name': 'sim_unique_name', 'sim_sid': 'DEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'period': {}, 'url': 'https://preview.twilio.com/wireless/Sims/DEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Usage' }); holodeck.mock(new Response(200, body)); var promise = client.preview.wireless.sims('DEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') .usage().fetch(); promise = promise.then(function(response) { expect(response).toBeDefined(); }, function() { throw new Error('failed'); }); promise.done(); } ); });
import React from 'react'; import PropTypes from 'prop-types'; type Props = { data: PropTypes.object.isRequired, xScale: PropTypes.func.isRequired, yScale: PropTypes.func.isRequired, colorScale: PropTypes.func.isRequired } export default ({ data, xScale, yScale, colorScale }: Props) => { return ( <g className="horizontal-bar">> <rect y={yScale(data.name)} height={yScale.rangeBand()} x={0} width={xScale(data.value)} style={{ fill: `${colorScale(data.name)}`}} /> <text className="horizontal-bar-text" y={yScale(data.name) + yScale.rangeBand() / 2 + 4} x={xScale(data.value) + 25} textAnchor="end">{data.value}</text> </g> ); };
'use strict'; //angular.module('myApp.view2', ['ngRoute']) // //.config(['$routeProvider', function($routeProvider) { // $routeProvider.when('/view2', { // templateUrl: 'view2/view2.html', // controller: 'View2Ctrl' // }); //}]) app.controller('View2Ctrl', ['$scope','$http','$modal','$localStorage','Book',function($scope,$http,$modal,$localStorage,$Book) { console.log($Book); console.log($modal); }]);